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
Merge remote-tracking branch 'origin/epic/8088-tinyagents-slim' into epic-8088-final-rollup
Steven Enamakel73dc486a466a
diff --cc crates/openhuman-core/src/agent/session_host/driver/execute.rsindex 0000000000,9d50084cea..b90d1db262mode 000000,100644..100644--- a/crates/openhuman-core/src/agent/session_host/driver/execute.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/execute.rs@@@ -1,0 -1,450 +1,452 @@@+ use super::*;++ #[async_trait]+ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {+ async fn execute(+ &self,+ mut request: DriverRequest<OpenHumanRunContext>,+ ) -> Result<DriverOutcome, DriverFailure> {+ // Use the policy and context prepared for this exact request.+ let tool_policy = request+ .run_context+ .data+ .tool_policy+ .clone()+ .ok_or_else(|| {+ driver_failure("session turn is missing its request-scoped tool policy")+ })?;+ let mut context_mw = request+ .run_context+ .data+ .context_middleware+ .clone()+ .ok_or_else(|| driver_failure("session turn is missing its request-scoped context"))?;+ let hosted_base = self.hosted_base.clone().ok_or_else(|| {+ driver_failure(+ "hosted root invocation is unavailable because the session has no hosted authority",+ )+ })?;+ let security = crate::agent::tinyagents::host::OpenHumanSecurityGate::new(+ hosted_base.security_policy.clone(),+ Vec::new(),+ )+ .with_input_screening(!request.run_context.data.untrusted_input_turn)+ .with_approval(request.run_context.data.approval.clone())+ .with_dispatch(request.run_context.data.dispatch_ctx());+ let (_, block_reason) = security+ .screen_new_user_row(&mut request.history)+ .await+ .map_err(|error| driver_failure(error.to_string()))?;+ if let Some(reason) = block_reason {+ return Err(DriverFailure {+ error: RuntimeError::Driver(reason),+ partial: None,+ outcome: None,+ });+ }+ // Snapshot the request boundary before assembling the graph so errors+ // persist only provider-accepted rounds.+ let snapshot = context_mw+ .transcript_snapshot+ .get_or_insert_with(|| {+ Arc::new(std::sync::Mutex::new(+ crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshot {+ request_base_len: request.history.len(),+ ..Default::default()+ },+ ))+ })+ .clone();+ if let Ok(mut snapshot_state) = snapshot.lock() {+ snapshot_state+ .pricing_model+ .get_or_insert_with(|| self.model_name.clone());+ }+ let sidecar = request.run_context.data.session_sidecar.clone();+ let started = Instant::now();+ let user_message = tinyagents_harness::summarization::last_user_message(&request.history)+ .map(crate::agent::message_convert::user_text_with_markers)+ .unwrap_or_default();+ let context_window = self+ .turn_model_source+ .effective_context_window(&self.model_name)+ .await;+ let turn_models = self+ .turn_model_source+ .build(+ &self.model_name,+ self.temperature,+ context_window,+ request.run_context.data.thread_id.as_deref(),+ )+ .map_err(driver_error)?;++ let mut messages: Vec<TranscriptMessage> = request+ .history+ .iter()+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)+ .collect();+ if crate::agent::multimodal::has_image_placeholders(&messages) {+ messages = crate::agent::multimodal::rehydrate_image_placeholders(&messages).await;+ }++ // Harness `ToolSnapshot` remains the model declaration and final+ // allowlist. The actual executable instances must be supplied by the+ // request hook as well: falling back to a long-lived driver's tool+ // registry would let revoked or hidden tools execute under stale+ // authority.+ let tools = request+ .run_context+ .data+ .current_tools+ .clone()+ .ok_or_else(|| driver_failure("session turn is missing request-scoped tools"))?;+ let synthesized_tools = request+ .run_context+ .data+ .current_synthesized_tools+ .clone()+ .ok_or_else(|| {+ driver_failure("session turn is missing request-scoped synthesized tools")+ })?;+ let visible_tool_names: HashSet<String> = request+ .tools+ .specs()+ .iter()+ .map(|spec| spec.name.clone())+ .collect();+ ensure_snapshot_tools_are_executable(+ &visible_tool_names,+ &tools,+ &synthesized_tools,+ &request.run_context.data.recorded_tool_names,+ )?;+ // Text dialects need the positional registry to recover P-Format and code-style calls.+ let run_context = request.run_context.data.clone().with_tool_dialect(+ tinyagents_harness::dialect::dispatcher_for_format(self.dispatcher.tool_call_format()),+ );+ let cancellation = request.run_context.cancellation.clone();+ // Boxing avoids worker-stack overflow in debug builds.+ let turn = Box::pin(async move {+ let hosted_base = hosted_base.clone();+ let mut run_context = run_context;+ run_context.workspace = self.workspace.clone().or(run_context.workspace);+ run_context.sandbox_mode = Some(self.sandbox_mode);+ let provider_id = turn_models.provider_id().to_string();+ TurnSpec {+ run_context,+ turn_models,+ provider_id,+ model: &self.model_name,+ history: messages,+ // Durable and synthesized tools follow the declared-snapshot order.+ tool_sets: vec![tools, synthesized_tools],+ // `Some(empty)` is deny-all; `None` re-exposes the driver registry.+ allowed: Some(visible_tool_names),+ max_iterations: self.max_iterations,+ subagent_scope: None,+ context_window,+ run_queue: self.run_queue.clone(),+ message_run_queue: None,+ early_exit_tools: &["ask_user_clarification"],+ pause_at_cap: true,- max_output_tokens: Some(crate::inference::provider::AGENT_TURN_MAX_OUTPUT_TOKENS),++ max_output_tokens: Some(++ tinyagents_harness::turn_policy::AGENT_TURN_MAX_OUTPUT_TOKENS,++ ),+ context_mw,+ tool_policy: Some(tool_policy),+ deterministic_cacheable: false,+ defer_turn_completed_to_caller: true,+ }+ .run_hosted(hosted_base, self.agent_id.clone())+ .await+ });+ // A Stop hands provider-accepted rounds back so the runtime retains them (#7715).+ let result = tokio::select! {+ biased;+ _ = cancellation.cancelled() => {+ return Err(driver_cancelled_with_snapshot(+ &snapshot,+ &sidecar,+ started.elapsed(),+ std::mem::take(&mut request.history),+ ));+ }+ result = turn => result,+ };+ let mut outcome = match result {+ Ok(outcome) => outcome,+ Err(error) => {+ return Err(driver_error_with_snapshot(+ error,+ &snapshot,+ &sidecar,+ started.elapsed(),+ ));+ }+ };+ let supplemental_trace = SupplementalTrace::install_for_turn(&sidecar, &mut outcome);++ if outcome.text.trim().is_empty() && outcome.tool_outcomes.is_empty() {+ return Err(driver_error(+ tinyagents_harness::agent_error::AgentError::EmptyProviderResponse {+ iteration: outcome.model_calls,+ },+ ));+ }+ // A late cap pause still marks an empty exhausted loop as capped.+ outcome.hit_cap |= outcome.text.trim().is_empty()+ && (outcome.model_calls >= self.max_iterations+ || outcome.tool_calls >= self.max_iterations+ || outcome.tool_outcomes.len() >= self.max_iterations);+ // Older hosted-harness fallbacks leave the raw counters unavailable.+ // They only occur when the loop exhausted a tool round without a model+ // conclusion, so normalize them to the same resumable cap state.+ let exhausted_fallback = outcome+ .text+ .starts_with("I finished this turn without writing up a result.");+ outcome.hit_cap |= exhausted_fallback;+ // This fallback is not model-authored; replace it with the resumable checkpoint.+ if exhausted_fallback {+ outcome.wrap_up_injected = false;+ }++ // Keep the close and any required-output repair inside the turn deadline.+ let close_by = request.run_context.data.turn_deadline.map(|deadline| {+ let now = Instant::now();+ now + deadline.close_budget(now)+ });+ // A Stop during close or repair also returns accepted rounds (#7776).+ let accepted_history = request.history.clone();+ let stopped = || {+ driver_cancelled_with_snapshot(+ &snapshot,+ &sidecar,+ started.elapsed(),+ accepted_history.clone(),+ )+ };+ let close = tokio::select! {+ biased;+ _ = cancellation.cancelled() => return Err(stopped()),+ close = grounded_close::close_if_needed(+ &self.turn_model_source,+ &self.model_name,+ self.temperature,+ request.run_context.data.thread_id.as_deref(),+ self.dispatcher.as_ref(),+ &request.history,+ &user_message,+ &outcome,+ close_by.map(|at| at.saturating_duration_since(Instant::now())),+ supplemental_trace.as_ref(),+ ) => close,+ };+ let mut output = close+ .as_ref()+ .map(|close| close.output.clone())+ .unwrap_or_else(|| outcome.text.clone());+ // A tools-only loop may reach the close path after the hosted runtime+ // has already dropped its cap metadata. Its generic final-summary+ // fallback is not a completed answer; preserve resumability by making+ // the durable reply an explicit checkpoint.+ if outcome.text.trim().is_empty()+ && output.starts_with("I finished this turn without writing up a result.")+ {+ let results = super::super::product_copy::close_results(&outcome.tool_outcomes);+ let rendered = super::super::product_copy::render_close_results(&results, 4_000);+ output = tinyagents_harness::close::checkpoint_with_copy(+ &super::super::product_copy::OPENHUMAN_CLOSE_COPY,+ self.max_iterations,+ &rendered,+ !results.is_empty(),+ );+ }+ let mut history = request.history;+ let conversation = crate::agent::message_convert::provider_messages_from_conversation(+ self.dispatcher.as_ref(),+ &outcome.conversation,+ );+ let mut appended = crate::agent::message_convert::history_to_messages(&conversation);+ if close.is_some() {+ // A blank or breaker-halt terminal row is not the durable answer.+ // Retain every completed tool round and replace only that final+ // assistant row with the verified/deterministic grounded close.+ if appended+ .last()+ .is_some_and(|message| matches!(message, Message::Assistant(_)))+ {+ appended.pop();+ }+ appended.push(Message::assistant(output.clone()));+ }+ history.extend(appended);++ let required_output = request.run_context.data.required_output.clone();+ let classified_halt = outcome+ .breaker_halt+ .as_deref()+ .is_some_and(|reason| reason.starts_with("Stopping after "));+ let time_left = close_by.map(|at| at.saturating_duration_since(Instant::now()));+ let mut repair_usage = grounded_close::RepairUsage::for_model(&self.model_name);+ let required_repair = match required_output.as_ref() {+ Some(contract) if classified_halt || time_left.is_some_and(|left| left.is_zero()) => {+ append_synthesized_block(&mut output, &mut history, contract);+ None+ }+ Some(contract) => {+ let repaired = {+ let repair = grounded_close::repair_required_output(+ &self.turn_model_source,+ &self.model_name,+ self.temperature,+ request.run_context.data.thread_id.as_deref(),+ self.dispatcher.as_ref(),+ contract,+ &history,+ &output,+ close.is_none() && request.run_context.data.progress.is_some(),+ request.run_context.data.progress.as_ref(),+ outcome.model_calls.saturating_add(1) as u32,+ &mut repair_usage,+ supplemental_trace.as_ref(),+ );+ tokio::pin!(repair);+ tokio::select! {+ biased;+ _ = cancellation.cancelled() => return Err(stopped()),+ repaired = async {+ match time_left {+ // Bound to what is left so the turn still commits;+ // on expiry fall back to the deterministic block.+ Some(left) => tokio::time::timeout(left, &mut repair).await.ok(),+ None => Some((&mut repair).await),+ }+ } => repaired,+ }+ };+ match repaired {+ Some(repaired) => repaired,+ None => {+ append_synthesized_block(&mut output, &mut history, contract);+ None+ }+ }+ }+ None => None,+ };+ if let Some(repaired) = required_repair {+ output = repaired;+ if history+ .last()+ .is_some_and(|message| matches!(message, Message::Assistant(_)))+ {+ history.pop();+ }+ history.push(Message::assistant(output.clone()));+ }++ // This is deliberately an out-of-band observation rather than a+ // second history or transcript. The runtime only reads it from+ // `after_commit`, so a failed/cancelled turn cannot publish its usage+ // or tool outcomes as if they had become durable.+ {+ // Always billed: a repair that timed out after its call answered+ // still recorded that call here.+ let repair_usage = Some(&repair_usage);+ let mut observed = sidecar+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ observed.model_calls = outcome.model_calls+ + close+ .as_ref()+ .map(|close| close.usage.model_calls)+ .unwrap_or_default()+ + repair_usage+ .map(|usage| usage.model_calls)+ .unwrap_or_default();+ observed.tool_calls = outcome.tool_calls;+ observed.input_tokens = outcome.input_tokens+ + close+ .as_ref()+ .map(|close| close.usage.input_tokens)+ .unwrap_or_default()+ + repair_usage+ .map(|usage| usage.input_tokens)+ .unwrap_or_default();+ observed.output_tokens = outcome.output_tokens+ + close+ .as_ref()+ .map(|close| close.usage.output_tokens)+ .unwrap_or_default()+ + repair_usage+ .map(|usage| usage.output_tokens)+ .unwrap_or_default();+ observed.cached_input_tokens = outcome.cached_input_tokens+ + close+ .as_ref()+ .map(|close| close.usage.cached_input_tokens)+ .unwrap_or_default()+ + repair_usage+ .map(|usage| usage.cached_input_tokens)+ .unwrap_or_default();+ let mut cost = outcome.cost;+ if let Some(close) = close.as_ref() {+ cost.merge(close.usage.cost);+ }+ if let Some(repair) = repair_usage {+ cost.merge(repair.cost);+ }+ observed.cost = cost;+ let loop_last_call = snapshot+ .lock()+ .ok()+ .map(|guard| (guard.last_call_input_tokens, guard.last_call_output_tokens));+ (+ observed.last_call_input_tokens,+ observed.last_call_output_tokens,+ ) = grounded_close::final_call_tokens(+ loop_last_call,+ close.as_ref().map(|close| &close.usage),+ repair_usage,+ );+ observed.duration = Some(started.elapsed());+ observed.driver_finished_at = Some(std::time::Instant::now());+ observed.tool_outcomes = outcome.tool_outcomes.clone();+ observed.hit_cap = outcome.hit_cap;+ observed.wrap_up_injected = outcome.wrap_up_injected;+ // Preserve the harness stop reason and the wind-down sidecar marker.+ observed.stop = crate::agent::session_host::stop_policy::classify_stop_with_cause(+ outcome.breaker_halt.as_deref(),+ outcome.failure_cause.clone(),+ observed.wind_down,+ outcome.hit_cap,+ );+ if let Some(stop) = &observed.stop {+ tracing::debug!(+ model = %self.model_name,+ "[session-driver] turn stopped early; recording on the sidecar {}",+ stop.status_message()+ );+ }+ observed.resolved_route = outcome.resolved_route.clone();+ };+ // The turn compacted its context: persist the compacted history, so the+ // next turn starts from the checkpoint. The runtime session seals the+ // current generation and opens the next (the history no longer extends+ // it), so the full conversation stays on disk.+ let history = match &outcome.compaction {+ Some(carry) => carry.apply(history),+ None => history,+ };+ Ok(DriverOutcome {+ history,+ output: Some(output),+ partial: None,+ interrupted: outcome.early_exit_tool.is_some() || outcome.hit_cap,+ // `None` lets the runtime derive the outcome from `interrupted`.+ outcome: None,+ tool_outcomes: outcome.tool_outcomes.clone(),+ })+ }+ }diff --cc crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 7f4d41a2c4,c5208e12e0..61b8289c5b--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@@ -259,310 -227,6 +227,7 @@@ impl OpenHumanSessionHostself.turn_with_origin(user_message, None).await}- pub(in crate::agent::session_host) fn ensure_runtime_session(&mut self) -> Result<()> {- if self.runtime_session.is_some() {- return Ok(());- }- let context_config = &self.context_config;- let tool_result_budget_bytes = context_config.tool_result_budget_bytes;- let tokenjuice_compaction_enabled = context_config.compaction_enabled;- let microcompact_keep_recent = if context_config.microcompact_enabled {- context_config.microcompact_keep_recent- } else {- 0- };- let autocompact_enabled = context_config.enabled && context_config.autocompact_enabled;- let compaction = context_config.compaction_settings();- let artifact_store = crate::agent::harness::tool_result_artifacts::build_artifact_store(- &self.workspace_dir,- &self.event_session_id,- );-- // `[components] juice = false`: truncation only, no compaction/summary.- let juice_on =- (self.runtime_config.as_ref()).is_none_or(|c| crate::inference::tokenjuice::enabled(c));- let context_mw = TurnContextMiddleware {- tool_result_budget_bytes,- payload_summarizer: self.payload_summarizer.clone().filter(|_| juice_on),- // Rooted outside the project; see `artifact_wiring` (#6408, #6483).- artifact_store,- tokenjuice_compaction_enabled: tokenjuice_compaction_enabled && juice_on,- tokenjuice_compression: self.tokenjuice_compression,- runtime_config: self.runtime_config.clone(),- microcompact_keep_recent,- autocompact_enabled,- compaction,- transcript_snapshot: None,- };- let driver = Arc::new(OpenHumanSessionDriver::new(- self.turn_model_source.clone(),- self.tool_dispatcher.clone(),- self.model_name.clone(),- self.temperature,- self.config.max_tool_iterations,- self.model_vision,- self.run_queue.clone(),- self.workspace_descriptor.clone(),- self.resolved_definition()- .map(|definition| definition.sandbox_mode)- .unwrap_or(tinyagents_definition::SandboxMode::None),- self.hosted_base.clone(),- self.agent_definition_id.clone(),- ));- // Thread-bound roots resume their deterministic transcript; other- // turns keep the per-run stem path. Reuse one locator for the initial- // binding and each resume because the runtime compares locator identity.- let injected_locator = self.session_history_locator.clone();- let resume_target = injected_locator- .as_ref()- .map(|locator| match self.session.clone() {- Some(session) => TranscriptTarget::for_session(- Arc::clone(locator),- session,- self.runtime_transcript_meta(),- ),- None => TranscriptTarget::new(- Arc::clone(locator),- self.injected_transcript_stem(),- self.runtime_transcript_meta(),- )- .with_resume_agent(self.agent_definition_name.clone()),- });- {- let mut state = self- .runtime_state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- state.context_middleware = Some(context_mw.clone());- state.required_output = self- .config- .required_output- .as_ref()- .map(crate::agent::tinyagents::config::required_output_from);- state.prelude = Some(self.create_turn_prelude(false));- }- let hooks = Arc::new(OpenHumanSessionHooks::new(- {- let resume_target = resume_target.clone();- let state = self.runtime_state.clone();- move |_, options, _| {- let resume_target = resume_target.clone();- begin_turn_resume(- &mut state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner()),- &mut options.resume,- );- Box::pin(async move {- Ok(ResumePreparation {- transcript: resume_target,- })- })- }- },- {- let state = self.runtime_state.clone();- move |request, options, view| {- let state = state.clone();- let request_base_len = view.history.len()- + usize::from(view.history.last() != Some(&request.input));- Box::pin(async move {- let transcript_snapshot =- crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink::default();- transcript_snapshot- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .request_base_len = request_base_len;- let (prelude, pending_post_commit) = {- let mut state = state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- state.active_terminal_sidecar =- Some(options.run_context.data.session_sidecar.clone());- (state.prelude.clone(), state.pending_post_commit.take())- };- let prelude = prelude.ok_or({- tinyagents_runtime::RuntimeError::MissingDependency(- "OpenHumanTurnPrelude",- )- })?;- // The previous turn's goal accounting was deferred past- // its completion; settle it before this turn reads the goal.- post_commit::await_pending(pending_post_commit).await;- let new_session = !view.resumed && view.history.is_empty();- prelude- .refresh_turn_boundary(new_session)- .await- .map_err(|error| {- tinyagents_runtime::RuntimeError::Driver(error.to_string())- })?;- let context_window = prelude- .turn_model_source- .effective_context_window(&prelude.model_name)- .await- .unwrap_or_default();- options- .run_context- .data- .session_sidecar- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .context_window = context_window;- let original_user_message = user_text_with_markers(&request.input);- prelude.begin_user_effects(request, &options.run_context.data);- let turn = state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .take_turn_inputs();- let origin = options.run_context.data.origin.clone();- let (enriched, memory_turn) = futures::join!(- prelude.enrich_request(- &original_user_message,- &turn,- &mut options.run_context.data,- ),- // Boxed: the hook's future (config load, engine- // calls) would otherwise be inlined into this- // already-large hook future.- Box::pin(prelude.memory_pre_turn(- view.history,- view.committed_turns,- view.history.last().filter(|last| **last == request.input),- origin,- )),- );- options.run_context.data.memory_turn = memory_turn;- request.input = user_message_from_text(&enriched);- let mut preparation = prelude- .prepare_turn(new_session, &view, &transcript_snapshot, request)- .await?;- if turn.overrides.suppress_tools {- // One-off tool-less turn: must not become the- // thread's recorded tool list.- preparation.tools = Some(ToolSnapshot::default().exact());- }- let (- mut current_tools,- mut current_synthesized_tools,- policy_session,- policy_channel,- ) = prelude.current_tool_source();- if turn.overrides.suppress_tools {- current_tools = Arc::new(Vec::new());- current_synthesized_tools = Arc::new(Vec::new());- }- let mut middleware = state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .context_middleware- .clone()- .ok_or({- tinyagents_runtime::RuntimeError::MissingDependency(- "TurnContextMiddleware",- )- })?;- middleware.transcript_snapshot = Some(transcript_snapshot);- options.run_context.data.context_middleware = Some(middleware);- options.run_context.data.current_tools = Some(current_tools);- if !turn.overrides.suppress_tools {- options.run_context.data.deferred_tool_names =- Arc::new(prelude.current_deferred_tool_names());- }- options.run_context.data.current_synthesized_tools =- Some(current_synthesized_tools);- options.run_context.data.tool_rules =- prelude.turn_tool_rules(&policy_channel, &options.run_context.data);- options.run_context.data.tool_policy =- Some(crate::agent::tinyagents::ToolPolicyEnforcement {- policy: prelude.tool_policy.clone(),- session: policy_session,- channel: policy_channel,- agent_definition_id: prelude.agent_definition_id.clone(),- });- options.run_context.data.required_output = state- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())- .required_output- .clone();- Ok(preparation)- })- }- },- |outcome, _| {- Box::pin(async move {- if outcome- .output- .as_deref()- .is_none_or(|output| output.trim().is_empty())- {- return Err(tinyagents_runtime::RuntimeError::Driver(- "driver returned an empty final response after repair".into(),- ));- }- Ok(())- })- },- |_| Box::pin(async { Ok(()) }),- {- let state = self.runtime_state.clone();- move |terminal| {- let state = state.clone();- Box::pin(async move {- let sidecar = post_commit::take_terminal_sidecar(&state, terminal.clone());- if let Some(sidecar) = sidecar {- post_commit::finalize_deferred_terminal(&sidecar, &terminal).await;- }- Ok(())- })- }- },- ));- // Bind the hook's native target early so both thread and latest-agent- // resumes can read recorded declarations before host admission.- let mut builder = SessionBuilder::new(driver)- .codec(Arc::new(OpenHumanTranscriptCodec))- .hooks(hooks)- .post_commit_sink(Arc::new(post_commit::OpenHumanPostCommitSink {- state: self.runtime_state.clone(),- hooks: self.post_turn_hooks.clone(),- identity: post_commit::TurnIdentityOwned {- session_id: self.event_session_id.clone(),- agent_id: self.agent_definition_id.clone(),- channel: self.event_channel.clone(),- },- }))- .retain_recorded_tools(!self.host_only && !self.host_env.fresh_tool_snapshot);- let meta = self.runtime_transcript_meta();- builder = if let Some(locator) = injected_locator {- match self.session.clone() {- Some(session) => builder.session(locator, session, meta),- None => builder- .transcript(locator, self.injected_transcript_stem(), meta)- .resume_agent(self.agent_definition_name.clone()),- }- } else if self.thread_id.is_some() && self.session_parent_prefix.is_none() {- builder.identity_resolver(- self.runtime_session_key(),- meta,- Arc::new(self.session_identity_resolver()),- )- } else {- builder- .transcript(- self.subagent_transcript_locator(),- self.injected_transcript_stem(),- meta,- )- .resume_agent(self.agent_definition_name.clone())- };- self.runtime_session = Some(- builder- .build()- .map_err(|error| anyhow::anyhow!(error.to_string()))?,- );- Ok(())- }+/// Publish a caller-driven visibility/policy mutation into the live hook/// state. The runtime keeps generic snapshots immutable per request; this/// simply replaces the host composition from which the *next* snapshot,diff --cc crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rsindex 0000000000,e36bd8b6d0..84629ac695mode 000000,100644..100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/ensure.rs@@@ -1,0 -1,307 +1,307 @@@+ use super::*;++ impl OpenHumanSessionHost {+ pub(in crate::agent::session_host) fn ensure_runtime_session(&mut self) -> Result<()> {+ if self.runtime_session.is_some() {+ return Ok(());+ }+ let context_config = &self.context_config;+ let tool_result_budget_bytes = context_config.tool_result_budget_bytes;+ let tokenjuice_compaction_enabled = context_config.compaction_enabled;+ let microcompact_keep_recent = if context_config.microcompact_enabled {+ context_config.microcompact_keep_recent+ } else {+ 0+ };+ let autocompact_enabled = context_config.enabled && context_config.autocompact_enabled;+ let compaction = context_config.compaction_settings();+ let artifact_store = crate::agent::harness::tool_result_artifacts::build_artifact_store(+ &self.workspace_dir,+ &self.event_session_id,+ );++ // `[components] juice = false`: truncation only, no compaction/summary.+ let juice_on =+ (self.runtime_config.as_ref()).is_none_or(|c| crate::inference::tokenjuice::enabled(c));+ let context_mw = TurnContextMiddleware {+ tool_result_budget_bytes,+ payload_summarizer: self.payload_summarizer.clone().filter(|_| juice_on),+ // Rooted outside the project; see `tool_result_artifacts` (#6408, #6483).- artifact_store: Some(artifact_store),++ artifact_store,+ tokenjuice_compaction_enabled: tokenjuice_compaction_enabled && juice_on,+ tokenjuice_compression: self.tokenjuice_compression,+ runtime_config: self.runtime_config.clone(),+ microcompact_keep_recent,+ autocompact_enabled,+ compaction,+ transcript_snapshot: None,+ };+ let driver = Arc::new(OpenHumanSessionDriver::new(+ self.turn_model_source.clone(),+ self.tool_dispatcher.clone(),+ self.model_name.clone(),+ self.temperature,+ self.config.max_tool_iterations,+ self.model_vision,+ self.run_queue.clone(),+ self.workspace_descriptor.clone(),+ self.resolved_definition()+ .map(|definition| definition.sandbox_mode)+ .unwrap_or(tinyagents_definition::SandboxMode::None),+ self.hosted_base.clone(),+ self.agent_definition_id.clone(),+ ));+ // Thread-bound roots resume their deterministic transcript; other+ // turns keep the per-run stem path. Reuse one locator for the initial+ // binding and each resume because the runtime compares locator identity.+ let injected_locator = self.session_history_locator.clone();+ let resume_target = injected_locator+ .as_ref()+ .map(|locator| match self.session.clone() {+ Some(session) => TranscriptTarget::for_session(+ Arc::clone(locator),+ session,+ self.runtime_transcript_meta(),+ ),+ None => TranscriptTarget::new(+ Arc::clone(locator),+ self.injected_transcript_stem(),+ self.runtime_transcript_meta(),+ )+ .with_resume_agent(self.agent_definition_name.clone()),+ });+ {+ let mut state = self+ .runtime_state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ state.context_middleware = Some(context_mw.clone());+ state.required_output = self+ .config+ .required_output+ .as_ref()+ .map(crate::agent::tinyagents::config::required_output_from);+ state.prelude = Some(self.create_turn_prelude(false));+ }+ let hooks = Arc::new(OpenHumanSessionHooks::new(+ {+ let resume_target = resume_target.clone();+ let state = self.runtime_state.clone();+ move |_, options, _| {+ let resume_target = resume_target.clone();+ begin_turn_resume(+ &mut state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner()),+ &mut options.resume,+ );+ Box::pin(async move {+ Ok(ResumePreparation {+ transcript: resume_target,+ })+ })+ }+ },+ {+ let state = self.runtime_state.clone();+ move |request, options, view| {+ let state = state.clone();+ let request_base_len = view.history.len()+ + usize::from(view.history.last() != Some(&request.input));+ Box::pin(async move {+ let transcript_snapshot =+ crate::agent::tinyagents::middleware::turn_context::TranscriptSnapshotSink::default();+ transcript_snapshot+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .request_base_len = request_base_len;+ let (prelude, pending_post_commit) = {+ let mut state = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ state.active_terminal_sidecar =+ Some(options.run_context.data.session_sidecar.clone());+ (state.prelude.clone(), state.pending_post_commit.take())+ };+ let prelude = prelude.ok_or({+ tinyagents_runtime::RuntimeError::MissingDependency(+ "OpenHumanTurnPrelude",+ )+ })?;+ // The previous turn's goal accounting was deferred past+ // its completion; settle it before this turn reads the goal.+ post_commit::await_pending(pending_post_commit).await;+ let new_session = !view.resumed && view.history.is_empty();+ prelude+ .refresh_turn_boundary(new_session)+ .await+ .map_err(|error| {+ tinyagents_runtime::RuntimeError::Driver(error.to_string())+ })?;+ let context_window = prelude+ .turn_model_source+ .effective_context_window(&prelude.model_name)+ .await+ .unwrap_or_default();+ options+ .run_context+ .data+ .session_sidecar+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .context_window = context_window;+ let original_user_message = user_text_with_markers(&request.input);+ prelude.begin_user_effects(request, &options.run_context.data);+ let turn = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .take_turn_inputs();+ let origin = options.run_context.data.origin.clone();+ let (enriched, memory_turn) = futures::join!(+ prelude.enrich_request(+ &original_user_message,+ &turn,+ &mut options.run_context.data,+ ),+ // Boxed: the hook's future (config load, engine+ // calls) would otherwise be inlined into this+ // already-large hook future.+ Box::pin(prelude.memory_pre_turn(+ view.history,+ view.committed_turns,+ view.history.last().filter(|last| **last == request.input),+ origin,+ )),+ );+ options.run_context.data.memory_turn = memory_turn;+ request.input = user_message_from_text(&enriched);+ let mut preparation = prelude+ .prepare_turn(new_session, &view, &transcript_snapshot, request)+ .await?;+ if turn.overrides.suppress_tools {+ // One-off tool-less turn: must not become the+ // thread's recorded tool list.+ preparation.tools = Some(ToolSnapshot::default().exact());+ }+ let (+ mut current_tools,+ mut current_synthesized_tools,+ policy_session,+ policy_channel,+ ) = prelude.current_tool_source();+ if turn.overrides.suppress_tools {+ current_tools = Arc::new(Vec::new());+ current_synthesized_tools = Arc::new(Vec::new());+ }+ let mut middleware = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .context_middleware+ .clone()+ .ok_or({+ tinyagents_runtime::RuntimeError::MissingDependency(+ "TurnContextMiddleware",+ )+ })?;+ middleware.transcript_snapshot = Some(transcript_snapshot);+ options.run_context.data.context_middleware = Some(middleware);+ options.run_context.data.current_tools = Some(current_tools);+ if !turn.overrides.suppress_tools {+ options.run_context.data.deferred_tool_names =+ Arc::new(prelude.current_deferred_tool_names());+ }+ options.run_context.data.current_synthesized_tools =+ Some(current_synthesized_tools);+ options.run_context.data.tool_rules =+ prelude.turn_tool_rules(&policy_channel, &options.run_context.data);+ options.run_context.data.tool_policy =+ Some(crate::agent::tinyagents::ToolPolicyEnforcement {+ policy: prelude.tool_policy.clone(),+ session: policy_session,+ channel: policy_channel,+ agent_definition_id: prelude.agent_definition_id.clone(),+ });+ options.run_context.data.required_output = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .required_output+ .clone();+ Ok(preparation)+ })+ }+ },+ |outcome, _| {+ Box::pin(async move {+ if outcome+ .output+ .as_deref()+ .is_none_or(|output| output.trim().is_empty())+ {+ return Err(tinyagents_runtime::RuntimeError::Driver(+ "driver returned an empty final response after repair".into(),+ ));+ }+ Ok(())+ })+ },+ |_| Box::pin(async { Ok(()) }),+ {+ let state = self.runtime_state.clone();+ move |terminal| {+ let state = state.clone();+ Box::pin(async move {+ let sidecar = post_commit::take_terminal_sidecar(&state, terminal.clone());+ if let Some(sidecar) = sidecar {+ post_commit::finalize_deferred_terminal(&sidecar, &terminal).await;+ }+ Ok(())+ })+ }+ },+ ));+ // Bind the hook's native target early so both thread and latest-agent+ // resumes can read recorded declarations before host admission.+ let mut builder = SessionBuilder::new(driver)+ .codec(Arc::new(OpenHumanTranscriptCodec))+ .hooks(hooks)+ .post_commit_sink(Arc::new(post_commit::OpenHumanPostCommitSink {+ state: self.runtime_state.clone(),+ hooks: self.post_turn_hooks.clone(),+ identity: post_commit::TurnIdentityOwned {+ session_id: self.event_session_id.clone(),+ agent_id: self.agent_definition_id.clone(),+ channel: self.event_channel.clone(),+ },+ }))+ .retain_recorded_tools(!self.host_only && !self.host_env.fresh_tool_snapshot);+ let meta = self.runtime_transcript_meta();+ builder = if let Some(locator) = injected_locator {+ match self.session.clone() {+ Some(session) => builder.session(locator, session, meta),+ None => builder+ .transcript(locator, self.injected_transcript_stem(), meta)+ .resume_agent(self.agent_definition_name.clone()),+ }+ } else if self.thread_id.is_some() && self.session_parent_prefix.is_none() {+ builder.identity_resolver(+ self.runtime_session_key(),+ meta,+ Arc::new(self.session_identity_resolver()),+ )+ } else {+ builder+ .transcript(+ self.subagent_transcript_locator(),+ self.injected_transcript_stem(),+ meta,+ )+ .resume_agent(self.agent_definition_name.clone())+ };+ self.runtime_session = Some(+ builder+ .build()+ .map_err(|error| anyhow::anyhow!(error.to_string()))?,+ );+ Ok(())+ }+ }diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rsindex 0000000000,950a25afac..ac81233928mode 000000,100644..100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs@@@ -1,0 -1,350 +1,351 @@@+ use super::*;++ impl Default for OpenHumanRunContext {+ fn default() -> Self {+ Self::new()+ }+ }++ impl OpenHumanRunContext {+ /// Builds an unbound context. Entry points set only the values their turn+ /// actually owns; `None` is an explicit absence, not an ambient fallback.+ pub fn new() -> Self {+ Self {+ model_budget: None,+ dispatch_admission: None,+ response_shape: None,+ max_spawn_depth: None,+ origin: None,+ approval: Default::default(),+ progress: None,+ stop_hooks: Vec::new(),++ goal_suppressed: false,+ tool_hooks: Vec::new(),+ tool_call_limit: None,+ untrusted_input_turn: false,+ turn_deadline: None,+ parent: None,+ prepared_context_sources: Arc::new(Vec::new()),+ memory_identity: None,+ core: None,+ hosted_base: None,+ transcripts: None,+ file_state_agent_id: None,+ tool_result_artifact_index: None,+ headless_descendant_settlement: false,+ headless_descendant_owner: None,+ attachment_placeholders: Arc::new(Vec::new()),+ dispatch: None,+ task_recency_window: None,+ command_environment: None,+ autonomous_iter_cap: None,+ sandbox_mode: None,+ spawn_depth: 0,+ subagent_usage: Arc::new(Mutex::new(Vec::new())),+ parent_subagent_usage: None,+ resolved_route: Arc::new(Mutex::new(None)),+ cancellation: tinyagents_harness::cancel::CancellationToken::default(),+ thread_id: None,+ root_run_id: None,+ workspace: None,+ tool_outcomes: None,+ tool_policy: None,+ current_tools: None,+ current_synthesized_tools: None,+ recorded_tool_names: Arc::new(std::collections::HashSet::new()),+ deferred_tool_names: Arc::new(std::collections::HashSet::new()),+ tool_rules: None,+ context_middleware: None,+ session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())),+ required_output: None,+ tool_dialect: tinyagents_harness::config::ToolDispatcher::Auto,+ memory_turn: None,+ }+ }++ /// Returns the registry owner for a spawn. Headless turns retain one+ /// root-scoped owner across native child thread identities so settlement+ /// can see the complete descendant tree. Ordinary chat remains scoped to+ /// the immediate parent session and thread.+ pub(crate) fn subagent_owner_scope(+ &self,+ workspace: &std::path::Path,+ parent_session: &str,+ thread_id: Option<&str>,+ ) -> String {+ if self.headless_descendant_settlement {+ if let Some(owner) = &self.headless_descendant_owner {+ return owner.clone();+ }+ }+ crate::agent::tinyagents::tool_registration::subagent_owner_key(+ workspace,+ parent_session,+ thread_id,+ )+ }++ /// Pins the harness tool dialect to the one the session prompt speaks.+ #[must_use]+ pub(crate) fn with_tool_dialect(+ mut self,+ dialect: tinyagents_harness::config::ToolDispatcher,+ ) -> Self {+ self.tool_dialect = dialect;+ self+ }++ /// Binds the context this run acts under, held weakly so a run kept past its turn never pins the tenant.+ #[must_use]+ pub fn with_core(mut self, core: Option<Arc<crate::core::runtime::CoreContext>>) -> Self {+ self.core = core.as_ref().map(Arc::downgrade);+ self+ }++ /// The dispatch context this run's readers use: its own `core`, else the+ /// calling task's (a run assembled by a caller that did not bind one).+ pub fn dispatch_ctx(&self) -> crate::core::runtime::DispatchCtx {+ crate::core::runtime::DispatchCtx::from_weak(self.core.as_ref())+ }++ /// The connected-identities prompt section, loaded asynchronously under this run's context.+ pub(crate) async fn connected_identities_md(&self) -> String {+ crate::integrations::render_connected_identities_async(&self.dispatch_ctx()).await+ }++ /// Sets the direct TinyTools workspace descriptor for this run.+ pub fn with_workspace(mut self, workspace: tinytools::WorkspaceDescriptor) -> Self {+ self.workspace = Some(workspace);+ self+ }++ /// Creates (once) this host turn's durable-unique root config.+ ///+ /// The returned root id is stable across the session/runtime and hosted+ /// harness boundaries for this one actual turn. Callers creating a new+ /// root must call this once rather than construct a config from a repeated+ /// literal; callers creating children must use [`direct_subagent_child`].+ pub(crate) fn root_run_config(&mut self, kind: &str) -> tinyagents_harness::context::RunConfig {+ let run_id = self+ .root_run_id+ .get_or_insert_with(|| fresh_root_run_config(kind).run_id.as_str().to_owned())+ .clone();+ tinyagents_harness::context::RunConfig::new(run_id)+ }++ /// Binds a direct runner to its explicit parent without exposing the+ /// child-ledger link reserved for recursive [`Self::child`] calls.+ pub(crate) fn with_parent(mut self, parent: ParentExecutionContext) -> Self {+ self.parent = Some(parent);+ self+ }++ /// Installs this turn's parent snapshot, binding the run's live progress+ /// sink to it.+ ///+ /// The snapshot is built from a prelude that captured `on_progress` when+ /// the runtime session was first created. A web-chat turn checks out a+ /// cached session — so that build is a no-op — and only afterwards calls+ /// `set_on_progress`, leaving the prelude's copy `None` for the rest of the+ /// session's life. Sub-agent spawn and completion are the only progress+ /// events that ride this parent sink instead of the harness event+ /// projection, so a stale `None` drops them outright: no `subagent_spawned`+ /// socket event, no run-ledger row, and a "Background tasks" panel that+ /// reads "none running" while sub-agents are working. The run context's own+ /// sink is the live one (it is what `driver.rs` hands the turn graph), so+ /// prefer it and keep the snapshot as the fallback.+ ///+ /// Returns the installed parent so a caller that must launch a sub-agent+ /// *before* the rest of the turn is assembled — `inject_triggered_memory_agent_context`+ /// is the one such caller — hands it the bound context rather than the+ /// stale snapshot it started from.+ pub(crate) fn attach_parent(+ &mut self,+ mut parent: ParentExecutionContext,+ ) -> &ParentExecutionContext {+ parent.on_progress = self.progress.clone().or(parent.on_progress);+ self.parent.insert(parent)+ }++ /// The callbacks and caps this turn's harness assembly installs.+ pub(crate) fn harness_host_policy(&self) -> HarnessHostPolicy {+ HarnessHostPolicy {+ stop_hooks: self.stop_hooks.clone(),+ tool_hooks: self.tool_hooks.clone(),+ tool_call_cap: self.tool_call_limit,+ }+ }++ /// The real tool invocation budget for a turn of `max_iterations`: the+ /// product default, narrowed by the host's explicit cap.+ pub(crate) fn tool_call_limit_for(&self, max_iterations: usize) -> usize {+ crate::agent::tinyagents::turn_policy::tool_call_limit(max_iterations, self.tool_call_limit)+ }++ /// Applies the host environment an entry point handed to the session:+ /// shared budget, delegation depth, cancellation, deadline and hooks.+ #[must_use]+ pub(crate) fn with_host_env(mut self, env: &crate::agent::turn_env::HostTurnEnv) -> Self {+ self.model_budget = env.model_budget.clone().or(self.model_budget);+ self.dispatch_admission = env.dispatch_admission.clone().or(self.dispatch_admission);+ self.max_spawn_depth = env.spawn_depth_limit.or(self.max_spawn_depth);+ if let Some(cancellation) = &env.cancellation {+ self.cancellation = cancellation.clone();+ }+ self.turn_deadline = env.turn_deadline.or(self.turn_deadline);+ self.tool_call_limit = env.tool_call_limit.or(self.tool_call_limit);+ self.command_environment = env.command_environment.clone().or(self.command_environment);+ self.memory_identity = env.memory_identity.clone().or(self.memory_identity);+ self.core = env.core.clone().or(self.core);+ self.stop_hooks+ .extend(env.hooks.stop_hooks().iter().cloned());+ self.tool_hooks+ .extend(env.hooks.tool_hooks().iter().cloned());+ self+ }++ /// Sets the same cancellation token on this context and its TinyAgents run.+ pub fn with_cancellation(+ mut self,+ cancellation: tinyagents_harness::cancel::CancellationToken,+ ) -> Self {+ self.cancellation = cancellation;+ self+ }++ /// Builds a child context that inherits authority, cancellation and shared+ /// workspace policy while keeping route observation and usage isolated.+ pub fn child(&self) -> Self {+ let mut child = self.clone();+ child.spawn_depth = self.spawn_depth.saturating_add(1);+ child.file_state_agent_id = None;+ child.parent_subagent_usage = Some(self.subagent_usage.clone());+ child.subagent_usage = Arc::new(Mutex::new(Vec::new()));+ child.resolved_route = Arc::new(Mutex::new(None));+ child.memory_turn = None;+ child.response_shape = None;+ child+ }++ /// Builds the explicit carrier for detached background work.+ ///+ /// A detached task keeps the authority, thread and workspace descriptor it+ /// needs to execute and deliver its own result, but it is no longer part of+ /// the originating turn's dispatch timer or subagent usage roll-up. It+ /// still inherits the shared monetary budget and physical-dispatch policy,+ /// and it does not observe cancellation that only stopped the interactive+ /// turn.+ pub fn detached_child(&self) -> Self {+ let mut child = self.child();+ // The chat surface belongs to the turn that started it. A detached+ // child's parks route through the origin and are marked detached, so+ // their cards survive the parent turn's end (#5499).+ child.approval = Default::default();+ child.dispatch = None;+ child.subagent_usage = Arc::new(Mutex::new(Vec::new()));+ child.parent_subagent_usage = None;+ // Detached work has its own terminal boundary; its typed refusal must+ // never be mistaken for the interactive parent's failure.+ child.session_sidecar = Arc::new(Mutex::new(SessionTurnSidecar::default()));+ child.cancellation = tinyagents_harness::cancel::CancellationToken::new();+ child.headless_descendant_settlement = false;+ child.headless_descendant_owner = None;+ child+ }++ /// Converts this host context into TinyAgents' canonical run context.+ ///+ /// The canonical context receives the exact same cancellation and direct+ /// `tinytools::WorkspaceDescriptor`; no type alias, re-export or task-local+ /// bridge is involved.+ pub fn into_tinyagents(+ mut self,+ mut config: tinyagents_harness::context::RunConfig,+ ) -> tinyagents_harness::context::RunContext<Self> {+ // Imported transport facts and explicit child context must survive entry+ // into the native driver, which scopes the depth recorded in RunConfig.+ let depth = config+ .depth()+ .max(self.spawn_depth)+ .max(tinyagents_harness::context::current_run_depth().map_or(0, |facts| facts.depth));+ self.spawn_depth = depth;+ config = config.with_depth(depth);+ if config.thread_id.is_none() {+ if let Some(thread_id) = self.thread_id.as_deref() {+ config = config.with_thread(thread_id);+ }+ }+ let cancellation = self.cancellation.clone();+ let workspace = self.workspace.clone();+ let run_ext = OpenHumanRunExt::from_run_context(&self);+ let host_operations = Arc::new(HostOperationContext {+ origin: self.origin.clone(),+ approval: self.approval.clone(),+ sandbox_mode: self.sandbox_mode,+ parent_agent_id: self+ .parent+ .as_ref()+ .map(|parent| parent.agent_definition_id.clone()),+ memory_identity: self.memory_identity.clone(),+ memory_turn: self.memory_turn.clone(),+ core: self.core.clone(),+ });+ let context = tinyagents_harness::context::RunContext::new(config, self)+ .with_cancellation(cancellation)+ .with_state_view(host_operations)+ .with_host(run_ext);+ match workspace {+ Some(workspace) => context.with_workspace(workspace),+ None => context,+ }+ }++ /// Records a child usage entry without relying on a task-local collector.+ pub fn append_subagent_usage(&self, entry: SubagentUsageEntry) {+ self.subagent_usage+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .push(entry);+ }++ /// Record a completed child on the immediate parent's ledger. This makes+ /// completed children visible at the root without leaking siblings into one+ /// another's in-flight ledger. Direct/root callers retain their own entry.+ pub fn record_completed_subagent_usage(&self, entry: SubagentUsageEntry) {+ let ledger = self+ .parent_subagent_usage+ .as_ref()+ .unwrap_or(&self.subagent_usage);+ ledger+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .push(entry);+ }++ /// Snapshot child totals after the child has returned. A snapshot, rather+ /// than a task-local drain, preserves totals even when sibling futures are+ /// cancelled or one child fails after another has completed.+ pub fn subagent_usage_entries(&self) -> Vec<SubagentUsageEntry> {+ self.subagent_usage+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .clone()+ }++ /// Promote already-completed descendants when this run cannot produce its+ /// own terminal outcome. This is intentionally a snapshot: callers invoke+ /// it only from one terminal finalizer, so every completed descendant is+ /// promoted once without exposing a shared, in-flight sibling ledger.+ pub fn promote_completed_descendant_usage(&self) {+ for entry in self.subagent_usage_entries() {+ self.record_completed_subagent_usage(entry);+ }+ }++ /// Resolves whether a file-state scope has been assigned to this context.+ /// Keeping the conversion here makes file-state callers use the explicit+ /// context instead of discovering an ambient identifier.+ pub fn file_state_agent_id(&self) -> Option<String> {+ self.file_state_agent_id.clone()+ }+ }diff --cc crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rsindex 0000000000,1d7524c49e..606c556c65mode 000000,100644..100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec/drive.rs@@@ -1,0 -1,493 +1,503 @@@+ use super::*;++ #[path = "drive/controls.rs"]+ mod controls;+ #[path = "drive/setup.rs"]+ mod setup;+ #[path = "drive/stores.rs"]+ mod stores;++ pub(super) async fn drive_turn(+ spec: TurnSpec<'_>,+ hosted_root: Option<(+ Arc<crate::agent::tinyagents::host::OpenHumanHostBase>,+ String,+ )>,+ native_subagent: Option<NativeSubagentRunContext>,+ ) -> Result<TinyagentsTurnOutcome> {+ let TurnSpec {+ mut run_context,+ turn_models,+ provider_id,+ model,+ history,+ tool_sets,+ allowed,+ max_iterations,+ subagent_scope,+ context_window,+ run_queue,+ message_run_queue,+ early_exit_tools,+ pause_at_cap,+ max_output_tokens,+ context_mw,+ tool_policy,+ deterministic_cacheable,+ defer_turn_completed_to_caller,+ } = spec;+ // 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);+ let native_security_gate = if hosted_root.is_none() {+ native_subagent.as_ref().and_then(|native| {+ run_context.hosted_base.as_ref().map(|base| {+ let mut gate = crate::agent::tinyagents::host::OpenHumanSecurityGate::new(+ base.security_policy.clone(),+ tool_sets.clone(),+ )+ .with_input_screening(!run_context.untrusted_input_turn)+ .with_approval(run_context.approval.clone())+ .with_dispatch(run_context.dispatch_ctx())+ .with_headless_descendant_settlement(run_context.headless_descendant_settlement);+ if let Some(policy) = tool_policy.as_ref() {+ gate = gate.with_tool_policy(Arc::new(policy.session.clone()));+ }+ (Arc::new(gate), native.name.clone())+ })+ })+ } else {+ None+ };+ let is_hosted_root = hosted_root.is_some();+ let hosted_security_gate = is_hosted_root || native_security_gate.is_some();+ let is_local = turn_models.is_local();+ // Wrap concrete routes before the invocation-local hosted resolver captures them.+ let turn_models = turn_models.with_host_controls(+ run_context.model_budget.as_ref(),+ run_context.dispatch_admission.clone(),+ );+ let hosted_model_resolver = hosted_root.as_ref().map(|_| {+ Arc::new(turn_models.resolver()) as Arc<dyn tinyagents_harness::host::ModelResolver<()>>+ });+ // The host security adapter must see the exact same `Arc`-shared instances+ // the registration resolves against, 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());+ // Retained for the event bridge (cheap `Arc` clones — never the tools+ // themselves) so it can resolve a live `&dyn Tool` by name and call the+ // tool's OWN `display_label`/`display_detail` instead of only ever+ // guessing from the bare name (issue: tool-call presentation).+ let bridge_tool_sets = tool_sets.clone();+ // A turn runs on a chat thread exactly when its run context carries one;+ // `into_tinyagents` stamps that id onto the `RunConfig` the tools read.+ // Thread-scoped tools (`goal_*`) are only registered when it is `Some`.+ let has_thread = run_context.thread_id.is_some();+ let is_subagent = subagent_scope.is_some();+ let (mut policy, has_route_fallback) = turn_run_policy(+ model,+ max_iterations,+ deterministic_cacheable,+ is_local,+ run_context.tool_dialect,- crate::inference::reasoning::turn_reasoning_for(++ crate::agent::tinyagents::thread_reasoning::turn_reasoning_for(+ &run_context,+ hosted_root.as_ref().map(|(base, _)| base.config.as_ref()),+ max_output_tokens,+ ),+ run_context.tool_rules.clone(),+ run_context.tool_call_limit,+ );+ // A `tool_search` of this turn tells its ranker which chat it runs in, so a+ // cloud embedder's disclosure reaches that chat.+ policy.discovery.rank_context =+ crate::agent::tinyagents::discovery::rank_context_for(run_context.approval.chat.as_ref());+ // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry id are built by+ // the caller via `build_turn_models`: the seam is crate-native and names no `Provider` (#4249,+ // Phase 5). The telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.+ let TurnModels {+ primary,+ routes: tier_routes,+ summarizer: summarizer_model,+ error_slot,+ ..+ } = turn_models;+ let plan_models =+ turn_models_for_plan(model, primary, tier_routes, &error_slot, is_hosted_root);+ let planner = OpenHumanTurnPlanner {+ models: plan_models.clone(),+ policy,+ tool_sets: tool_sets.clone(),+ allowed: allowed.clone(),+ has_thread,+ session_deferred: Arc::clone(&run_context.deferred_tool_names),+ };+ let driver = TurnDriver::<(), OpenHumanRunContext>::new(Arc::new(planner), Arc::new(()));++ // Shared slots the middleware writes and the event bridge / finalizer read.+ // They are created here, not by the middleware installer, because the run+ // context (built before the harness is prepared) carries two of them.+ let cursor: tinyagents_harness::events::IterationCursor = Arc::default();+ let tool_names: crate::agent::tinyagents::observability::ToolNameMap = Arc::default();+ let failure_map: crate::agent::tinyagents::observability::ToolFailureMap = Arc::default();+ let provider_usage_carry: crate::agent::tinyagents::observability::ProviderUsageCarry =+ Arc::default();+ let tool_outcome_sink: ToolOutcomeSink = Arc::new(std::sync::Mutex::new(Vec::new()));+ let tool_result_artifact_index = context_mw+ .artifact_store+ .as_ref()+ .map(|_| Arc::new(ToolResultArtifactIndexStore::new()));++ // The hosted graph is the execution boundary of the same root turn the+ // runtime/session already created. Retain that root config id here instead+ // of manufacturing a second literal `agent_turn` root. The driver adds the+ // `scope:root` / `scope:subagent` tag.+ let (config, journal_run_id) = setup::run_config(+ &mut run_context,+ native_subagent.as_ref(),+ is_subagent,+ on_progress.is_some(),+ max_iterations,+ max_output_tokens,+ model,+ );++ 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_host`) paths.+ let request_base_len = input.len();++ // Build the run context: an event sink feeds the progress/cost bridge, the+ // journal and the cap pauser; the driver's steering handle carries+ // mid-flight, early-exit and cap pauses.+ 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);+ if native_subagent.is_some() {+ // The prepared child context carries the parent's sink. Never attach+ // child model/tool records to it: those records have run-local offsets+ // and the parent run id. Emit the lifecycle link through that sink.+ ctx.events = EventSink::with_stream_id(journal_run_id.as_str());+ }+ let run_instance_id = ctx.instance_id();+ ctx = if let Some(stores) =+ stores::attach(&run_context, tool_result_artifact_index.clone()).await+ {+ ctx.with_stores(stores)+ } else {+ ctx+ };++ let streaming = on_progress.is_some();+ let turn_completed_sink =+ setup::turn_completed_sink(&on_progress, is_subagent, defer_turn_completed_to_caller);+ let sink = setup::event_sink(&journal_run_id, native_subagent.as_ref());+ let bridge = setup::event_bridge(+ &sink,+ on_progress,+ model,+ provider_id.clone(),+ max_iterations,+ subagent_scope.clone(),+ &cursor,+ &tool_names,+ &failure_map,+ &provider_usage_carry,+ bridge_tool_sets.clone(),+ &run_context,+ );++ // 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 = journal::attach_turn_journal(+ &run_context.dispatch_ctx(),+ &sink,+ model,+ journal_run_id.clone(),+ journal_thread_id,+ ctx.config.lineage.parent_run_id.clone(),+ ctx.config.lineage.root_run_id.clone(),+ )+ .await;+ if let Some(native) = &native_subagent {+ *native+ .child_journal+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = turn_journal.clone();+ }+ if !is_subagent {+ if let Some(crate::security::turn_origin::AgentTurnOrigin::WebChat {+ request_id: Some(request_id),+ ..+ }) = run_context.origin.as_ref()+ {+ journal::register_request_journal_run(+ &run_context.dispatch_ctx(),+ request_id,+ journal_run_id.as_str(),+ );+ }+ }+ ctx = ctx.with_events(sink.clone());++ // Per-turn controls for the driver. Best-effort thread label for the+ // delivery/requeue observability events and the metadata on any requeued+ // steer: a sub-agent uses its task id; the interactive/channel parent turn+ // reads the turn origin.++ let controls = controls::build(+ max_iterations,+ pause_at_cap,+ early_exit_tools,+ subagent_scope.clone(),+ message_run_queue,+ run_queue,+ is_subagent,+ &run_context,+ );+ let request = DriverRequest {+ history: input,+ // A turn driven outside a `Session` has no frozen declaration set; the+ // planner disables the snapshot comparison.+ tools: ToolSnapshot::new(Vec::new()).map_err(|error| anyhow::anyhow!("{error}"))?,+ run_context: ctx,+ stream: streaming,+ controls,+ };+ let mut prepared = driver.prepare(request).await.map_err(|failure| {+ tracing::error!(error = %failure.error, "[tinyagents] turn driver could not prepare the turn");+ anyhow::anyhow!("{}", failure.error)+ })?;+ let steering =+ prepared.run_context.steering.clone().ok_or_else(|| {+ anyhow::anyhow!("turn driver prepared a run without a steering handle")+ })?;+ let tool_count = prepared.tools().registered.len();+ // A turn without the `todo` tool (tools suppressed, or `todo` not admitted)+ // cannot tick its plan, so it gets no plan-order middleware.+ let todo_registered = prepared+ .tools()+ .registered+ .iter()+ .any(|name| name == "todo");++ let candidate_names = prepared.tools().plan.candidates.clone();+ let TurnWiring {+ halt_summary,+ wrap_up_fired,+ compression_mw,+ prompt_cache_guard,+ } = install_turn_middleware(+ &mut prepared.harness,+ &steering,+ TurnMiddlewareInputs {+ provider_id: provider_id.clone(),+ model: model.to_string(),+ tool_sets,+ allowed,+ candidate_names,+ subagent_scope: subagent_scope.clone(),+ context_window,+ context_mw,+ host_policy: run_context.harness_host_policy(),+ tool_policy: tool_policy.clone(),- required_capabilities: routes::turn_required_capabilities(model),++ required_capabilities: tinyagents_registry::WorkloadRouter::from_workload_routes(++ "hint:vision",++ )++ .required_capabilities(model),+ deterministic_cacheable,+ has_route_fallback,+ dispatch: run_context.dispatch_ctx(),+ hosted_security_gate,+ native_security_gate,+ pause_at_cap,+ run_mode: run_context.thread_id.as_deref().map(|thread_id| {+ crate::threads::run_mode::handle_for_thread(&run_context.dispatch_ctx(), thread_id)+ }),+ memory_turn: run_context.memory_turn.clone(),+ summarizer_model,+ failure_map: failure_map.clone(),+ provider_usage_carry: provider_usage_carry.clone(),+ tool_outcome_sink: tool_outcome_sink.clone(),+ // The store the `todo` tool resolves from the same parent context.+ todo_store: run_context+ .parent+ .as_ref()+ .filter(|_| todo_registered)+ .map(|parent| {+ crate::storage::sessions::stores_or_ephemeral(&parent.workspace_dir).kv+ }),+ compaction_notice: Some({+ let bridge = bridge.clone();+ Arc::new(move || bridge.announce_compaction())+ }),++ state_store: run_context.parent.as_ref().map(|parent| {++ (++ crate::storage::sessions::stores_or_ephemeral(&parent.workspace_dir).kv,++ parent.session_id.clone(),++ )++ }),++ goal_suppressed: run_context.goal_suppressed,+ },+ );+ if let Some(scope) = run_context.response_shape.clone() {+ tinyagents_harness::middleware::install_response_shape(&mut prepared.harness, scope);+ }+ super::super::budget::install_depth(&mut prepared.harness, &run_context);+ super::super::deadline_wind_down::install(+ &mut prepared.harness,+ &Some(steering.clone()),+ &run_context,+ &subagent_scope,+ );+ turn_observer::install(&mut prepared.harness, &sink, is_hosted_root);++ // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).+ // The projected `CapabilityRegistry` produced these diagnostics while the+ // turn was planned; enforce them here, *before* the first model dispatch, so+ // an ambiguous/broken tool surface (duplicate name across native/MCP/Composio/+ // generated tools, dangling alias, etc.) aborts the turn instead of silently+ // resolving to an unintended component while a provider call is in flight.+ let registry_diagnostics = capability_diagnostics(+ &plan_models,+ &bridge_tool_sets,+ &prepared.tools().plan.admitted,+ );+ if let Err(error) = enforce_registry_diagnostics(®istry_diagnostics) {+ // Settle the driver's steering registration before the turn aborts.+ let _ = prepared.split().1.finish(None);+ return Err(error);+ }+ tracing::debug!(+ model,+ tools = tool_count,+ "[tinyagents] turn harness assembled"+ );++ // Heap-allocate the harness drive future. It is large (it owns the whole run+ // context, middleware stack, and loop state), and a sub-agent turn runs+ // 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, early_exit) = 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+ .expect("hosted root retained its selected model resolver"),+ },+ &run_context,+ );+ 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 (parts, tail) = prepared.split();+ let invocation = AgentInvocation::new(+ host_bundle.capabilities,+ AgentTurnRequest::new(agent_id, parts.history),+ parts.run_context,+ )+ .with_replayed_prefix(request_base_len.saturating_sub(1))+ .with_runtime(InvocationRuntime::new(parts.harness));+ let state = ();+ // Both surfaces return the harness's typed `HostedError`, so a timeout,+ // a limit and a provider failure keep their kind through the turn error+ // and `web_errors` can classify them (#6375). Draining+ // `invoke_agent_stream` instead would collapse every failure to one+ // sanitized string. Streaming still drives every model call through+ // `ChatModel::stream`; this path reads only the terminal run.+ let hosted = root_hosted_harness();+ let outcome = if streaming {+ hosted.invoke_agent_streaming(invocation, &state).await+ } else {+ hosted.invoke_agent(invocation, &state).await+ };+ let outcome = outcome.map_err(|error| {+ tracing::debug!(+ kind = ?error.kind,+ streaming,+ "[tinyagents] hosted root turn failed; keeping the typed kind"+ );+ super::super::hosted_error::run_error_from_hosted(error)+ });+ // Stop forwarding and deregister now: the poll loop must not 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.+ let report = tail.finish(outcome.as_ref().ok());+ (outcome, report.early_exit)+ } else {+ let run = Box::pin(prepared.run()).await;+ let early_exit = run.report.early_exit;+ (+ match run.partial.error {+ Some(error) => Err(error),+ None => Ok(run.partial.run),+ },+ early_exit,+ )+ };+ 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();+ let outcome = finalize_turn_outcome(+ run,+ model,+ max_iterations,+ &subagent_scope,+ pause_at_cap,+ turn_journal.as_ref(),+ &sink,+ defer_turn_completed_to_caller || native_subagent.is_some(),+ compression_mw.as_ref(),+ prompt_cache_guard.as_ref(),+ turn_completed_sink,+ Some(bridge),+ early_exit,+ &halt_summary,+ &wrap_up_fired,+ run_instance_id,+ &tool_outcome_sink,+ resolved_route,+ request_base_len,+ &run_context.dispatch_ctx(),+ journal_run_id,+ )+ .await;+ Ok(outcome)+ }diff --cc vendor/tinyjuiceindex 96dff78f4d,6bef05b294..e9aa90fa5f--- a/vendor/tinyjuice+++ b/vendor/tinyjuice@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 96dff78f4d74a3399aadee5da218e61483b35571-Subproject commit 6bef05b294dab09375d61cb3bbc78d664feab6f0++Subproject commit e9aa90fa5fc87511c3e59fea93a800cc12959b41diff --cc vendor/tinyvoiceindex 9ed9c2eb79,e6de2bfa5b..c25a9960cf--- a/vendor/tinyvoice+++ b/vendor/tinyvoice@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 9ed9c2eb79198ad4eed9d88c787c03d554f816dd-Subproject commit e6de2bfa5b783a8c26bf9ceedff70477eecc1af9++Subproject commit c25a9960cfed35eaf4c69050bae65ac6f3c7c9d7