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
fix(ci): remove uncompiled agent source duplicates
Steven Enamakel069ecf0c2786
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/use_skill_dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/use_skill_dispatch.rsdeleted file mode 100644index ed20d8a865..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/use_skill_dispatch.rs+++ /dev/null@@ -1,71 +0,0 @@-//! Hosted-context-preserving dispatch for packed skill tools.--use super::dispatch::DelegationDispatch;-use async_trait::async_trait;-use std::sync::Arc;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};-use tinytools::{ToolCallOptions, ToolResult};--/// Typed dispatch for `use_skill` when its selected inner tool is a synthesized-/// delegation. Plain `Tool::execute_with_context` cannot carry the hosted-/// parent run context that a sub-agent needs, so route those inner calls back-/// through [`DelegationDispatch`] and leave every ordinary packed tool on the-/// proxy's existing execution path.-pub(crate) struct UseSkillDispatch {- tool: Arc<dyn tinytools::Tool>,- tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,-}--impl UseSkillDispatch {- pub(crate) fn new(- tool: Arc<dyn tinytools::Tool>,- tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,- ) -> Self {- Self { tool, tool_sets }- }-}--#[async_trait]-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for UseSkillDispatch {- fn tool(&self) -> Arc<dyn tinytools::Tool> {- self.tool.clone()- }-- async fn execute(- &self,- state: &(),- arguments: serde_json::Value,- options: ToolCallOptions,- parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- ) -> anyhow::Result<ToolResult> {- let skill = arguments.get("skill").and_then(serde_json::Value::as_str);- let inner_name = arguments.get("tool").and_then(serde_json::Value::as_str);- if let (Some(skill), Some(inner_name)) = (skill, inner_name) {- let belongs_to_pack = crate::tools::toolpacks::pack_for_tool(inner_name)- .is_some_and(|pack| pack.id == skill);- if belongs_to_pack {- if let Some(inner) =- crate::agent::tinyagents::tools::CanonicalSharedToolAdapter::for_name(- self.tool_sets.clone(),- inner_name,- )- .map(Arc::new)- {- if let Some(dispatch) = DelegationDispatch::for_tool(inner) {- let inner_args = arguments- .get("args")- .cloned()- .unwrap_or_else(|| serde_json::json!({}));- return dispatch.execute(state, inner_args, options, parent).await;- }- }- }- }-- let context = ToolExecutionContext::from_run_context(parent, _call_id.clone());- self.tool- .execute_with_context(arguments, options, Some(&context))- .await- }-}diff --git a/crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rs b/crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rsdeleted file mode 100644index c4d04f0a80..0000000000--- a/crates/openhuman-core/src/agent/session_host/turn/recall_lanes.rs+++ /dev/null@@ -1,99 +0,0 @@-//! The per-message memory lanes of the turn's context.-//!-//! Both lanes fetch what memory holds for *this* message and prepend it to the-//! user message — never to the system prompt, whose rendered bytes are the-//! KV-cache prefix the inference backend has already tokenised. Both are-//! bounded, because on a cold launch the memory module may still be-//! downloading behind them: a turn without a block is an ordinary turn, a turn-//! that waits minutes for one is the outage the bounds exist to prevent.-//!-//! - **Lane B** — situational preferences: topic-scoped preferences whose-//! vector similarity to the message clears a floor. Runs every turn; an-//! unrelated message clears the gate to nothing.-//! - **Lane C** — auto-recall of facts about the user (#6040): opens only for-//! a message that asks about the user, then one bounded tree lookup. See-//! [`crate::memory::auto_recall`] for the gate, the floor and the-//! switch.-//!-//! The two run **side by side**. Each embeds the message on its own — there is-//! no retrieval that takes a precomputed vector — so run in sequence the turn-//! would pay the sum of two round trips; joined, it pays the slower one. The-//! blocks are appended in a fixed order afterwards, so the prompt is stable-//! whichever lane answers first.-//!-//! `core_turn.rs` documents the broad per-turn recall that used to live here-//! and why it was removed; neither lane is that.--use super::super::types::OpenHumanSessionHost;-use std::time::Instant;--/// Append the Lane B and Lane C blocks for `user_message` to `context`.-pub(super) async fn append_recall_lanes(- agent: &OpenHumanSessionHost,- user_message: &str,- context: &mut String,-) {- let (situational, auto_recall) = tokio::join!(- situational_preferences(agent, user_message),- auto_recall_block(agent, user_message),- );- if !situational.is_empty() {- context.push_str("## Relevant preferences for this message\n\n");- for pref in &situational {- context.push_str("- ");- context.push_str(pref.trim());- context.push('\n');- }- context.push('\n');- }- if let Some(block) = auto_recall {- context.push_str(&block);- }-}--/// Lane B: preferences semantically relevant to this message.-async fn situational_preferences(agent: &OpenHumanSessionHost, user_message: &str) -> Vec<String> {- // 5 s, not 3: the module's lookup (a query embed round trip, queued behind- // the citation and autosave calls spawned off the turn) measured over 3 s- // on a live desktop and lost the block on both on-topic turns of the- // #6041 field test.- const SITUATIONAL_RECALL_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);- let started = Instant::now();- let situational = match tokio::time::timeout(- SITUATIONAL_RECALL_BUDGET,- crate::memory::preferences::recall_situational_preferences_on(&agent.memory, user_message),- )- .await- {- Ok(situational) => situational,- Err(_elapsed) => {- log::warn!(- "[pref_recall] situational recall exceeded {SITUATIONAL_RECALL_BUDGET:?}; \- continuing without a preference block"- );- return Vec::new();- }- };- if situational.is_empty() {- log::debug!(- "[pref_recall] no situational preference relevant to this message elapsed_ms={}",- started.elapsed().as_millis()- );- } else {- log::info!(- "[pref_recall] situational block injected: {} item(s) elapsed_ms={}",- situational.len(),- started.elapsed().as_millis()- );- }- situational-}--/// Lane C: the gated auto-recall block, when the session has the lane bound.-async fn auto_recall_block(agent: &OpenHumanSessionHost, user_message: &str) -> Option<String> {- let Some(auto_recall) = agent.auto_recall.as_ref() else {- log::debug!("[auto_recall] no lane bound to this session; skipping");- return None;- };- auto_recall.block_for(user_message).await-}diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/memory_fast_path.rs b/crates/openhuman-core/src/agent/subagent_host/ops/memory_fast_path.rsdeleted file mode 100644index 45135d2022..0000000000--- a/crates/openhuman-core/src/agent/subagent_host/ops/memory_fast_path.rs+++ /dev/null@@ -1,248 +0,0 @@-use super::*;--/// Definition id of the pure-retrieval memory agent, reached from chat as the-/// `retrieve_memory` delegate and from other agents as `call_memory_agent`.-pub(super) const AGENT_MEMORY_ID: &str = "agent_memory";--/// How many deterministic hits the memory fast path returns (#4677).-pub(super) const MEMORY_FAST_PATH_LIMIT: usize = 8;--/// Whether the deterministic memory fast path (#4677) is enabled. Default on;-/// `OPENHUMAN_MEMORY_FAST_PATH=0` (or `false`/`no`/`off`) forces the full-/// model-driven walk, e.g. to A/B the two paths without a rebuild.-pub(super) fn memory_fast_path_enabled() -> bool {- parse_memory_fast_path_enabled(std::env::var("OPENHUMAN_MEMORY_FAST_PATH").ok().as_deref())-}--/// Pure core of [`memory_fast_path_enabled`], kept env-free for deterministic-/// unit testing.-pub(super) fn parse_memory_fast_path_enabled(env_value: Option<&str>) -> bool {- !matches!(- env_value.map(|v| v.trim().to_ascii_lowercase()).as_deref(),- Some("0") | Some("false") | Some("no") | Some("off")- )-}--/// Render deterministic retrieval hits into a compact, citable memory-context-/// block for the parent turn. Returns `None` when there are no hits, so the-/// caller falls back to the model-driven walk (the empty/degraded case is-/// #4655's territory and still benefits from the model's judgement).-pub(super) fn format_deterministic_memory_hits(resp: &RetrievalResponse) -> Option<String> {- use std::fmt::Write as _;- if resp.hits.is_empty() {- return None;- }- const PER_HIT_CHARS: usize = 600;- let mut out = format!(- "Retrieved {} relevant memor{} via deterministic memory search:\n",- resp.hits.len(),- if resp.hits.len() == 1 { "y" } else { "ies" }- );- for (i, hit) in resp.hits.iter().enumerate() {- let content = hit.content.trim();- let body: String = content.chars().take(PER_HIT_CHARS).collect();- let ellipsis = if content.chars().count() > PER_HIT_CHARS {- " …"- } else {- ""- };- let scope = if hit.tree_scope.trim().is_empty() {- "memory"- } else {- hit.tree_scope.trim()- };- let _ = writeln!(- out,- "{}. [{scope}] {body}{ellipsis} (relevance {:.2})",- i + 1,- hit.score- );- }- Some(out)-}--/// Truncate `output` in place to the definition's `max_result_chars` cap (when-/// set), appending a `[...truncated]` marker. Char-count based (not byte-length)-/// to avoid panicking on a multi-byte UTF-8 sequence at the boundary.-///-/// Shared by the normal sub-agent path and the deterministic memory fast path so-/// both honour a definition's cap. `agent_memory` sets no cap today (its output-/// is self-bounded at 8 hits × 600 chars), but routing the fast path through the-/// same helper keeps the two paths from silently diverging if one is ever added-/// (YellowSnnowmann review).-pub(super) fn apply_max_result_chars(output: &mut String, cap: Option<usize>, agent_id: &str) {- let Some(cap) = cap else { return };- let original_chars = output.chars().count();- if original_chars <= cap {- return;- }- tracing::debug!(- agent_id = %agent_id,- original_chars,- cap,- "[subagent_runner] truncating oversized result to max_result_chars cap"- );- let byte_offset = output- .char_indices()- .nth(cap)- .map(|(i, _)| i)- .unwrap_or(output.len());- output.truncate(byte_offset);- output.push_str("\n[...truncated]");-}--/// Deterministic fast path for the pure-retrieval [`AGENT_MEMORY_ID`] sub-agent-/// (#4677).-///-/// `agent_memory` otherwise runs a model-driven walk (≤ its `max_iterations`)-/// whose per-iteration LLM round-trips dominate turn latency at ~30–40s per call-/// *even when data is present*. [`fast_retrieve`] (E2GraphRAG: query-entity +-/// dense/semantic recall over the same memory tree, no LLM in the loop) returns-/// the same hits in a single deterministic pass. When it finds data we return-/// those hits directly; when the fast path is disabled, errors, or finds nothing-/// we return `None` so the caller runs the full sub-agent unchanged.-///-/// # Relevance guard (Codex review)-///-/// We only short-circuit for an **entity-grounded** query — one that yields at-/// least one canonical entity or salient topic. Without grounding, `fast_retrieve`-/// falls back to a pure global-dense pass that reranks/truncates whatever-/// summaries exist, so a vague query against a populated profile would surface-/// unrelated top-k memories as a "completed" retrieval instead of letting the-/// model-driven agent judge relevance (or emit "no relevant memory found").-/// Grounded queries keep the fast path; ungrounded ones defer to the full agent.-pub(super) async fn try_deterministic_memory_retrieval(- task_prompt: &str,- definition: &AgentDefinition,- task_id: &str,- started: Instant,- loaded_config: &LoadedConfig,-) -> Option<SubagentRunOutcome> {- let agent_id = definition.id.as_str();- if !memory_fast_path_enabled() {- return None;- }- let query = task_prompt.trim();- if query.is_empty() {- return None;- }- let config = match loaded_config.as_ref() {- Ok(config) => config.as_ref(),- Err(e) => {- tracing::warn!(- task_id = %task_id,- error = %e,- "[subagent_runner] agent_memory fast-path config load failed — falling back to model walk (#4677)"- );- return None;- }- };- // Relevance guard (Codex review): require entity/topic grounding before a- // deterministic pass stands in for the model's relevance judgement — the- // extraction is cheap (regex or one spaCy call) and `fast_retrieve` repeats- // it internally anyway. It goes through the provider's scoring family so- // the host no longer calls `tinymemory_core::` directly, and every failure- // (binding unavailable, scoring not exposed, extraction error) is fail-safe- // as entities_empty = true: the fast path is skipped and the model-driven- // walk runs — the same conservative outcome an unavailable extractor- // produced before scoring existed.- let entities_empty = match crate::memory::binding::for_config(config) {- Ok(binding) => match binding.provider().as_scoring() {- Some(scoring) => match scoring.extract_entities(query).await {- Ok(entities) => entities.is_empty(),- Err(e) => {- tracing::debug!(- task_id = %task_id,- error = %e,- "[subagent_runner] scoring extract_entities failed (non-fatal) — deferring to model walk (#4677)"- );- true- }- },- None => {- tracing::debug!(- task_id = %task_id,- "[subagent_runner] driver does not expose scoring (module not loaded or policy excluded) — deferring to model walk (#4677)"- );- true- }- },- Err(e) => {- tracing::debug!(- task_id = %task_id,- error = %e,- "[subagent_runner] memory binding unavailable (non-fatal) — deferring to model walk (#4677)"- );- true- }- };- if entities_empty {- tracing::debug!(- task_id = %task_id,- "[subagent_runner] agent_memory fast-path skipped — ungrounded query (no entities/topics); deferring to model walk (#4677)"- );- return None;- }- let opts = FastRetrieveQuery {- limit: MEMORY_FAST_PATH_LIMIT,- ..FastRetrieveQuery::default()- };- // Through the bound driver's `MemoryRetrieval`, not the engine (#5560).- // This is an agent turn, so `as_bus_scope()` carries the turn's own- // memory-source allowlist; `binding.provider()` is unguarded, which makes- // that argument the gate rather than a hint.- let scope = as_bus_scope();- let binding = match crate::memory::binding::for_config(config) {- Ok(binding) => binding,- Err(e) => {- tracing::warn!(- task_id = %task_id,- error = %e,- "[subagent_runner] agent_memory fast-path could not bind the memory driver — falling back to model walk (#4677)"- );- return None;- }- };- // A driver with no retrieval family has no summary tree to rank. Falling- // through to the model walk is the same answer this path already gives for- // an empty result, and strictly better than reporting a failure that is- // really an absent capability.- let retrieval = binding.provider().as_retrieval()?;- let resp = match retrieval.fast_retrieve(query, opts, scope.as_ref()).await {- Ok(resp) => resp,- Err(e) => {- tracing::warn!(- task_id = %task_id,- error = %format!("{e:#}"),- "[subagent_runner] agent_memory fast-path retrieval errored — falling back to model walk (#4677)"- );- return None;- }- };- let mut output = format_deterministic_memory_hits(&resp)?;- // Honour the definition's `max_result_chars` cap just like the model-driven- // path (YellowSnnowmann review). No-op for `agent_memory` (uncapped, and the- // block above is already self-bounded), but keeps the paths from diverging.- apply_max_result_chars(&mut output, definition.max_result_chars, agent_id);- tracing::info!(- task_id = %task_id,- hits = resp.hits.len(),- total = resp.total,- elapsed_ms = started.elapsed().as_millis() as u64,- "[subagent_runner] agent_memory deterministic fast-path hit — skipped the model walk (#4677)"- );- Some(SubagentRunOutcome {- task_id: task_id.to_string(),- agent_id: agent_id.to_string(),- output,- iterations: 0,- elapsed: started.elapsed(),- mode: SubagentMode::Typed,- status: SubagentRunStatus::Completed,- final_history: Vec::new(),- usage: SubagentUsage::default(),- // Deterministic memory hits are already bounded; nothing is offloaded- // on this path.- artifact_paths: Vec::new(),- })-}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rsdeleted file mode 100644index 062b683ad8..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner_inner.rs+++ /dev/null@@ -1,529 +0,0 @@-use super::*;-pub(super) async fn run_turn_via_tinyagents_inner(- run_context: OpenHumanRunContext,- turn_models: TurnModels,- provider_id: String,- model: &str,- history: Vec<ChatMessage>,- tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,- allowed: Option<HashSet<String>>,- max_iterations: usize,- subagent_scope: Option<SubagentScope>,- context_window: Option<u64>,- run_queue: Option<Arc<RunQueue>>,- early_exit_tools: &[&str],- pause_at_cap: bool,- max_output_tokens: Option<u32>,- context_mw: TurnContextMiddleware,- tool_policy: Option<ToolPolicyEnforcement>,- deterministic_cacheable: bool,- defer_turn_completed_to_caller: bool,- hosted_root: Option<(- Arc<crate::agent::tinyagents::host::OpenHumanHostBase>,- String,- )>,-) -> Result<TinyagentsTurnOutcome> {- // The host context is the sole turn carrier. Pulling the sender into this- // local keeps the event bridge API compact without creating a second- // parameter path for progress.- let on_progress = run_context.progress.clone();- // `0` means "unset" → the legacy default (a native-bus / test convention);- // otherwise the harness model-call cap would be zero and abort the run before- // the first provider call.- let max_iterations = effective_max_iterations(max_iterations);- // Hosted resolution must expose this turn's already-selected primary and- // fallback models. Build the resolver before assembly consumes the model- // bundle; it is installed only on the invocation-local host bundle.- let hosted_model_resolver = hosted_root.as_ref().map(|_| {- Arc::new(- crate::agent::tinyagents::turn_models::TurnModelResolver::from_turn_models(- &turn_models,- ),- ) as Arc<dyn tinyagents_harness::host::ModelResolver<()>>- });- // Assembly consumes the registry sets. The host security adapter must see- // the exact same `Arc`-shared instances, so retain only the cheap Arc clone- // for a hosted invocation (never clone the tools themselves).- let hosted_tool_sets = hosted_root.as_ref().map(|_| tool_sets.clone());- // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry- // id are built by the caller via `build_turn_models` — the seam entry is- // crate-native and no longer names `Provider` (issue #4249, Phase 5). The- // telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.- let AssembledTurnHarness {- harness,- cursor,- tool_names,- failure_map,- provider_usage_carry,- error_slot,- halt_summary,- tool_outcome_sink,- handle,- early_exit_hook,- wrap_up_fired,- tool_count,- registry_snapshot: _,- registry_diagnostics,- tool_result_artifact_index,- compression_mw,- prompt_cache_guard,- } = assemble_turn_harness(- turn_models,- model,- tool_sets,- allowed,- max_iterations,- on_progress.clone(),- subagent_scope.clone(),- context_window,- early_exit_tools,- context_mw,- run_context.stop_hooks.clone(),- tool_policy.clone(),- routes::turn_required_capabilities(model),- deterministic_cacheable,- hosted_root.is_some(),- pause_at_cap,- );-- // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).- // The projected `CapabilityRegistry` produced these diagnostics during- // assembly; enforce them here, *before* the first model dispatch, so an- // ambiguous/broken tool surface (duplicate name across native/MCP/Composio/- // generated tools, dangling alias, etc.) aborts the turn instead of silently- // resolving to an unintended component while a provider call is in flight.- if !registry_diagnostics.is_empty() {- let (errors, warnings): (- Vec<&tinyagents_registry::RegistryDiagnostic>,- Vec<&tinyagents_registry::RegistryDiagnostic>,- ) = registry_diagnostics- .iter()- .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));- for diag in &warnings {- tracing::warn!(- kind = diag.kind.as_str(),- name = %diag.name,- "[registry] non-fatal diagnostic: {}",- diag.message- );- }- if !errors.is_empty() {- let messages: Vec<String> = errors- .iter()- .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))- .collect();- for msg in &messages {- tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");- }- tracing::error!(- error_count = messages.len(),- warning_count = warnings.len(),- "[registry] aborting turn before model dispatch: capability registry validation failed"- );- return Err(anyhow::Error::new(- crate::agent::error::AgentError::RegistryValidationFailed {- diagnostics: messages,- },- ));- }- tracing::debug!(- warning_count = warnings.len(),- "[registry] registry diagnostics present (warnings only); proceeding with turn"- );- }-- let mut config = RunConfig::new("agent_turn")- .with_max_model_calls(max_iterations)- .with_max_tool_calls(max_iterations.saturating_mul(8).max(8))- .with_max_depth(MAX_SPAWN_DEPTH)- .with_tag("openhuman")- .with_tag(if subagent_scope.is_some() {- "scope:subagent"- } else {- "scope:root"- })- .with_tag(if on_progress.is_some() {- "observed"- } else {- "unobserved"- });- // Per-turn output cap rides RunConfig now (Phase 5 groundwork): the loop- // stamps it onto every `ModelRequest.max_tokens` and the native model adapter- // adapter honors it, so the cap no longer bakes into the primary + route- // models. Mirrors the legacy `AGENT_TURN_MAX_OUTPUT_TOKENS` / sub-agent cap.- if let Some(cap) = max_output_tokens {- config = config.with_max_turn_output_tokens(cap);- }-- tracing::info!(- model,- max_iterations,- tools = tool_count,- observed = on_progress.is_some(),- "[tinyagents] routing turn through tinyagents harness (shared tools)"- );-- let input = crate::agent::message_convert::history_to_messages(&history);- // Explicit persistence boundary (issue #4455): the request transcript length,- // captured *before* the run consumes `input`. The turn's persisted- // `conversation` is everything appended past this index — assistant/tool- // rounds plus any mid-turn steer/collect messages injected as user turns.- // Anchoring here (instead of the last-user-message suffix) keeps injected- // steers from moving the boundary and truncating persisted history on both- // the parent (`session/turn/core.rs`) and subagent (`subagent_runner`) paths.- let request_base_len = input.len();-- // Build the run context: an optional event sink feeds the progress/cost- // bridge (streaming) and/or the model-call-cap pauser; the shared steering- // handle carries mid-flight, early-exit, and cap pauses.- let mut run_context = run_context;- run_context.tool_result_artifact_index = tool_result_artifact_index.clone();- run_context.tool_outcomes = Some(tool_outcome_sink.clone());- let mut ctx = run_context.clone().into_tinyagents(config);- // Assemble the run's store registry: the tool-result artifact index (when- // present) and — behind the default-ON session dual-write flag — the- // session KV store, so the harness carries a handle to the same- // `{workspace}/tinyagents_store/kv` tree the live dual-write mirrors into- // (issue #4249, 04.1). Both stores share one registry so neither clobbers- // the other. Reads stay legacy until 04.2; this registration is additive- // and best-effort (a workspace-resolve failure just skips it).- let mut stores: Option<StoreRegistry> = None;- if let Some(index) = tool_result_artifact_index {- stores- .get_or_insert_with(StoreRegistry::new)- .register(TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE, index);- }- // `session_kv_store` self-gates on the dual-write flag (config default ON +- // env kill switch), returning `None` when disabled or unresolvable.- if let Some(session_kv) = crate::agent::session_import::live::session_kv_store().await {- stores.get_or_insert_with(StoreRegistry::new).register(- crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE,- session_kv,- );- tracing::debug!(- "[session-store] registered session kv store on RunContext.stores under '{}'",- crate::agent::session_import::live::TINYAGENTS_SESSION_KV_STORE- );- }- if let Some(stores) = stores {- ctx = ctx.with_stores(stores);- }-- let streaming = on_progress.is_some();- // Retain a clone of the progress sink so the turn can emit a terminal- // `TurnCompleted` after the run (the harness event stream the bridge mirrors- // has no run-completed event). Parent turns only — a sub-agent turn reports- // via its `Subagent*` events, not a top-level `TurnCompleted`.- //- // #4457 (defect C): suppressed entirely when `defer_turn_completed_to_caller`- // is set — the caller (chat/session path) emits the single terminal- // `TurnCompleted` itself, after its post-run wrap-up finishes streaming.- let turn_completed_sink = (subagent_scope.is_none() && !defer_turn_completed_to_caller)- .then(|| on_progress.clone())- .flatten();- // A sink is needed to mirror progress (bridge), to observe model-call- // completions for the cap pauser, or to persist a durable event journal- // (issue #4249, 05.1). The journal must attach even for an unobserved- // (`on_progress = None`) turn so the run stays reconstructable, so the- // EventSink is now created unconditionally — cheap (an empty sink) and, if- // no consumer subscribes, inert.- //- // Mint the durable run id *before* the sink and seed the sink stream prefix- // with it (`with_stream_id`), so every persisted observation's `event_id` is- // the restart-stable `{run_id}-evt-{offset}` a late-attach replay- // reconstructs the timeline from (05.1). The same id keys the journal + status.- let journal_run_id = journal::mint_run_id();- let events = Some(EventSink::with_stream_id(journal_run_id.as_str()));-- // Attach the event bridge for EVERY turn — including an unobserved- // (`on_progress = None`) background/cron turn (#4467, item 3). The bridge's- // `record_usage` feeds the global cost tracker on each `UsageRecorded` event- // *during* the run, so a run that burns N model calls and then fails still- // contributes that spend to the wallet/cost surfaces — the post-run- // `record_unobserved_turn_usage` fallback below only runs on the success path- // and never sees a failed run's usage. With `on_progress = None` the bridge- // still records cost but its progress `send`s are inert no-ops, so there is- // no spurious streaming. `events` is created unconditionally above, so the- // bridge is always present.- let bridge = events.as_ref().map(|events| {- let bridge = OpenhumanEventBridge::with_scope(- on_progress,- model,- provider_id.clone(),- max_iterations,- subagent_scope.clone(),- cursor.clone(),- tool_names.clone(),- failure_map.clone(),- provider_usage_carry.clone(),- );- events.subscribe(bridge.clone());- bridge- });-- // Cap pauser: stop gracefully at the model-call budget (returning the partial- // transcript) so the caller can summarize a checkpoint instead of erroring.- //- // It is also handed the turn's dispatch guard, so the pause is *recorded* and- // not merely requested. `SteeringCommand::Pause` is advisory — honoured at the- // loop boundary — and nothing consulted it before dispatching a new sub-agent,- // so a dispatch issued in the same instant raced it and took the whole turn- // down with the run's remaining wall-clock budget (#5804). The guard is- // resolved here rather than inside the listener because this future runs on- // the turn's task, where the task-local is in scope; the listener need not.- if pause_at_cap {- if let (Some(events), Some(handle)) = (&events, &handle) {- // Only the TOP-LEVEL turn's cap pause is binding on dispatch. A- // sub-agent reaching its own model-call cap is a routine outcome —- // it summarises and hands its result back (`hit_cap`) — and the- // parent may legitimately keep delegating afterwards. Recording a- // child's cap here would stop the whole turn's fan-out on a signal- // that says nothing about the parent's budget, so `subagent_scope`- // gates it: `None` is the chat turn, `Some` is a delegated child.- // The child still gets its advisory `Pause` either way.- let dispatch_guard = subagent_scope- .is_none()- .then(|| run_context.dispatch.clone())- .flatten();- events.subscribe(CapPauser::new(- handle.clone(),- max_iterations,- ctx.run_id().as_str(),- dispatch_guard,- ));- }- }-- // Durable event journal + status store (issue #4249, 05.1). Attached *in- // addition to* the bridge above: the EventSink fans out to both, so the- // existing progress/global-bus path is untouched. Best-effort and non-fatal- // — a failure to open/attach the journal returns `None` and the turn runs- // unaffected. The handle stamps the terminal status once the run returns.- // A sub-agent turn records under its task scope as the status thread id, so- // `list_by_thread` can enumerate a task's runs (full parent/root lineage is- // a 05.2/05.3 follow-up).- let journal_thread_id = subagent_scope- .as_ref()- .map(|scope| tinyagents_harness::ids::ThreadId::new(scope.task_id.clone()));- let turn_journal = match &events {- Some(events) => {- journal::attach_turn_journal(events, model, journal_run_id.clone(), journal_thread_id)- .await- }- None => None,- };- if subagent_scope.is_none() {- if let Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat {- request_id: Some(request_id),- ..- }) = run_context.origin.as_ref()- {- journal::register_request_journal_run(request_id, journal_run_id.as_str());- }- }-- if let Some(events) = &events {- ctx = ctx.with_events(events.clone());- }-- // Steering: attach the shared handle (when present), drain any already-queued- // steer messages into it (so a pre-run steer lands before the first model- // call), and forward mid-flight steers via a poll loop. The same handle- // carries the early-exit `Pause`.- //- // Best-effort thread label for the delivery/requeue observability events and- // the metadata on any requeued steer: a sub-agent uses its task id; the- // interactive/channel parent turn reads the task-local turn origin.- let steer_thread_label = subagent_scope- .as_ref()- .map(|s| s.task_id.clone())- .or_else(|| match run_context.origin.as_ref() {- Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {- Some(thread_id.clone())- }- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {- reply_target,- ..- }) => Some(reply_target.clone()),- _ => None,- })- .unwrap_or_default();-- // The forwarder is wrapped in an abort-on-drop RAII guard (issue #4456): its- // `Drop` aborts the poll task, deregisters the sub-agent steering handle, and- // drains residual (delivered-but-unapplied) steers back into the session run- // queue. Because the guard is held across the drive future, that cleanup runs- // identically on normal return, error, AND drop-cancellation — the previous- // manual `forwarder.abort()` after the drive future only ran on normal- // return, so a cancelled turn (web interrupt / sub-agent abort, both- // drop-based) leaked a forwarder task that looped forever and raced the next- // turn for the shared run queue.- let steering_forwarder_guard = if let Some(handle) = handle {- let registry_task_id = if let Some(scope) = &subagent_scope {- let task_id = TaskId::new(scope.task_id.clone());- shared_steering_registry().register(task_id.clone(), handle.clone());- tracing::debug!(- task_id = scope.task_id.as_str(),- "[tinyagents] registered subagent steering handle"- );- Some(task_id)- } else {- None- };- // Pre-run drain so a steer/collect queued before the turn started lands- // ahead of the first model call.- if let Some(queue) = run_queue.clone() {- steering_forwarder::forward_steers(&queue, &handle, &steer_thread_label).await;- steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;- }- ctx = ctx.with_steering(handle.clone());- Some(steering_forwarder::SteeringForwarderGuard::new(- handle,- run_queue,- registry_task_id,- steer_thread_label.clone(),- ))- } else {- None- };-- // Heap-allocate the harness drive future. It is large (it owns the whole run- // context, middleware stack, and loop state), and a sub-agent turn runs- // 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.- let resolved_route_slot = run_context.resolved_route.clone();- let run_result = if let Some((base, agent_id)) = hosted_root {- let tool_sets = hosted_tool_sets.expect("hosted root retained its tool sets");- let mut host_bundle =- crate::agent::tinyagents::host::OpenHumanHostBundleFactory::build_for_invocation(- crate::agent::tinyagents::host::OpenHumanHostInvocationInputs {- base,- tool_sets,- tool_policy: tool_policy- .as_ref()- .map(|policy| Arc::new(policy.session.clone())),- model_resolver: hosted_model_resolver,- },- &run_context,- );- // The root session has already assembled its exact system prompt,- // learned context and history before this graph runs. Keep those bytes- // as the hosted request rather than composing/recalling a second copy;- // the host still owns definition resolution, security, model routing,- // budgets, progress and outcome classification for this invocation.- host_bundle.capabilities.context = Arc::new(PrecomposedRootContext);- host_bundle.capabilities.memory = None;- host_bundle.capabilities.experience = None;- // Session finalization owns the full-fidelity hook payload (including- // sanitized per-tool outcomes). The generic names-only summary would- // otherwise fire the same hooks a second time.- host_bundle.capabilities.learning = None;-- let invocation = AgentInvocation::new(- host_bundle.capabilities,- AgentTurnRequest::new(agent_id, input),- ctx,- )- .with_runtime(InvocationRuntime::new(harness));- let state = ();- if streaming {- let stream = root_hosted_harness()- .invoke_agent_stream(invocation, &state)- .await;- match stream {- Ok(mut stream) => {- let mut terminal = None;- while let Some(item) = stream.next().await {- match item {- AgentStreamItem::Event(_) => {}- AgentStreamItem::Completed(run) => {- terminal = Some(Ok(*run));- break;- }- AgentStreamItem::Failed { error, .. } => {- terminal =- Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));- break;- }- }- }- terminal.unwrap_or_else(|| {- Err(tinyagents_harness::TinyAgentsError::Model(- "hosted agent stream ended without terminal run".to_string(),- ))- })- }- Err(error) => Err(error),- }- } else {- root_hosted_harness().invoke_agent(invocation, &state).await- }- } else if streaming {- let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));- let mut terminal = None;- while let Some(item) = stream.next().await {- match item {- AgentStreamItem::Event(_) => {}- AgentStreamItem::Completed(run) => {- terminal = Some(Ok(*run));- break;- }- AgentStreamItem::Failed { error, .. } => {- terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));- break;- }- }- }- terminal.unwrap_or_else(|| {- Err(tinyagents_harness::TinyAgentsError::Model(- "tinyagents stream ended without terminal run".to_string(),- ))- })- } else {- Box::pin(harness.invoke_in_context(&(), ctx, input)).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- // journal/mapping work. On a *cancelled* turn this line is never reached; the- // guard's `Drop` fires as the turn future unwinds, giving identical cleanup.- drop(steering_forwarder_guard);- let run = match run_result {- Ok(run) => run,- Err(e) => {- return Err(map_turn_run_error(- e,- model,- max_iterations,- &error_slot,- turn_journal.as_ref(),- )- .await);- }- };-- let resolved_route = resolved_route_slot- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .clone();- Ok(finalize_turn_outcome(- run,- model,- max_iterations,- &subagent_scope,- pause_at_cap,- turn_journal.as_ref(),- compression_mw.as_ref(),- prompt_cache_guard.as_ref(),- turn_completed_sink,- bridge,- early_exit_hook,- &halt_summary,- &wrap_up_fired,- &tool_outcome_sink,- resolved_route,- request_base_len,- )- .await)-}