The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(agent): carry resolved routes through run context
Steven Enamakela0faec831dc2
diff --git a/crates/openhuman-core/src/agent/bus.rs b/crates/openhuman-core/src/agent/bus.rsindex 003a86868c..c257cf9580 100644--- a/crates/openhuman-core/src/agent/bus.rs+++ b/crates/openhuman-core/src/agent/bus.rs@@ -22,9 +22,6 @@ use tokio::sync::mpsc;use crate::agent::messages::ChatMessage;use crate::agent::progress::AgentProgress;-use crate::agent::tinyagents::{- current_resolved_provider_route, with_resolved_provider_route_scope,-};use crate::agent::turn_origin::{self, AgentTurnOrigin};use crate::config::MultimodalConfig;use crate::core::bus::BUS;@@ -291,43 +288,41 @@ async fn handle_agent_run_turn(req: AgentTurnRequest) -> Result<AgentTurnResponschannel_name,target_agent_id.as_deref().unwrap_or("root"));- let (text, resolved_route) = with_resolved_provider_route_scope(async {- let text = turn_origin::with_origin(- origin,- with_file_state_agent_id(- file_state_id,- with_current_sandbox_mode(sandbox_mode, async {- // Channel/CLI turns run through the tinyagents harness- // (issue #4249); the legacy `run_tool_call_loop` is removed.- // `on_progress` mirrors the harness event stream (tool- // timeline, text deltas, cost footer) — production channel- // dispatch always supplies it and now expects it live.- // `on_delta` (raw Sender<String>) is superseded by- // `on_progress` text deltas, so it's intentionally unused.- let _ = (&provider_name, silent, &channel_name, on_delta);- run_channel_turn_via_graph(- turn_model_source.clone(),- &mut history,- tools_registry.clone(),- extra_tools,- visible_tool_names.as_ref(),- &model,- temperature,- max_tool_iterations,- multimodal.clone(),- multimodal_files.clone(),- on_progress,- )- .await- }),- ),- )- .await- .map_err(|e| e.to_string())?;- let resolved_route = current_resolved_provider_route();- Ok::<_, String>((text, resolved_route))- })- .await?;+ let outcome = turn_origin::with_origin(+ origin,+ with_file_state_agent_id(+ file_state_id,+ with_current_sandbox_mode(sandbox_mode, async {+ // Channel/CLI turns run through the tinyagents harness+ // (issue #4249); the legacy `run_tool_call_loop` is removed.+ // `on_progress` mirrors the harness event stream (tool+ // timeline, text deltas, cost footer) — production channel+ // dispatch always supplies it and now expects it live.+ // `on_delta` (raw Sender<String>) is superseded by+ // `on_progress` text deltas, so it's intentionally unused.+ let _ = (&provider_name, silent, &channel_name, on_delta);+ run_channel_turn_via_graph(+ turn_model_source.clone(),+ &mut history,+ tools_registry.clone(),+ extra_tools,+ visible_tool_names.as_ref(),+ &model,+ temperature,+ max_tool_iterations,+ multimodal.clone(),+ multimodal_files.clone(),+ on_progress,+ )+ .await+ }),+ ),+ )+ .await+ .map_err(|e| e.to_string())?;++ let text = outcome.text;+ let resolved_route = outcome.resolved_route;tracing::debug!(channel = %channel_name,diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rsindex 95ef9f67ca..c7b08ce0d0 100644--- a/crates/openhuman-core/src/agent/harness/graph.rs+++ b/crates/openhuman-core/src/agent/harness/graph.rs@@ -39,9 +39,10 @@ use crate::agent::tinyagents::TurnModelSource;use crate::config::{MultimodalConfig, MultimodalFileConfig};use tinytools::Tool;-/// Drive a channel/CLI turn on the graph engine. Returns the final assistant-/// text. When `on_progress` is `Some`, the run streams and mirrors progress-/// onto `AgentProgress`; pass `None` for a fire-and-forget final-text turn.+/// Drive a channel/CLI turn on the graph engine. Returns the explicit turn+/// outcome, including the concrete route selected by the model runtime. When+/// `on_progress` is `Some`, the run streams and mirrors progress onto+/// `AgentProgress`; pass `None` for a fire-and-forget final-text turn.#[allow(clippy::too_many_arguments)]pub(crate) async fn run_channel_turn_via_graph(source: TurnModelSource,@@ -55,7 +56,7 @@ pub(crate) async fn run_channel_turn_via_graph(multimodal: MultimodalConfig,multimodal_files: MultimodalFileConfig,on_progress: Option<Sender<AgentProgress>>,-) -> Result<String> {+) -> Result<crate::agent::tinyagents::TinyagentsTurnOutcome> {let extra_arc = Arc::new(extra_tools);// The callable set is the visibility whitelist. The runner advertises each via@@ -188,7 +189,7 @@ pub(crate) async fn run_channel_turn_via_graph(// that the agent had asked anything.history.push(ChatMessage::assistant(outcome.text.clone()));}- Ok(outcome.text)+ Ok(outcome)}#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/harness/graph_tests.rs b/crates/openhuman-core/src/agent/harness/graph_tests.rsindex 77cd7429a0..d6b09aa56b 100644--- a/crates/openhuman-core/src/agent/harness/graph_tests.rs+++ b/crates/openhuman-core/src/agent/harness/graph_tests.rs@@ -41,6 +41,8 @@ async fn channel_turn_runs_through_the_graph() {resolved_model: None,continue_turn: None,served_from_cache: false,+ correlation: None,+ resolved_route: None,},ModelResponse::assistant("channel done"),]));@@ -62,7 +64,7 @@ async fn channel_turn_runs_through_the_graph() {).await.expect("channel graph turn runs");- assert_eq!(text, "channel done");+ assert_eq!(text.text, "channel done");assert!(history.iter().any(|m| m.content.contains("pong")));}@@ -98,6 +100,8 @@ async fn channel_turn_pauses_on_ask_user_clarification() {resolved_model: None,continue_turn: None,served_from_cache: false,+ correlation: None,+ resolved_route: None,},ModelResponse::assistant("built it without asking"),]));@@ -121,7 +125,7 @@ async fn channel_turn_pauses_on_ask_user_clarification() {.expect("channel graph turn runs");assert_eq!(- text, "Which three sources?",+ text.text, "Which three sources?","the turn must end on the question; got the model's own follow-up, so the pause did not fire");let last = history.last().expect("history is not empty");diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.mdindex fe48c1edbb..40151b6565 100644--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@ -7,7 +7,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../- Assemble a per-turn harness (`assemble_turn_harness` in `harness_assembly.rs`): register the turn's `ChatModel`s, every shared tool, and the full middleware stack, then drive it via `AgentHarness::invoke_stream_in_context` (`turn_runner.rs`).- Convert between OpenHuman and crate types: tiered `ChatModel` bundles from `(role, config)` (`turn_models.rs`, `model.rs`), `Tool` → crate `Tool` (`tools.rs`, `convert.rs`), and `ChatMessage`/`ConversationMessage` ↔ crate `Message` via `crate::agent::message_convert`.- Enforce cross-cutting policy as harness middleware: approval/security gating, tool policy and CLI/RPC-only denial, cost budgets, context compaction/summarization, credential scrubbing, malformed-argument recovery, and the repeated-tool-failure circuit breaker (`middleware*.rs`).-- Route workloads to model tiers and record the resolved provider/model for audit (`routes.rs`, `resolved_route.rs`).+- Route workloads to model tiers and record the resolved provider/model for audit (`routes.rs`, canonical TinyInference response metadata).- Make turns durable and replayable: a JSONL event journal plus status store (`journal.rs`), a startup sweep for orphaned runs (`reaper.rs`), and a read-only RPC surface over both (`replay/`).- Provide graph-layer helpers for multi-stage sub-agent orchestration (`orchestration.rs`, `delegation.rs`) and expose graph structure for debugging (`topology.rs`).- Host adapters (`host/`) for the crate's ten host-capability traits. Not yet wired into the live turn path; see [Host adapters](#host-adapters) below.@@ -16,7 +16,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../| File / group | Role || --- | --- |-| `mod.rs` | Module root: declares submodules and re-exports (`TurnContextMiddleware`, `HandoffConfig`, `TranscriptSnapshotSink`, `SubagentScope`, `resolved_route::*`, `ToolPolicyEnforcement`, `TinyagentsTurnOutcome`, `TurnModelSource`/`TurnModels`, `run_turn_via_tinyagents_shared`). |+| `mod.rs` | Module root: declares submodules and re-exports (`TurnContextMiddleware`, `HandoffConfig`, `TranscriptSnapshotSink`, `SubagentScope`, `ToolPolicyEnforcement`, `TinyagentsTurnOutcome`, `TurnModelSource`/`TurnModels`, `run_turn_via_tinyagents_shared`). || `turn_policy.rs` | `ToolPolicyEnforcement`, run-policy construction, and wall-clock-ceiling helpers (`agent_turn_wall_clock_ms` and friends). || `turn_runner.rs` | `run_turn_via_tinyagents_shared`, the single entry point every production caller uses, plus the `#[cfg(test)]`-only `run_turn_via_tinyagents`. || `turn_models.rs` | `TurnModels` (primary + tier routes + summarizer) and `TurnModelSource`, whose `build`/`build_summarizer` construct crate-native models from `(role, config)` via `build_turn_models_crate`. |@@ -30,11 +30,10 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../| `journal.rs` | `TurnJournal` and `FileStatusStore`: a crate `StoreEventJournal` over a JSONL append store plus a `HarnessStatusStore` writer under `{workspace}/tinyagents_store`. Attached alongside the live `observability` bridge as an independent `EventSink` subscriber, wrapped in `RedactingSink`; best-effort and non-fatal. || `reaper.rs` | `reap_orphaned_runs`: startup sweep that marks non-terminal runs `Cancelled` in the durable status store. The only writer over the status seam that `replay/` reads. || `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware`. `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware` (adjacent-repeat streaks plus a run-wide `(call, result)` recurrence ledger) and `RepeatEvictionObserver` (registered last; resets the ledger when compaction evicts a recorded result, #6275). `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware`. `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |-| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`, `RouteRecordingModel`. |+| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. || `convert.rs` | `spec_to_schema`: OpenHuman `ToolSpec` → crate `ToolSchema`. Message conversion lives in `crate::agent::message_convert`. || `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` | `WORKLOAD_ROUTE_TIERS` (the tier inventory projected into the model registry), `RequiredCapabilitiesMiddleware`, `FallbackObserverMiddleware`, `UsageCarryMiddleware`, and the per-model fallback policy. |-| `resolved_route.rs` | Task-local slot recording the provider/model that actually served the latest call (`ResolvedProviderRoute`, `with_resolved_provider_route_scope`, `record_resolved_provider_route`). || `topology.rs` | `all_graph_topologies`: behaviour-free `GraphTopology` exports of every custom OpenHuman graph for debug/inspection. || `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. `cap_pauser.rs`: `CapPauser` and `SubagentScope`. `graph_tracing.rs`: `GraphTracingSink`. || `host/steering.rs` | OpenHuman's steering allowlist and the shared `SteeringRegistry` for detached sub-agents. Task primitives are imported directly from `tinyagents_graph::orchestration`. |@@ -59,7 +58,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).-- `resolved_route::*`: read by `agent/bus.rs` after a turn to persist the provider/model actually used.+- `routes::ResolvedRouteMiddleware`: records canonical response metadata in the explicit run context; `TinyagentsTurnOutcome` carries it to the bus.- `thread_context::*`, `todos::*`, `host::*` (all ten `OpenHuman*` adapter structs), and `TurnModelSource`.Within the crate the entry point is `run_turn_via_tinyagents_shared` (`pub(crate)`); `run_turn_via_tinyagents` is `#[cfg(test)]` only.@@ -91,7 +90,7 @@ Responses project the crate's own `AgentObservation` and `HarnessRunStatus` serd- `agent/harness/graph.rs`: the channel/CLI bus turn route.- `agent/harness/subagent_runner/ops/graph.rs`: the sub-agent spawn route. It and the session route both build their context-window summarizer through `TurnModelSource::build_summarizer`.- `agent/harness/session/builder/setters.rs`, `agent/harness/subagent_runner/ops/{provider,runner}.rs`, `channels/`: construct `TurnModelSource`.-- `agent/bus.rs`: reads `resolved_route` after a turn.+- `agent/bus.rs`: reads `TinyagentsTurnOutcome::resolved_route` after a turn.- `core/all.rs` (replay controllers) and `core/runtime/builder.rs` (`reaper::reap_orphaned_runs`).- `agent/todos/`: `todos::*` stores.- `memory/tools/{recall,store}.rs` and `memory/auto_recall/`: `host::agent_memory::DEFAULT_AGENT_MEMORY_NAMESPACE`.diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex d0a1ce4c24..2226b3e184 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -210,6 +210,12 @@ pub(super) fn assemble_turn_harness(provider_usage_carry.clone(),)));+ // Route audit capture is a typed run-context concern. The canonical+ // TinyInference decorator attached in `turn_models` stamps the successful+ // unary response and the streamed terminal response, and this middleware+ // moves that metadata into the explicit OpenHuman carrier.+ harness.push_model_middleware(Arc::new(routes::ResolvedRouteMiddleware));+// Per-call capability gate (issue #4249, Workstream 02.1): when the turn has// derivable capability needs (today: vision for a `vision-v1` turn), stamp// them onto every `ModelRequest` via `with_required_capabilities` so an unfitdiff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex c27efbcc2d..3e363223c4 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -21,9 +21,9 @@ use crate::agent::harness::turn_dispatch_guard::TurnDispatchState;use crate::agent::harness::turn_subagent_usage::SubagentUsageEntry;use crate::agent::progress::AgentProgress;use crate::agent::stop_hooks::StopHook;-use crate::agent::tinyagents::resolved_route::RouteSlot;use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;use crate::agent::turn_origin::AgentTurnOrigin;+use tinyinference_llm::model::ResolvedModelRoute;/// Explicit OpenHuman data carried by a top-level or child agent run.///@@ -59,8 +59,10 @@ pub struct OpenHumanRunContext {pub spawn_depth: usize,/// This run's subagent usage roll-up; intentionally isolated for children.pub subagent_usage: Arc<Mutex<Vec<SubagentUsageEntry>>>,- /// Provider/model observation for this run; intentionally isolated for children.- pub resolved_route: RouteSlot,+ /// Provider/model/host-route observation for this run, written from the+ /// canonical response metadata by typed model middleware. Intentionally+ /// isolated for children.+ pub(crate) resolved_route: Arc<Mutex<Option<ResolvedModelRoute>>>,/// Cooperative cancellation shared by the complete recursive run tree.pub cancellation: tinyagents_harness::cancel::CancellationToken,/// Thread attached to provider requests and host persistence.@@ -91,9 +93,6 @@ impl OpenHumanRunContext {context.stop_hooks = crate::agent::stop_hooks::current_stop_hooks();context.dispatch = crate::agent::harness::turn_dispatch_guard::current();context.thread_id = crate::agent::tinyagents::thread_context::current_thread_id();- if let Some(slot) = crate::agent::tinyagents::current_route_slot() {- context.resolved_route = slot;- }if let Some(cancellation) = crate::agent::tinyagents::current_run_cancellation() {context.cancellation = cancellation;}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsindex ba6f891b20..8760f40ef3 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -23,9 +23,10 @@ fn child_inherits_tree_handles_but_isolates_observations_and_usage() {parent.thread_id = Some("thread-a".to_string());parent.file_state_agent_id = Some("parent-file-state".to_string());*parent.resolved_route.lock().expect("route lock") =- Some(crate::agent::tinyagents::ResolvedProviderRoute {+ Some(tinyinference_llm::model::ResolvedModelRoute {provider: "provider-a".to_string(),model: "model-a".to_string(),+ route: "chat-v1".to_string(),});let child = parent.child();@@ -68,7 +69,6 @@ async fn snapshots_live_root_scopes_before_child_dispatch() {let root = tempfile::tempdir().expect("workspace");let (progress, _rx) = tokio::sync::mpsc::channel(1);let cancellation = tinyagents_harness::cancel::CancellationToken::new();- let route = std::sync::Arc::new(std::sync::Mutex::new(None));crate::agent::turn_origin::with_origin(crate::agent::turn_origin::AgentTurnOrigin::Cli,@@ -78,39 +78,37 @@ async fn snapshots_live_root_scopes_before_child_dispatch() {progress.clone(),crate::agent::tinyagents::thread_context::with_thread_id("thread-a",- crate::agent::tinyagents::with_route_slot(- route.clone(),- crate::agent::tinyagents::run_cancellation_context::with_run_cancellation(- cancellation.clone(),- crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(- None,- async {- let expected_dispatch =- crate::agent::harness::turn_dispatch_guard::current()- .expect("dispatch scope");- let captured = OpenHumanRunContext::from_current_scopes();- assert!(matches!(- captured.origin,- Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)- ));- assert!(captured.progress.is_some());- assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));- assert_eq!(- captured.workspace.expect("workspace").root,- root.path()- );- assert!(std::sync::Arc::ptr_eq(- captured.dispatch.as_ref().expect("dispatch"),- &expected_dispatch,- ));- assert!(std::sync::Arc::ptr_eq(- &captured.resolved_route,- &route- ));- cancellation.cancel();- assert!(captured.cancellation.is_cancelled());- },- ),+ crate::agent::tinyagents::run_cancellation_context::with_run_cancellation(+ cancellation.clone(),+ crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(+ None,+ async {+ let expected_dispatch =+ crate::agent::harness::turn_dispatch_guard::current()+ .expect("dispatch scope");+ let captured = OpenHumanRunContext::from_current_scopes();+ assert!(matches!(+ captured.origin,+ Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)+ ));+ assert!(captured.progress.is_some());+ assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));+ assert_eq!(+ captured.workspace.expect("workspace").root,+ root.path()+ );+ assert!(std::sync::Arc::ptr_eq(+ captured.dispatch.as_ref().expect("dispatch"),+ &expected_dispatch,+ ));+ assert!(captured+ .resolved_route+ .lock()+ .expect("route lock")+ .is_none());+ cancellation.cancel();+ assert!(captured.cancellation.is_cancelled());+ },),),),diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex d04d9cc8d7..15a93dd53c 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 payload_summarizer;mod policy_denial;pub(crate) mod reaper;pub(crate) mod replay;-pub mod resolved_route;pub(crate) mod retriever;mod routes;pub(crate) mod run_cancellation_context;@@ -76,10 +75,6 @@ pub(crate) use middleware::{TurnContextMiddleware,};pub(crate) use observability::SubagentScope;-pub use resolved_route::{- current_resolved_provider_route, current_route_slot, record_resolved_provider_route,- with_resolved_provider_route_scope, with_route_slot, ResolvedProviderRoute, RouteSlot,-};pub(crate) use run_cancellation_context::current_run_cancellation;pub(crate) use topology::all_graph_topologies;pub use turn_models::TurnModelSource;diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rsindex 27ce5413e7..5e54861f19 100644--- a/crates/openhuman-core/src/agent/tinyagents/model.rs+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs@@ -410,67 +410,6 @@ pub(super) struct ProfileOverrideModel {request_temperature: Option<f64>,}-/// Records the concrete provider/model selected by a crate-native turn model.-///-/// TinyAgents' registry records the selected registry key (for example-/// `chat-v1`) on `ModelResponse`, but channel audit events also need the-/// provider and concrete wire model. Each registered route is wrapped with-/// this metadata at construction time. Recording immediately before dispatch-/// means retries are harmless and a successful fallback leaves the last-/// attempted (therefore handling) route in the ambient turn slot.-pub(super) struct RouteRecordingModel {- inner: Arc<dyn ChatModel<()>>,- provider: String,- model: String,-}--impl RouteRecordingModel {- pub(super) fn new(- inner: Arc<dyn ChatModel<()>>,- provider: impl Into<String>,- model: impl Into<String>,- ) -> Self {- Self {- inner,- provider: provider.into(),- model: model.into(),- }- }-- fn record_route(&self) {- super::record_resolved_provider_route(&self.provider, &self.model);- }-}--#[async_trait]-impl ChatModel<()> for RouteRecordingModel {- fn profile(&self) -> Option<&ModelProfile> {- self.inner.profile()- }-- fn cache_identity(&self) -> Option<String> {- self.inner.cache_identity()- }-- async fn invoke(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- self.record_route();- self.inner.invoke(state, request).await- }-- async fn stream(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelStream> {- self.record_route();- self.inner.stream(state, request).await- }-}-impl ProfileOverrideModel {pub(super) fn new(inner: Arc<dyn ChatModel<()>>, profile: ModelProfile) -> Self {Self {@@ -584,10 +523,6 @@ impl ChatModel<()> for MaxTokensModel {}}-#[cfg(test)]-#[path = "model_route_recording_tests_tests.rs"]-mod route_recording_tests;-#[cfg(test)]#[path = "model_g1_usage_tests_tests.rs"]mod g1_usage_tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs b/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rsdeleted file mode 100644index b92877b87e..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/model_route_recording_tests_tests.rs+++ /dev/null@@ -1,125 +0,0 @@-use super::*;-use crate::agent::tinyagents::{- current_resolved_provider_route, with_resolved_provider_route_scope, ResolvedProviderRoute,-};--struct SuccessfulModel;--#[async_trait]-impl ChatModel<()> for SuccessfulModel {- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse::assistant("ok"))- }-}--#[tokio::test]-async fn selected_model_records_concrete_route_and_fallback_overwrites_primary() {- let primary = RouteRecordingModel::new(Arc::new(SuccessfulModel), "openhuman", "chat-v1");- let fallback =- RouteRecordingModel::new(Arc::new(SuccessfulModel), "anthropic", "claude-sonnet-4");- let observed = with_resolved_provider_route_scope(async {- primary- .invoke(&(), ModelRequest::default())- .await- .expect("primary dispatch");- fallback- .invoke(&(), ModelRequest::default())- .await- .expect("fallback dispatch");- current_resolved_provider_route()- })- .await;-- assert_eq!(- observed,- Some(ResolvedProviderRoute {- provider: "anthropic".to_string(),- model: "claude-sonnet-4".to_string(),- })- );-}--#[tokio::test]-async fn streamed_model_records_concrete_route_before_stream_consumption() {- let model = RouteRecordingModel::new(Arc::new(SuccessfulModel), "openhuman", "reasoning-v1");- let observed = with_resolved_provider_route_scope(async {- let _stream = model- .stream(&(), ModelRequest::default())- .await- .expect("stream dispatch");- current_resolved_provider_route()- })- .await;-- assert_eq!(- observed,- Some(ResolvedProviderRoute {- provider: "openhuman".to_string(),- model: "reasoning-v1".to_string(),- })- );-}--/// A model that identifies itself for response-cache scoping.-struct IdentifiedModel;--#[async_trait]-impl ChatModel<()> for IdentifiedModel {- fn cache_identity(&self) -> Option<String> {- Some("test-provider:https://example/v1:model-x".to_string())- }-- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse::assistant("ok"))- }-}--/// The harness scopes its response cache on `ChatModel::cache_identity`, and-/// the trait default declines identity. Every host wrapper therefore has to-/// forward it, or every wrapped model collapses into the crate's-/// "anonymous-model" key space and a shared cache can cross-serve answers-/// between a hosted and a local model.-#[test]-fn every_turn_wrapper_forwards_the_inner_cache_identity() {- let expected = Some("test-provider:https://example/v1:model-x".to_string());- let inner: Arc<dyn ChatModel<()>> = Arc::new(IdentifiedModel);-- let route = RouteRecordingModel::new(inner.clone(), "p", "m");- assert_eq!(route.cache_identity(), expected);-- let profile = ProfileOverrideModel::new(inner.clone(), ModelProfile::default());- assert_eq!(profile.cache_identity(), expected);-- let capped = MaxTokensModel::new(inner.clone(), 1024);- assert_eq!(capped.cache_identity(), expected);-- // Nested the way the turn builder stacks them.- let stacked = RouteRecordingModel::new(- Arc::new(MaxTokensModel::new(- Arc::new(ProfileOverrideModel::new(inner, ModelProfile::default())),- 1024,- )),- "p",- "m",- );- assert_eq!(stacked.cache_identity(), expected);-}--#[test]-fn profile_override_cache_identity_includes_request_model() {- let inner: Arc<dyn ChatModel<()>> = Arc::new(IdentifiedModel);- let first = ProfileOverrideModel::new(inner.clone(), ModelProfile::default())- .with_request_model("model-a");- let second =- ProfileOverrideModel::new(inner, ModelProfile::default()).with_request_model("model-b");-- assert_ne!(first.cache_identity(), second.cache_identity());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/resolved_route.rs b/crates/openhuman-core/src/agent/tinyagents/resolved_route.rsdeleted file mode 100644index e965337101..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/resolved_route.rs+++ /dev/null@@ -1,92 +0,0 @@-//! Per-turn resolved provider/model metadata.-//!-//! Model adapters that translate aliases or perform fallbacks record-//! the concrete route that actually handled the latest successful provider-//! call. The agent bus reads this after the turn so channel audit events can-//! persist the resolved provider/model instead of the caller's requested route.--use std::sync::{Arc, Mutex};--#[derive(Clone, Debug, PartialEq, Eq)]-pub struct ResolvedProviderRoute {- pub provider: String,- pub model: String,-}--/// The ambient audit slot shared by an enclosing-/// [`with_resolved_provider_route_scope`]. Exposed so a detached provider call-/// (issue #4460: streamed calls run in a `tokio::spawn`) can capture the caller's-/// slot before crossing the spawn boundary and re-establish it inside, so its-/// `record_resolved_provider_route` writes still land in the caller's scope.-pub type RouteSlot = Arc<Mutex<Option<ResolvedProviderRoute>>>;--tokio::task_local! {- static RESOLVED_PROVIDER_ROUTE: RouteSlot;-}--pub async fn with_resolved_provider_route_scope<F>(future: F) -> F::Output-where- F: std::future::Future,-{- tracing::trace!("[provider] resolved-route scope enter");- let out = RESOLVED_PROVIDER_ROUTE- .scope(Arc::new(Mutex::new(None)), Box::pin(future))- .await;- tracing::trace!("[provider] resolved-route scope exit");- out-}--pub fn record_resolved_provider_route(provider: impl Into<String>, model: impl Into<String>) {- let provider = provider.into();- let model = model.into();- let route = ResolvedProviderRoute {- provider: provider.clone(),- model: model.clone(),- };- let wrote = RESOLVED_PROVIDER_ROUTE- .try_with(|slot| {- *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(route);- })- .is_ok();- tracing::debug!(- provider = %provider,- model = %model,- wrote,- "[provider] resolved-route recorded"- );-}--/// Clone the ambient audit slot handle (the `Arc`, not the recorded route) set-/// by an enclosing [`with_resolved_provider_route_scope`]. `None` outside a-/// scope. Capture this **before** a `tokio::spawn` so the detached task can-/// re-establish the same slot via [`with_route_slot`] and have its route writes-/// reach the caller's scope — task-locals do not propagate across `spawn`-/// (issue #4460).-pub fn current_route_slot() -> Option<RouteSlot> {- RESOLVED_PROVIDER_ROUTE.try_with(|slot| slot.clone()).ok()-}--/// Re-establish a [`current_route_slot`]-captured `slot` as the ambient-/// resolved-route task-local for `future`. Any `record_resolved_provider_route`-/// call inside `future` then writes back to the original caller's audit slot,-/// even when `future` runs in a detached `tokio::spawn` (issue #4460).-pub async fn with_route_slot<F>(slot: RouteSlot, future: F) -> F::Output-where- F: std::future::Future,-{- tracing::trace!("[provider] resolved-route slot re-established across spawn boundary");- RESOLVED_PROVIDER_ROUTE.scope(slot, Box::pin(future)).await-}--pub fn current_resolved_provider_route() -> Option<ResolvedProviderRoute> {- let route = RESOLVED_PROVIDER_ROUTE- .try_with(|slot| slot.lock().unwrap_or_else(|e| e.into_inner()).clone())- .ok()- .flatten();- tracing::trace!(present = route.is_some(), "[provider] resolved-route read");- route-}--#[cfg(test)]-#[path = "resolved_route_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/resolved_route_tests.rs b/crates/openhuman-core/src/agent/tinyagents/resolved_route_tests.rsdeleted file mode 100644index 48e85a183b..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/resolved_route_tests.rs+++ /dev/null@@ -1,21 +0,0 @@-use super::*;--#[tokio::test]-async fn resolved_provider_route_scopes_and_clears() {- assert!(current_resolved_provider_route().is_none());-- let observed = with_resolved_provider_route_scope(async {- record_resolved_provider_route("provider-a", "model-a");- current_resolved_provider_route()- })- .await;-- assert_eq!(- observed,- Some(ResolvedProviderRoute {- provider: "provider-a".into(),- model: "model-a".into(),- })- );- assert!(current_resolved_provider_route().is_none());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/routes.rs b/crates/openhuman-core/src/agent/tinyagents/routes.rsindex 30df88efd3..60f4b71e96 100644--- a/crates/openhuman-core/src/agent/tinyagents/routes.rs+++ b/crates/openhuman-core/src/agent/tinyagents/routes.rs@@ -280,6 +280,43 @@ impl ModelMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>}}+/// 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;++#[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 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);+ }+ Ok(MiddlewareModelOutcome::from(response))+ }+}+#[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.rsindex 95bf94354c..3396526fbd 100644--- a/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs@@ -1,4 +1,132 @@use super::*;+use std::sync::Arc;++use async_trait::async_trait;+use futures::StreamExt;+use tinyagents_harness::agent_loop::AgentStreamItem;+use tinyagents_harness::context::RunConfig;+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,+};++struct FailingModel;++#[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 fn run_recorded_route(+ streaming: bool,+ fallback: bool,+ route: ResolvedModelRoute,+) -> ResolvedModelRoute {+ 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(+ Arc::new(ScriptedModel::replies(vec!["done"])),+ 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));++ let host = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ let slot = host.resolved_route.clone();+ let ctx = host.into_tinyagents(RunConfig::new("route-recording"));+ 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");+ }+ slot.lock()+ .expect("route slot")+ .clone()+ .expect("middleware records canonical response route")+}++#[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");+ assert_eq!(+ run_recorded_route(streaming, false, route.clone()).await,+ route,+ "streaming={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");+ assert_eq!(+ run_recorded_route(streaming, true, route.clone()).await,+ route,+ "streaming={streaming}"+ );+ }+}++#[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");+ let (first_observed, second_observed) = tokio::join!(+ run_recorded_route(false, false, first.clone()),+ run_recorded_route(true, false, second.clone()),+ );+ assert_eq!(first_observed, first);+ assert_eq!(second_observed, second);+}/// The fallback chain for every tier must lead with the primary and carry the/// single same-family alternate the legacy static table encoded — the cratediff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rsindex 1bf3bd9df0..d84539269f 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs@@ -4,9 +4,10 @@use std::sync::Arc;use crate::agent::tinyagents::model::{- BuiltTurnModels, ProfileOverrideModel, RouteRecordingModel, TierRoutes, TurnChatModel,+ BuiltTurnModels, ProfileOverrideModel, TierRoutes, TurnChatModel,};use crate::agent::tinyagents::routes;+use tinyinference_llm::model::{ResolvedModelRoute, RouteRecordingModel};pub(crate) fn tinyagents_depth_error(err: &tinyagents_harness::TinyAgentsError,@@ -133,8 +134,7 @@ fn build_turn_models_crate(}?;Ok(Arc::new(RouteRecordingModel::new(model,- provider,- resolved_model,+ ResolvedModelRoute::new(provider, resolved_model, m),)))};@@ -168,8 +168,7 @@ fn build_turn_models_crate(tier.to_string(),Arc::new(RouteRecordingModel::new(route_model,- provider,- resolved_model,+ ResolvedModelRoute::new(provider, resolved_model, tier),)),)),Err(e) => {diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rsindex 02673ee526..31ed67f85c 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs@@ -2,12 +2,17 @@//! sinks middleware write into to build it.use crate::agent::messages::{ChatMessage, ConversationMessage};+use tinyinference_llm::model::ResolvedModelRoute;/// The outcome of a turn driven on the `tinyagents` harness.#[derive(Debug, Clone)]pub(crate) struct TinyagentsTurnOutcome {/// Final assistant text.pub text: String,+ /// Concrete provider/model/host route selected for the final successful+ /// model call. This travels explicitly to channel and bus callers; it is+ /// never recovered from a task-local after the run.+ pub resolved_route: Option<ResolvedModelRoute>,/// The full transcript, converted back to openhuman messages (flat — tool/// calls rendered as text).pub history: Vec<ChatMessage>,diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rsindex f1f3b9c42c..17eab99dfe 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs@@ -41,6 +41,7 @@ pub(super) async fn finalize_turn_outcome(halt_summary: &HaltSummarySlot,wrap_up_fired: &Option<Arc<std::sync::atomic::AtomicBool>>,tool_outcome_sink: &ToolOutcomeSink,+ resolved_route: Option<tinyinference_llm::model::ResolvedModelRoute>,request_base_len: usize,) -> TinyagentsTurnOutcome {// Durable journal: the harness returned a transcript, so stamp the terminal@@ -249,6 +250,7 @@ pub(super) async fn finalize_turn_outcome(TinyagentsTurnOutcome {text,+ resolved_route,history: crate::agent::message_convert::messages_to_history(&run.messages),conversation,model_calls: run.model_calls,diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex e95b948127..a3a9a5cf49 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -137,6 +137,7 @@ pub(crate) async fn run_turn_via_tinyagents(Ok(TinyagentsTurnOutcome {text,+ resolved_route: None,history: out_history,conversation,model_calls: run.model_calls,@@ -579,12 +580,12 @@ pub(crate) async fn run_turn_via_tinyagents_shared(// nested inside its parent's drive future — leaving it inline on the stack// overflows when the parent + child drives compose. Boxing keeps only a// pointer on the stack at each level.- // The route/thread/cancellation scopes remain for legacy tool/model APIs- // outside the typed TinyAgents surface. Their values come from the explicit- // carrier, so detached and nested drives retain the intended identity.+ // Thread and cancellation scopes remain for legacy tool/model APIs outside+ // the typed TinyAgents surface. Route metadata is carried exclusively by+ // the typed run context and canonical model response.let run_thread_id = run_context.thread_id.clone().unwrap_or_default();- let run_route_slot = run_context.resolved_route.clone();- let run_result = crate::agent::tinyagents::with_route_slot(run_route_slot, async move {+ let resolved_route_slot = run_context.resolved_route.clone();+ let run_result =crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {with_run_cancellation(cancellation.clone(), async {if streaming {@@ -615,9 +616,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(}).await})- .await- })- .await;+ .await;// Drive future returned: run cleanup now (abort poll task + deregister +// requeue residual steers) rather than deferring to end-of-scope so the poll// loop cannot deliver into the no-longer-drained handle during post-run@@ -638,6 +637,10 @@ pub(crate) async fn run_turn_via_tinyagents_shared(}};+ let resolved_route = resolved_route_slot+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .clone();Ok(finalize_turn_outcome(run,model,@@ -653,6 +656,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(&halt_summary,&wrap_up_fired,&tool_outcome_sink,+ resolved_route,request_base_len,).await)diff --git a/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs b/crates/openhuman-core/src/skills/e2e_plumbing_tests.rsindex 6de78d03c2..ea01c5fff8 100644--- a/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs+++ b/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs@@ -209,7 +209,7 @@ async fn mock_llm_orchestrator_lists_and_runs_workflows_through_the_loop() {.await.expect("tool loop should run to completion");- assert_eq!(result, "done");+ assert_eq!(result.text, "done");let tool_msgs: String = history.iter()diff --git a/crates/openhuman-core/src/skills/e2e_run_tests.rs b/crates/openhuman-core/src/skills/e2e_run_tests.rsindex b7cb090b9a..55b3bec28d 100644--- a/crates/openhuman-core/src/skills/e2e_run_tests.rs+++ b/crates/openhuman-core/src/skills/e2e_run_tests.rs@@ -247,7 +247,7 @@ async fn orchestrator_runs_workflow_tool_and_gets_inner_result() {.await.expect("orchestrator loop should complete");- assert_eq!(result, "ORCHESTRATOR_DONE");+ assert_eq!(result.text, "ORCHESTRATOR_DONE");// The run_workflow tool result (carrying the inner run's DONE outcome) must// have flowed back into the conversation.let tool_msgs: String = historydiff --git a/docs/specs/agent-runtime-upstream-boundary.md b/docs/specs/agent-runtime-upstream-boundary.mdindex e4259103ab..a269425264 100644--- a/docs/specs/agent-runtime-upstream-boundary.md+++ b/docs/specs/agent-runtime-upstream-boundary.md@@ -184,9 +184,12 @@ The inference crate owns information that is true at a model call boundary:- OpenHuman maps its provider DTO at the provider boundary and keeps pricingpolicy and tier selection host-side.-This removes `MaxTokensModel`, `ProfileOverrideModel`, `RouteRecordingModel`,-the raw `openhuman_usage_meta` envelope, `UsageCarryMiddleware`, and-`AbortOnDrop` from `agent/tinyagents/`.+The canonical `RouteRecordingModel` stamps this metadata on unary responses+and stream terminal metadata. OpenHuman's typed model middleware copies only+the successful response route into its explicit run context, and the turn+outcome carries it to channel callers. This removes the OpenHuman+`RouteRecordingModel` and resolved-route task-local bridge; the remaining+host wrappers stay only while their product policy is not yet upstream.### Explicit recursive context@@ -314,7 +317,7 @@ all consumers import the owner directly, not that behavior is dropped.| `host/*` | Keep as the ten OpenHuman adapter implementations; wire all into one bundle factory. || `harness_assembly.rs`, `harness_context_ladder.rs`, `harness_tool_registration.rs`, `turn_runner.rs` | Delete after host-driven invocation owns assembly and live routes switch. || `convert.rs`, `tools.rs` | Delete after canonical `tinytools::Tool` adoption. |-| `model.rs`, `abort_guard.rs`, `resolved_route.rs`, route/usage helpers in `routes.rs` | Move generic pieces to `tinyinference-llm`; keep tier/fallback choice in host model resolver; delete task-local route slot. |+| `model.rs`, `abort_guard.rs`, route/usage helpers in `routes.rs` | Move generic pieces to `tinyinference-llm`; keep tier/fallback choice in host model resolver. Route observation already uses TinyInference response metadata and an explicit OpenHuman run-context field; no task-local slot remains. || `middleware/{arg_recovery,message_trim,prompt_cache,repeat_progress,repeated_failure,final_call_wrap_up,artifact_index_toc,credential_scrub}.rs` | Move generic mechanism to harness, parameterized by policy/callbacks. || `middleware/{approval,cli_rpc_only,cost_budget,embedder_hooks,memory_protocol,packed_tool_route,tool_exposure,tool_outcome_capture,tool_output,tool_policy,turn_context}.rs` | Split: upstream lifecycle/mechanics; OpenHuman policy and domain adapters remain behind host traits/context. No forwarding middleware module. || `middleware/loop_guards.rs` | Move generic terminal/no-progress behavior to harness. |diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex 9d2cd90f0a..efa087855e 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -9,7 +9,7 @@{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/harness/graph.rs",- "line": 122,+ "line": 123,"text": "let outcome = run_turn_via_tinyagents_shared(","occurrence": 1},@@ -72,7 +72,7 @@{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",- "line": 91,+ "line": 86,"text": "pub(crate) use turn_runner::run_turn_via_tinyagents_shared;","occurrence": 1},@@ -86,14 +86,14 @@{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 199,+ "line": 200,"text": "pub(crate) async fn run_turn_via_tinyagents_shared(","occurrence": 1},{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 257,+ "line": 258,"text": "} = assemble_turn_harness(","occurrence": 1},@@ -114,38 +114,24 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/bus.rs",- "line": 37,+ "line": 34,"text": "use super::harness::{run_channel_turn_via_graph, with_current_sandbox_mode};","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/bus.rs",- "line": 294,- "text": "let (text, resolved_route) = with_resolved_provider_route_scope(async {",+ "line": 291,+ "text": "let outcome = turn_origin::with_origin(","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/bus.rs","line": 295,- "text": "let text = turn_origin::with_origin(",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/bus.rs",- "line": 299,"text": "with_current_sandbox_mode(sandbox_mode, async {","occurrence": 1},- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/bus.rs",- "line": 327,- "text": "let resolved_route = current_resolved_provider_route();",- "occurrence": 1- },{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/goals/continuation.rs",@@ -1283,155 +1269,64 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 89,+ "line": 91,"text": "context.origin = crate::agent::turn_origin::current();","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 90,+ "line": 92,"text": "context.progress = crate::agent::progress_sink::current_progress_sink();","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 92,+ "line": 94,"text": "context.dispatch = crate::agent::harness::turn_dispatch_guard::current();","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 93,+ "line": 95,"text": "context.thread_id = crate::agent::tinyagents::thread_context::current_thread_id();","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 94,- "text": "if let Some(slot) = crate::agent::tinyagents::current_route_slot() {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 97,+ "line": 96,"text": "if let Some(cancellation) = crate::agent::tinyagents::current_run_cancellation() {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/host/run_context.rs",- "line": 100,+ "line": 99,"text": "context.workspace = crate::agent::turn_workspace::current()","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",- "line": 50,- "text": "pub mod resolved_route;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",- "line": 53,+ "line": 52,"text": "pub(crate) mod run_cancellation_context;","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",- "line": 57,+ "line": 56,"text": "pub mod thread_context;","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",- "line": 83,- "text": "pub(crate) use run_cancellation_context::current_run_cancellation;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/model.rs",- "line": 441,- "text": "super::record_resolved_provider_route(&self.provider, &self.model);",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 23,- "text": "tokio::task_local! {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 24,- "text": "static RESOLVED_PROVIDER_ROUTE: RouteSlot;",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 32,- "text": "let out = RESOLVED_PROVIDER_ROUTE",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 39,- "text": "pub fn record_resolved_provider_route(provider: impl Into<String>, model: impl Into<String>) {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 46,- "text": "let wrote = RESOLVED_PROVIDER_ROUTE",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 65,- "text": "pub fn current_route_slot() -> Option<RouteSlot> {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 66,- "text": "RESOLVED_PROVIDER_ROUTE.try_with(|slot| slot.clone()).ok()",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs","line": 78,- "text": "RESOLVED_PROVIDER_ROUTE.scope(slot, Box::pin(future)).await",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 81,- "text": "pub fn current_resolved_provider_route() -> Option<ResolvedProviderRoute> {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/resolved_route.rs",- "line": 82,- "text": "let route = RESOLVED_PROVIDER_ROUTE",+ "text": "pub(crate) use run_cancellation_context::current_run_cancellation;","occurrence": 1},{@@ -1514,21 +1409,14 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 587,- "text": "let run_result = crate::agent::tinyagents::with_route_slot(run_route_slot, async move {",- "occurrence": 1- },- {- "rule": "openhuman-task-local",- "path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 588,+ "line": 589,"text": "crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 589,+ "line": 590,"text": "with_run_cancellation(cancellation.clone(), async {","occurrence": 1},@@ -2501,7 +2389,7 @@{"rule": "tinyagents-tool-calling-facade","path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/run_loop.rs",- "line": 963,+ "line": 998,"text": "use tinytools_agent::dialect::{DialectResponse, ToolDialect, XmlDialect};","occurrence": 1},