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
feat(agent): add explicit host context bundle
Steven Enamakelf33a398faaae
diff --git a/crates/openhuman-core/src/agent/harness/agent_graph.rs b/crates/openhuman-core/src/agent/harness/agent_graph.rsindex 746e12c179..9844a7bdd7 100644--- a/crates/openhuman-core/src/agent/harness/agent_graph.rs+++ b/crates/openhuman-core/src/agent/harness/agent_graph.rs@@ -22,7 +22,7 @@ use std::path::PathBuf;use std::pin::Pin;use std::sync::Arc;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;use tokio::sync::mpsc::Sender;use crate::agent::harness::run_queue::RunQueue;diff --git a/crates/openhuman-core/src/agent/harness/fork_context.rs b/crates/openhuman-core/src/agent/harness/fork_context.rsindex 17ba165931..08d1c9df1a 100644--- a/crates/openhuman-core/src/agent/harness/fork_context.rs+++ b/crates/openhuman-core/src/agent/harness/fork_context.rs@@ -18,7 +18,7 @@ use crate::skills::Workflow;use std::collections::HashSet;use std::path::PathBuf;use std::sync::Arc;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;use tinytools::{Tool, ToolSpec};// ─────────────────────────────────────────────────────────────────────────────diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rsindex 5447876b59..652da75d5f 100644--- a/crates/openhuman-core/src/agent/harness/graph.rs+++ b/crates/openhuman-core/src/agent/harness/graph.rs@@ -16,7 +16,7 @@//!//! **Available tools.** Reuses the bus handler's `Arc`-shared tool sets//! (`tools_registry: Arc<Vec<Box<dyn Tool>>>` + per-turn `extra_tools`),-//! advertised via `SharedToolAdapter`+//! advertised via the canonical shared-tool adapter//! and filtered by `visible_tool_names`. `ask_user_clarification` is the//! early-exit tool: it pauses the turn and returns its question as the turn's//! text, which the channel relays as the reply.diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs b/crates/openhuman-core/src/agent/harness/session/builder/factory.rsindex d3550f4f23..e4e2fc9770 100644--- a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs+++ b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs@@ -384,7 +384,7 @@ impl Agent {let before = tools.len();tools.retain(|tool| {tool.permission_level() <= PermissionLevel::ReadOnly- && !matches!(tool.scope(), ToolScope::CliRpcOnly)+ && !matches!(tool.scope(), tinytools::ToolScope::CliRpcOnly)});log::info!("[agent::builder] read-only tool filter applied: before={} after={}",@@ -1481,7 +1481,7 @@ pub(crate) fn provider_role_for_definition(pub(crate) fn derive_profile_workspace_descriptor(action_dir: &std::path::Path,profile: Option<&crate::agent::profiles::AgentProfile>,-) -> Option<tinyagents_harness::workspace::WorkspaceDescriptor> {+) -> Option<tinytools::WorkspaceDescriptor> {let (profile_id, dir) = profile.and_then(|p| {crate::agent::profiles::dedicated_workspace_dir(action_dir, p).map(|dir| (p.id.clone(), dir))@@ -1504,13 +1504,12 @@ pub(crate) fn derive_profile_workspace_descriptor("[profiles] session bound to dedicated workspace as default cwd");Some(- tinyagents_harness::workspace::WorkspaceDescriptor::new(dir)+ tinytools::WorkspaceDescriptor::new(dir).with_policy_id(crate::agent::profiles::workspace_policy_id(&profile_id)),)}-fn derive_turn_workspace_descriptor() -> Option<tinyagents_harness::workspace::WorkspaceDescriptor>-{+fn derive_turn_workspace_descriptor() -> Option<tinytools::WorkspaceDescriptor> {let root = crate::agent::turn_workspace::current()?;if !root.is_dir() {tracing::warn!(@@ -1524,10 +1523,7 @@ fn derive_turn_workspace_descriptor() -> Option<tinyagents_harness::workspace::Wroot = %root.display(),"[turn_workspace] turn bound to the embedder's per-turn root as default cwd");- Some(- tinyagents_harness::workspace::WorkspaceDescriptor::new(root)- .with_policy_id("turn-workspace"),- )+ Some(tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"))}fn build_profile_security(diff --git a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs b/crates/openhuman-core/src/agent/harness/session/builder/setters.rsindex 8d1537a37e..b9ccdd2ba7 100644--- a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs+++ b/crates/openhuman-core/src/agent/harness/session/builder/setters.rs@@ -203,7 +203,7 @@ impl AgentBuilder {/// tools resolve their default cwd to the profile's dedicated workspace.pub fn workspace_descriptor(mut self,- descriptor: Option<tinyagents_harness::workspace::WorkspaceDescriptor>,+ descriptor: Option<tinytools::WorkspaceDescriptor>,) -> Self {self.workspace_descriptor = descriptor;selfdiff --git a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rsindex 9d48d729d9..53c1947c5e 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs@@ -376,10 +376,7 @@ impl Agent {/// still decided by its [`SecurityPolicy`](crate::security::SecurityPolicy),/// so a caller that wants tools rooted somewhere new must build the agent/// from a config whose `action_dir` already permits it.- pub fn set_workspace_descriptor(- &mut self,- descriptor: Option<tinyagents_harness::workspace::WorkspaceDescriptor>,- ) {+ pub fn set_workspace_descriptor(&mut self, descriptor: Option<tinytools::WorkspaceDescriptor>) {self.workspace_descriptor = descriptor;}diff --git a/crates/openhuman-core/src/agent/harness/session/turn/context.rs b/crates/openhuman-core/src/agent/harness/session/turn/context.rsindex 992774045e..941005a921 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/context.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/context.rs@@ -9,7 +9,6 @@ use crate::agent::prompts::{};use crate::memory::MemoryCategory;use crate::tools::agent_policy::render_tool_policy_boundary;-use tinytools::Tool;use anyhow::Result;diff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/harness/session/turn/graph.rsindex 4a0f155987..fb73577612 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs@@ -13,7 +13,7 @@//! instead of erroring.//!//! **Available tools.** The agent's resolved harness tool set (`tools`),-//! advertised via `SharedToolAdapter`+//! advertised via the canonical shared-tool adapter//! and filtered by `visible_tool_names`. The chat turn surfaces clarifying//! questions inline rather than pausing, so it advertises **no early-exit//! tools**.@@ -86,7 +86,7 @@ pub(crate) struct ChatTurnGraph {/// workspace — acting tools then resolve their default cwd to/// `<action_dir>/profiles/<id>` via `ToolExecutionContext.workspace`. `None`/// (the common case) keeps the shared-`action_dir` cwd behaviour.- pub workspace_descriptor: Option<tinyagents_harness::workspace::WorkspaceDescriptor>,+ pub workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,/// Declared sandbox mode for the top-level agent. The chat path scopes it/// around the shared harness so acting tools see the same mode as workers.pub sandbox_mode: SandboxMode,diff --git a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rsindex 6a3865a2c6..6ec50a852f 100644--- a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs@@ -118,10 +118,9 @@ fn build_parent_context_propagates_own_descriptor_on_root_turn() {// reaches subagents spawned via spawn_subagent/spawn_async_subagent, and they// silently fall back to the shared action_dir instead of// `<action_dir>/profiles/<id>`.- let descriptor = tinyagents_harness::workspace::WorkspaceDescriptor::new(- std::path::PathBuf::from("/tmp/act/profiles/alice"),- )- .with_policy_id("openhuman.profile:alice");+ let descriptor =+ tinytools::WorkspaceDescriptor::new(std::path::PathBuf::from("/tmp/act/profiles/alice"))+ .with_policy_id("openhuman.profile:alice");let mut agent = make_agent(None);// No ambient parent context is installed in this test, so current_parent()diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rsindex f9f5f80bbc..2be7cb0eb0 100644--- a/crates/openhuman-core/src/agent/harness/session/types.rs+++ b/crates/openhuman-core/src/agent/harness/session/types.rs@@ -177,7 +177,7 @@ pub struct Agent {/// turn so acting tools (shell/file/git) resolve their default cwd to/// `<action_dir>/profiles/<id>` instead of the shared `action_dir`. `None`/// (the common case) preserves the shared-cwd behaviour unchanged.- pub(super) workspace_descriptor: Option<tinyagents_harness::workspace::WorkspaceDescriptor>,+ pub(super) workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,pub(super) workflows: Vec<crate::skills::Workflow>,/// Agent workflows discovered at session start.pub(super) auto_save: bool,@@ -548,7 +548,7 @@ pub struct AgentBuilder {pub(super) action_dir: Option<std::path::PathBuf>,/// Optional per-profile workspace descriptor forwarded to [`Agent`] at build/// time. Defaults to `None` (shared `action_dir` cwd).- pub(super) workspace_descriptor: Option<tinyagents_harness::workspace::WorkspaceDescriptor>,+ pub(super) workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,pub(super) workflows: Option<Vec<crate::skills::Workflow>>,/// Agent workflows to surface in the prompt. Populated from `load_workflows`/// at session start; defaults to empty when not explicitly set.diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rsindex 0e0c61f257..12472bd90e 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph.rs@@ -12,7 +12,7 @@//! are removed); `run_typed_mode` calls it unconditionally.//!//! **Available tools.** The sub-agent reuses the parent's harness tools plus the-//! per-spawn dynamic tools, advertised via [`SharedToolAdapter`] over the shared+//! per-spawn dynamic tools, advertised via the canonical shared-tool adapter over the shared//! `Arc<Vec<Box<dyn Tool>>>` tool sets (`[dynamic_tools, parent_tools]` — dynamic//! first so a shadowing dynamic tool executes, matching advertisement), filtered//! by `allowed_names`. `ask_user_clarification` is the early-exit tool.diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rsindex e0c76cde89..3d4a45c624 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs@@ -12,7 +12,7 @@ use crate::agent::messages::{ChatMessage, ConversationMessage};use crate::agent::progress::AgentProgress;use crate::agent::tinyagents::{run_turn_via_tinyagents_shared, SubagentScope};use crate::inference::tokenjuice::AgentTokenjuiceCompression;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;use tinytools::{Tool, ToolSpec};use super::transcript::persist_subagent_transcript;diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rsindex 19c2a1b55f..838b084c55 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs@@ -6,7 +6,7 @@use std::path::PathBuf;use std::time::Duration;use thiserror::Error;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;use crate::agent::harness::definition::AgentTier;use crate::agent::messages::ChatMessage;diff --git a/crates/openhuman-core/src/agent/message_convert.rs b/crates/openhuman-core/src/agent/message_convert.rsindex 911f113f08..42e53cfeb8 100644--- a/crates/openhuman-core/src/agent/message_convert.rs+++ b/crates/openhuman-core/src/agent/message_convert.rs@@ -24,7 +24,7 @@ use tinytools_agent::dialect::{};use crate::agent::messages::{ChatMessage, ConversationMessage, ToolResultMessage};-use crate::inference::provider::{ChatResponse, ToolCall};+use crate::inference::provider::ChatResponse;/// Convert the host provider response at its boundary into the canonical/// dialect input. The dialect crate owns all parsing after this field-wise map.diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsindex b9000fe8fe..5ffca1dd27 100644--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs@@ -28,8 +28,8 @@ use tinyagents_graph::delegation::{DelegationConfig, DelegationStage, DelegationStageOutput, DelegationState,};use tinyagents_graph::SqliteCheckpointer;-use tinyagents_harness::workspace::WorkspaceDescriptor;use tinyagents_harness::CancellationToken;+use tinytools::WorkspaceDescriptor;const LOG_TARGET: &str = "agent_orchestration::delegation";diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rsindex 76215e930b..6fb947fd7c 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/dispatch.rs@@ -5,7 +5,8 @@use std::collections::HashMap;use std::path::Path;-use tinyagents_harness::workspace::{WorkspaceDescriptor, WorkspaceIsolation};+use tinyagents_harness::workspace::WorkspaceIsolation;+use tinytools::WorkspaceDescriptor;use tokio::sync::mpsc::Sender;use crate::agent::harness::definition::{AgentDefinition, SandboxMode};@@ -49,10 +50,8 @@ async fn create_spawn_parallel_worktree(ParallelWorktreeRequest::Isolated { base_ref } => match action_root {Some(repo_root) => {let sandbox = match definition.sandbox_mode {- SandboxMode::Sandboxed => tinyagents_harness::tool::SandboxMode::Required,- SandboxMode::None | SandboxMode::ReadOnly => {- tinyagents_harness::tool::SandboxMode::Inherit- }+ SandboxMode::Sandboxed => tinytools::SandboxMode::Required,+ SandboxMode::None | SandboxMode::ReadOnly => tinytools::SandboxMode::Inherit,};let isolation = worktree::OpenHumanWorktreeIsolation::new(repo_root).with_base_ref(base_ref)diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rsindex a34f492a80..f91b54c947 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs@@ -13,8 +13,8 @@ use std::sync::Arc;use tinyagents_graph::export::GraphTopology;use tinyagents_graph::{ClosureStateReducer, CompiledGraph, GraphBuilder, NodeContext, NodeResult};use tinyagents_harness::retry::RetryPolicy;-use tinyagents_harness::workspace::WorkspaceDescriptor;use tinyagents_harness::{CancellationToken, TinyAgentsError};+use tinytools::WorkspaceDescriptor;use tokio::sync::mpsc::Sender;use crate::agent::harness::definition::AgentDefinition;diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rsindex adbcbb96ab..fe05cdc7cd 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs@@ -4,8 +4,8 @@use std::path::PathBuf;-use tinyagents_harness::workspace::WorkspaceDescriptor;use tinyagents_harness::CancellationToken;+use tinytools::WorkspaceDescriptor;use crate::agent::harness::definition::AgentDefinitionRegistry;use crate::agent::harness::fork_context::current_parent;diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rsindex 6c0f50c59c..ea938b965c 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/types.rs@@ -4,7 +4,7 @@use std::path::PathBuf;use serde::Serialize;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;use super::request::ParallelAgentTask;use crate::agent::harness::definition::AgentDefinition;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rsindex 3118bb4306..c37756a314 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs@@ -11,8 +11,8 @@ use crate::agent::progress::AgentProgress;use crate::agent::tinyagents::thread_context::current_thread_id;use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use tinyagents_harness::workspace::WorkspaceDescriptor;use tinytools::ToolResult;+use tinytools::WorkspaceDescriptor;use super::tool::AgentPrepareContextTool;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait.rsindex c0a02dbb83..2519b9238e 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/wait.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/wait.rs@@ -189,7 +189,11 @@ fn wait_schema(loop_mode: bool) -> serde_json::Value {fn timeout_policy_for_wait(args: &serde_json::Value) -> ToolTimeout {let duration_ms = duration_ms_from_args(args).unwrap_or(DEFAULT_DURATION_SECS * MILLIS_PER_SEC);let rounded_secs = duration_ms.saturating_add(MILLIS_PER_SEC - 1) / MILLIS_PER_SEC;- ToolTimeout::Secs(rounded_secs.saturating_add(1))+ ToolTimeout::Millis(+ rounded_secs+ .saturating_add(1)+ .saturating_mul(MILLIS_PER_SEC),+ )}/// Extract and clamp the caller's requested wait duration in milliseconds.diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rsindex 084503f769..5452de94ee 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs@@ -69,11 +69,11 @@ impl Tool for WaitSubagentTool {/// Without this the harness kills the tool at the global `Inherit` timeout/// (120s by default) *before* the wait can return its "still running"/// success, so a legitimate long wait is reported as a tool failure. The- /// harness adds its own small grace on top of `Secs`, so the tool always+ /// harness adds its own small grace on top of `Millis`, so the tool always/// gets to finish and report first. Same reasoning as/// `spawn_parallel_agents`, which opts out for the same class of bug.fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {- ToolTimeout::Secs(requested_timeout_secs(args))+ ToolTimeout::Millis(requested_timeout_secs(args).saturating_mul(1000))}fn parameters_schema(&self) -> serde_json::Value {diff --git a/crates/openhuman-core/src/agent/orchestration/worktree.rs b/crates/openhuman-core/src/agent/orchestration/worktree.rsindex cdda153120..67099a4c5b 100644--- a/crates/openhuman-core/src/agent/orchestration/worktree.rs+++ b/crates/openhuman-core/src/agent/orchestration/worktree.rs@@ -39,10 +39,8 @@use std::path::{Path, PathBuf};-use tinyagents_harness::tool::SandboxMode;-use tinyagents_harness::workspace::{- GitWorktreeIsolation, WorkspaceDescriptor, WorkspaceIsolation,-};+use tinyagents_harness::workspace::{GitWorktreeIsolation, WorkspaceIsolation};+use tinytools::{SandboxMode, WorkspaceDescriptor};use crate::core::bus::BUS;use crate::core::events::DomainEvent;diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.mdindex 88f264272a..f1204f9747 100644--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@ -100,7 +100,14 @@ Responses project the crate's own `AgentObservation` and `HarnessRunStatus` serd## Host adapters-`host/` implements the crate's ten host-capability traits (Phase 4 of the agents plan described in `host/mod.rs`), so that `agent/` can ask ten capabilities instead of reaching into ~45 domains directly. The adapters are implemented and tested, but **no live turn path calls them yet**. The session exposes `host_agent_memory()` and `host_experience_store()` accessors (`agent/harness/session/runtime/accessors.rs`) that construct two of the adapters, and only tests call those. Repointing the call sites is the remaining half of Phase 4. Several adapter methods carry `TODO(phase4)` where a domain surface was not yet reachable; they are documented gaps, not silent stubs.+`host/` implements the crate's ten host-capability traits and exposes one+`OpenHumanHostBundleFactory`. It constructs the complete+`HostCapabilities<()>` bundle from a single session/runtime input set, while+`OpenHumanRunContext` carries the explicit per-turn values (origin, progress,+attachments, artifacts, dispatch, cancellation, thread, workspace and stop+hooks) into canonical `tinyagents_harness::context::RunContext`. Runtime route+cutover remains separate: the existing manual assembly shell is retained until+every caller can accept the explicit context.## Notesdiff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 2dbb6695c9..72ede30229 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -498,7 +498,7 @@ pub(super) fn assemble_turn_harness(// Phase 1): an external-effect tool intercepts through the global// `ApprovalGate`, a denial short-circuits with a model-consumable result, and// an approved call records a terminal audit row. Replaces the inline approval- // block that used to live in `execute_openhuman_tool`.+ // block that used to live in the legacy tool adapter.harness.push_tool_middleware(Arc::new(middleware::ApprovalSecurityMiddleware::new(tool_sets.clone(),)));diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rsindex 3758209b25..7cc5bbd4e1 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs@@ -11,7 +11,7 @@ use tinyagents_registry::{CapabilityRegistry, ComponentKind, RegistryDiagnostic, RegistrySnapshot,};-use crate::agent::tinyagents::tools::{EarlyExitHook, SharedToolAdapter};+use crate::agent::tinyagents::tools::{CanonicalSharedToolAdapter, EarlyExitHook};use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;/// Register every admitted tool from `tool_sets` onto `harness` (and its@@ -79,7 +79,9 @@ pub(super) fn register_turn_tools_and_agents();}if !registered.contains(name) && admitted && !spawn_stripped {- if let Some(mut adapter) = SharedToolAdapter::for_name(tool_sets.to_vec(), name) {+ if let Some(mut adapter) =+ CanonicalSharedToolAdapter::for_name(tool_sets.to_vec(), name)+ {if early_exit_set.contains(name) {if let Some(hook) = early_exit_hook {adapter = adapter.with_early_exit(hook.clone());@@ -169,7 +171,7 @@ pub(super) fn register_turn_tools_and_agents(// into that stream. The harness is deliberately NOT switched over to these// projections yet — that glue swap is explicitly deferred.let projected_models = capability_registry.to_model_registry();- let projected_tools = capability_registry.to_tool_registry();+ let projected_tools = capability_registry.to_tool_registry::<()>();tracing::debug!(models = projected_models.names().len(),tools = projected_tools.names().len(),diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rsnew file mode 100644index 0000000000..7b363999a1--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs@@ -0,0 +1,136 @@+//! The one factory that assembles OpenHuman's TinyAgents host capabilities.+//!+//! Keeping this construction in one place makes the boundary auditable: every+//! concrete adapter receives values from the same host session and explicit+//! [`OpenHumanRunContext`], and the generic runtime receives only its canonical+//! [`tinyagents_harness::host::HostCapabilities`] bundle.++use std::sync::Arc;++use tinyagents_harness::host::{+ AgentMemory, BudgetGate, ContextComposer, ExperienceStore, HostCapabilities, LearningSink,+ ModelResolver, ProgressSink, SecurityGate, ToolOutcomeClassifier,+};++use crate::agent::harness::definition::AgentDefinitionRegistry;+use crate::agent::hooks::PostTurnHook;+use crate::config::Config;+use crate::memory::Memory;+use crate::security::policy::SecurityPolicy;+use crate::tools::agent_policy::ToolPolicySession;+use tinytools::Tool;++use super::{+ OpenHumanAgentMemory, OpenHumanBudgetGate, OpenHumanContextComposer,+ OpenHumanDefinitionRegistry, OpenHumanExperienceStore, OpenHumanLearningSink,+ OpenHumanModelResolver, OpenHumanProgressSink, OpenHumanRunContext, OpenHumanSecurityGate,+ OpenHumanToolOutcomeClassifier,+};++/// Runtime-owned inputs required to build every OpenHuman host capability.+///+/// This is deliberately an input value, rather than a global lookup. The+/// caller obtains it while building a session and passes it alongside the+/// matching [`OpenHumanRunContext`].+pub struct OpenHumanHostBundleInputs {+ pub config: Arc<Config>,+ pub definitions: Arc<AgentDefinitionRegistry>,+ pub security_policy: Arc<SecurityPolicy>,+ pub tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,+ pub tool_policy: Option<Arc<ToolPolicySession>>,+ pub memory: Arc<dyn Memory>,+ pub shared_experience_memory: Option<Arc<dyn Memory>>,+ pub profile_id: Option<String>,+ pub post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,+}++/// OpenHuman's ten concrete capability adapters plus their erased crate bundle.+///+/// Typed handles make it possible to verify wiring without downcasting trait+/// objects. The runtime consumes [`Self::capabilities`]; the typed fields exist+/// solely to preserve the host boundary and to support focused wiring tests.+pub struct OpenHumanHostBundle {+ pub capabilities: HostCapabilities<()>,+ pub context: Arc<OpenHumanContextComposer>,+ pub definitions: Arc<OpenHumanDefinitionRegistry>,+ pub security: Arc<OpenHumanSecurityGate>,+ pub models: Arc<OpenHumanModelResolver>,+ pub memory: Arc<OpenHumanAgentMemory>,+ pub budget: Arc<OpenHumanBudgetGate>,+ pub progress: Arc<OpenHumanProgressSink>,+ pub learning: Arc<OpenHumanLearningSink>,+ pub tool_outcomes: Arc<OpenHumanToolOutcomeClassifier>,+ pub experience: Arc<OpenHumanExperienceStore>,+}++/// Builds the full OpenHuman host bundle for an explicit turn.+pub struct OpenHumanHostBundleFactory;++impl OpenHumanHostBundleFactory {+ /// Constructs all ten concrete adapters from a single session input set.+ ///+ /// The run context supplies per-turn state, while `inputs` supplies durable+ /// session/runtime dependencies. No adapter is optional for OpenHuman. An+ /// unobserved context gets an unconsumed bounded sink, preserving the+ /// concrete progress seam without discovering state through a task-local.+ pub fn build(+ inputs: OpenHumanHostBundleInputs,+ turn: &OpenHumanRunContext,+ ) -> OpenHumanHostBundle {+ let context = Arc::new(OpenHumanContextComposer::new(Arc::clone(&inputs.config)));+ let definitions = Arc::new(+ OpenHumanDefinitionRegistry::new(inputs.definitions)+ .with_config(Arc::clone(&inputs.config)),+ );+ let mut security = OpenHumanSecurityGate::new(inputs.security_policy, inputs.tool_sets);+ if let Some(policy) = inputs.tool_policy {+ security = security.with_tool_policy(policy);+ }+ let security = Arc::new(security);+ let models = Arc::new(OpenHumanModelResolver::new(Arc::clone(&inputs.config)));+ let memory = Arc::new(OpenHumanAgentMemory::new(Arc::clone(&inputs.memory)));+ let budget = Arc::new(OpenHumanBudgetGate::new(Arc::clone(&inputs.config)));+ let progress_tx = turn+ .progress+ .clone()+ .unwrap_or_else(|| tokio::sync::mpsc::channel(1).0);+ let progress = Arc::new(OpenHumanProgressSink::new(progress_tx));+ let learning = Arc::new(OpenHumanLearningSink::new(inputs.post_turn_hooks));+ let tool_outcomes = Arc::new(OpenHumanToolOutcomeClassifier::new());+ let experience = Arc::new(+ OpenHumanExperienceStore::with_profile(inputs.memory, inputs.profile_id)+ .with_shared_recall_memory(inputs.shared_experience_memory),+ );++ let capabilities = HostCapabilities::new(+ context.clone() as Arc<dyn ContextComposer>,+ definitions.clone(),+ security.clone() as Arc<dyn SecurityGate>,+ models.clone() as Arc<dyn ModelResolver<()>>,+ )+ .with_memory(memory.clone() as Arc<dyn AgentMemory>)+ .with_budget(budget.clone() as Arc<dyn BudgetGate>)+ .with_progress(progress.clone() as Arc<dyn ProgressSink>)+ .with_learning(learning.clone() as Arc<dyn LearningSink>)+ .with_tool_outcomes(tool_outcomes.clone() as Arc<dyn ToolOutcomeClassifier>)+ .with_experience(experience.clone() as Arc<dyn ExperienceStore>);++ OpenHumanHostBundle {+ capabilities,+ context,+ definitions,+ security,+ models,+ memory,+ budget,+ progress,+ learning,+ tool_outcomes,+ experience,+ }+ }+}++#[cfg(test)]+#[path = "bundle_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rsnew file mode 100644index 0000000000..e67d495d2d--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs@@ -0,0 +1,81 @@+use super::*;++use std::sync::Arc;++use tinyagents_definition::DefinitionRegistry;+use tinyagents_harness::host::{+ AgentMemory, BudgetGate, ContextComposer, ExperienceStore, LearningSink, ModelResolver,+ ProgressSink, SecurityGate, ToolOutcomeClassifier,+};++fn inputs() -> (OpenHumanHostBundleInputs, OpenHumanRunContext) {+ let (progress, _receiver) = tokio::sync::mpsc::channel(4);+ let memory: Arc<dyn Memory> =+ Arc::new(crate::memory::tool_memory::test_helpers::MockMemory::default());+ let mut turn = OpenHumanRunContext::new();+ turn.thread_id = Some("thread-for-bundle".to_string());+ turn.progress = Some(progress);+ (+ OpenHumanHostBundleInputs {+ config: Arc::new(Config::default()),+ definitions: Arc::new(AgentDefinitionRegistry::builtins_only()),+ security_policy: Arc::new(SecurityPolicy::default()),+ tool_sets: Vec::new(),+ tool_policy: None,+ memory,+ shared_experience_memory: None,+ profile_id: Some("profile-a".to_string()),+ post_turn_hooks: Vec::new(),+ },+ turn,+ )+}++#[test]+fn factory_records_all_ten_concrete_adapters_in_one_bundle() {+ let (inputs, turn) = inputs();+ let host = OpenHumanHostBundleFactory::build(inputs, &turn);++ let context: Arc<dyn ContextComposer> = host.context.clone();+ let definitions: Arc<dyn DefinitionRegistry> = host.definitions.clone();+ let security: Arc<dyn SecurityGate> = host.security.clone();+ let models: Arc<dyn ModelResolver<()>> = host.models.clone();+ let memory: Arc<dyn AgentMemory> = host.memory.clone();+ let budget: Arc<dyn BudgetGate> = host.budget.clone();+ let progress: Arc<dyn ProgressSink> = host.progress.clone();+ let learning: Arc<dyn LearningSink> = host.learning.clone();+ let outcomes: Arc<dyn ToolOutcomeClassifier> = host.tool_outcomes.clone();+ let experience: Arc<dyn ExperienceStore> = host.experience.clone();++ assert!(Arc::ptr_eq(&context, &host.capabilities.context));+ assert!(Arc::ptr_eq(&definitions, &host.capabilities.definitions));+ assert!(Arc::ptr_eq(&security, &host.capabilities.security));+ assert!(Arc::ptr_eq(&models, &host.capabilities.models));+ assert!(Arc::ptr_eq(+ &memory,+ host.capabilities.memory.as_ref().expect("memory")+ ));+ assert!(Arc::ptr_eq(+ &budget,+ host.capabilities.budget.as_ref().expect("budget")+ ));+ assert!(Arc::ptr_eq(+ &progress,+ host.capabilities.progress.as_ref().expect("progress")+ ));+ assert!(Arc::ptr_eq(+ &learning,+ host.capabilities.learning.as_ref().expect("learning")+ ));+ assert!(Arc::ptr_eq(+ &outcomes,+ host.capabilities+ .tool_outcomes+ .as_ref()+ .expect("tool outcomes"),+ ));+ assert!(Arc::ptr_eq(+ &experience,+ host.capabilities.experience.as_ref().expect("experience"),+ ));+}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rsindex 9eca6bdbe8..88b7ac2b08 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/definition_registry.rs@@ -76,8 +76,8 @@ use std::collections::HashSet;use std::sync::Arc;use async_trait::async_trait;+use tinyagents_definition::Result;use tinyagents_definition::{AgentDefinition, DefinitionRegistry};-use tinyagents_harness::error::Result;use crate::agent::harness::definition::{AgentDefinition as HostAgentDefinition, AgentDefinitionRegistry, AgentTier, ModelSpec,diff --git a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs b/crates/openhuman-core/src/agent/tinyagents/host/mod.rsindex b9a7fc4b29..1adfcb18ec 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/mod.rs@@ -23,18 +23,13 @@//! filter to make a signature fit would silently disable a guarantee the rest//! of the system assumes, and no crate-side test could catch it.//!-//! # Status-//!-//! Adapters exist and are tested; **`agent/` does not call them yet.**-//! Repointing the call sites is the remaining half of Phase 4 and is gated on-//! work tracked in the plan (the session still holds `AgentConfig` until-//! Phase 2's reader flip; `builder/factory.rs` is split rather than repointed).-//! Several methods carry `TODO(phase4)` where a domain surface was not-//! reachable — those are honest gaps, not stubs pretending to work, and each-//! names what is missing.+//! [`OpenHumanRunContext`] is the host-owned, explicit per-turn state. It is+//! the sole input to the host bundle factory for per-turn handles; no adapter+//! discovers its state through a task-local.pub mod agent_memory;pub mod budget_gate;+mod bundle;pub mod context_composer;pub mod definition_registry;pub mod delegation;@@ -42,17 +37,20 @@ pub mod experience_store;pub mod learning_sink;pub mod model_resolver;pub mod progress_sink;+pub mod run_context;pub mod security_gate;pub(crate) mod steering;pub mod tool_outcome_classifier;pub use agent_memory::OpenHumanAgentMemory;pub use budget_gate::OpenHumanBudgetGate;+pub use bundle::{OpenHumanHostBundle, OpenHumanHostBundleFactory, OpenHumanHostBundleInputs};pub use context_composer::OpenHumanContextComposer;pub use definition_registry::OpenHumanDefinitionRegistry;pub use experience_store::OpenHumanExperienceStore;pub use learning_sink::OpenHumanLearningSink;pub use model_resolver::OpenHumanModelResolver;pub use progress_sink::OpenHumanProgressSink;+pub use run_context::OpenHumanRunContext;pub use security_gate::OpenHumanSecurityGate;pub use tool_outcome_classifier::OpenHumanToolOutcomeClassifier;diff --git a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs b/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rsindex ba7ef78355..3eb5e56041 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs@@ -19,8 +19,8 @@//!//! 1. **`State` erasure.** The trait is generic over the harness state//! (`ModelResolver<State>` must return `Arc<dyn ChatModel<State>>`), but-//! every model OpenHuman builds is a `ChatModel<()>` — the core's harness-//! carries its per-turn context in task-locals and `RunContext`, not in a+//! every model OpenHuman builds is a `ChatModel<()>` — the core carries+//! per-turn values explicitly in `OpenHumanRunContext` and `RunContext`, not in a//! typed state value. [`StatelessModel`] bridges the two: it implements//! `ChatModel<State>` for *any* `State` by discarding the state reference and//! invoking the inner model with `&()`. That is lossless today precisely@@ -205,7 +205,7 @@ fn workload_role_for(req: &ModelResolveRequest) -> &'static str {////// Not a general-purpose adapter: it is sound only because OpenHuman's models/// genuinely ignore the harness state (they carry per-turn context in-/// task-locals and `RunContext`). Both `invoke` and `stream` are forwarded so a+/// `OpenHumanRunContext` and `RunContext`). Both `invoke` and `stream` are forwarded so a/// streaming provider keeps streaming — falling through to the trait's default/// `stream` would silently downgrade every resolved model to replayed unary.struct StatelessModel {diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsnew file mode 100644index 0000000000..6bb61ef26e--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -0,0 +1,181 @@+//! OpenHuman's explicit, host-owned state for one agent run.+//!+//! `tinyagents_harness::context::RunContext` owns generic runtime mechanics.+//! This type owns the product values that used to be recovered from ambient+//! task-locals: approval origin, host progress, attachment and artifact scope,+//! parent dispatch state, and the handles a tool needs to continue a run. A+//! caller passes it through every turn and child invocation, then converts it+//! into the canonical TinyAgents context with [`Self::into_tinyagents`].++use std::sync::{Arc, Mutex};+use std::time::Duration;++use tokio::sync::mpsc::Sender;++use crate::agent::harness::definition::SandboxMode;+use crate::agent::harness::fork_context::{AgentContextPreparedSource, ParentExecutionContext};+use crate::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore;+use crate::agent::harness::turn_dispatch_guard::TurnDispatchState;+use crate::agent::harness::turn_subagent_usage::SubagentUsageEntry;+use crate::agent::progress::AgentProgress;+use crate::agent::stop_hooks::StopHook;+use crate::agent::tinyagents::resolved_route::RouteSlot;+use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;+use crate::agent::turn_origin::AgentTurnOrigin;++/// Explicit OpenHuman data carried by a single top-level or child agent run.+///+/// Shared members (`Arc`s, cancellation and workspace descriptor) retain the+/// identity required by a recursive run tree. [`Self::child`] deliberately+/// allocates a fresh route slot and subagent ledger: a child must not overwrite+/// the provider route or cost roll-up subsequently read by its parent.+#[derive(Clone)]+pub struct OpenHumanRunContext {+ /// Trust/routing source used by OpenHuman approval and attribution policy.+ pub origin: Option<AgentTurnOrigin>,+ /// UI/event progress receiver for this turn tree.+ pub progress: Option<Sender<AgentProgress>>,+ /// Stop policies evaluated after each model call.+ pub stop_hooks: Vec<Arc<dyn StopHook>>,+ /// Parent runtime snapshot used by canonical recursive tool dispatch.+ pub parent: Option<ParentExecutionContext>,+ /// Context-preparation sources already consumed in this turn.+ pub prepared_context_sources: Arc<Vec<AgentContextPreparedSource>>,+ /// File-state identity used to detect stale parent reads after child writes.+ pub file_state_agent_id: Option<String>,+ /// Host-owned artifact index for tool-result references.+ pub(crate) tool_result_artifact_index: Option<Arc<ToolResultArtifactIndexStore>>,+ /// Current-turn attachment placeholders forwarded to vision delegates.+ pub attachment_placeholders: Arc<Vec<String>>,+ /// Dispatch guard shared by synchronous delegates in this run.+ pub dispatch: Option<Arc<TurnDispatchState>>,+ /// Optional task recency restriction for integration tools.+ pub task_recency_window: Option<Duration>,+ /// Sandbox mode of the agent definition executing this turn.+ pub sandbox_mode: Option<SandboxMode>,+ /// Zero-based OpenHuman subagent depth (the root is zero).+ pub spawn_depth: usize,+ /// This run's subagent usage roll-up; intentionally isolated for children.+ pub subagent_usage: Arc<Mutex<Vec<SubagentUsageEntry>>>,+ /// Provider/model observation for this run; intentionally isolated for children.+ pub resolved_route: RouteSlot,+ /// Cooperative cancellation shared by the complete recursive run tree.+ pub cancellation: tinyagents_harness::cancel::CancellationToken,+ /// Thread attached to provider requests and host persistence.+ pub thread_id: Option<String>,+ /// Direct canonical workspace descriptor; never use the old harness re-export.+ pub workspace: Option<tinytools::WorkspaceDescriptor>,+ /// Per-turn tool result capture shared with the event bridge.+ pub(crate) tool_outcomes: Option<ToolOutcomeSink>,+}++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 {+ origin: None,+ progress: None,+ stop_hooks: Vec::new(),+ parent: None,+ prepared_context_sources: Arc::new(Vec::new()),+ file_state_agent_id: None,+ tool_result_artifact_index: None,+ attachment_placeholders: Arc::new(Vec::new()),+ dispatch: None,+ task_recency_window: None,+ sandbox_mode: None,+ spawn_depth: 0,+ subagent_usage: Arc::new(Mutex::new(Vec::new())),+ resolved_route: Arc::new(Mutex::new(None)),+ cancellation: tinyagents_harness::cancel::CancellationToken::new(),+ thread_id: None,+ workspace: None,+ tool_outcomes: None,+ }+ }++ /// Sets the direct TinyTools workspace descriptor for this run.+ pub fn with_workspace(mut self, workspace: tinytools::WorkspaceDescriptor) -> Self {+ self.workspace = Some(workspace);+ 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 the explicit child state for a recursive invocation.+ ///+ /// Cancellation, workspace, progress, policy hooks and dispatch state are+ /// inherited. Route observation and usage accounting are isolated, so a+ /// completed child cannot mutate facts subsequently persisted for its+ /// parent.+ 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.subagent_usage = Arc::new(Mutex::new(Vec::new()));+ child.resolved_route = Arc::new(Mutex::new(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(+ self,+ mut config: tinyagents_harness::context::RunConfig,+ ) -> tinyagents_harness::context::RunContext<Self> {+ 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 context = tinyagents_harness::context::RunContext::new(config, self)+ .with_cancellation(cancellation);+ match workspace {+ Some(workspace) => context.with_workspace(workspace),+ None => context,+ }+ }++ /// Returns this context's file-state identity for explicit tool plumbing.+ pub fn file_state_scope(&self) -> Option<&str> {+ self.file_state_agent_id.as_deref()+ }++ /// 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);+ }++ /// 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()+ }+}++#[cfg(test)]+#[path = "run_context_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsnew file mode 100644index 0000000000..3839afefe9--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -0,0 +1,49 @@+use super::*;++#[test]+fn converts_explicit_values_to_the_canonical_tinyagents_context() {+ let cancellation = tinyagents_harness::cancel::CancellationToken::new();+ let workspace = tinytools::WorkspaceDescriptor::new("/work/action");+ let mut host = OpenHumanRunContext::new()+ .with_cancellation(cancellation.clone())+ .with_workspace(workspace.clone());+ host.thread_id = Some("thread-a".to_string());++ let run = host.into_tinyagents(tinyagents_harness::context::RunConfig::new("run-a"));++ assert_eq!(run.thread_id().map(|id| id.as_str()), Some("thread-a"));+ assert_eq!(run.workspace, Some(workspace));+ cancellation.cancel();+ assert!(run.cancellation.is_cancelled());+}++#[test]+fn child_inherits_tree_handles_but_isolates_observations_and_usage() {+ let mut parent = OpenHumanRunContext::new();+ parent.thread_id = Some("thread-a".to_string());+ parent.file_state_agent_id = Some("parent-file-state".to_string());+ *parent.resolved_route.lock().expect("route lock") =+ Some(crate::agent::tinyagents::ResolvedProviderRoute {+ provider: "provider-a".to_string(),+ model: "model-a".to_string(),+ });++ let child = parent.child();++ assert_eq!(child.spawn_depth, 1);+ assert_eq!(child.thread_id.as_deref(), Some("thread-a"));+ assert!(child.file_state_agent_id().is_none());+ assert!(child+ .resolved_route+ .lock()+ .expect("child route lock")+ .is_none());+ assert!(child+ .subagent_usage+ .lock()+ .expect("child usage lock")+ .is_empty());++ parent.cancellation.cancel();+ assert!(child.cancellation.is_cancelled());+}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier.rs b/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier.rsindex 59436ec9cb..fa4c7485a6 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/tool_outcome_classifier.rs@@ -74,7 +74,7 @@ use std::collections::HashSet;use std::sync::Arc;use tinyagents_harness::host::{OutcomeClass, ToolOutcomeClassifier};-use tinyagents_harness::tool::ToolResult;+use tinytools::ToolResult;use crate::tools::status::{classify, ToolFailureClass};@@ -185,32 +185,24 @@ impl OpenHumanToolOutcomeClassifier {}}- /// Joins `error` and `content` into the text the heuristic reads.+ /// Renders canonical content into the text the heuristic reads.////// Mirrors `TinyAgentsToolStatusMiddleware::after_tool` exactly (#4459): the/// classifier historically read `error` while the marker/timeout sniffs read/// `content`, and the two disagreeing is the bug that combination fixed./// Borrows wherever possible so the common single-source case allocates/// nothing on the hot path.- fn failure_text<'a>(result: &'a ToolResult) -> Cow<'a, str> {- let error = result.error.as_deref().unwrap_or("");- if error.is_empty() {- Cow::Borrowed(result.content.as_str())- } else if result.content.is_empty() || result.content == error {- Cow::Borrowed(error)- } else {- Cow::Owned(format!("{error}\n{}", result.content))- }+ fn failure_text(result: &ToolResult) -> Cow<'static, str> {+ Cow::Owned(result.output())}}impl ToolOutcomeClassifier for OpenHumanToolOutcomeClassifier {fn classify(&self, name: &str, result: &ToolResult) -> OutcomeClass {- // `error.is_none()` is the sole success signal, matching the middleware.- // A tool that writes "Error: …" into `content` while leaving `error`- // unset has reported success; second-guessing that here would make the- // two paths disagree about whether the call failed at all.- if result.error.is_none() {+ // `is_error` is the canonical reported-failure signal. Content is never+ // parsed as an error signal: a successful tool may legitimately render+ // text containing the word "error".+ if !result.is_error {return OutcomeClass::Success;}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rsindex 5100b3e263..f8b631109f 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs@@ -67,6 +67,27 @@ pub(crate) use turn_context::{TurnContextMiddleware,};+/// Render the canonical TinyTools content blocks at the OpenHuman boundary.+/// Middleware that used the retired string-shaped harness result must not+/// invent a second result type merely to edit text.+pub(crate) fn tool_result_text(result: &tinytools::ToolResult) -> String {+ result.output()+}++/// Replaces the model-visible canonical content while retaining its reported+/// success/failure flag. Markdown is cleared because it no longer describes+/// the transformed blocks.+pub(crate) fn replace_tool_result_text(result: &mut tinytools::ToolResult, text: String) {+ result.content = vec![tinytools::ToolContent::Text { text }];+ result.markdown_formatted = None;+}++/// Appends a host note as a distinct canonical text block.+pub(crate) fn append_tool_result_text(result: &mut tinytools::ToolResult, text: String) {+ result.content.push(tinytools::ToolContent::Text { text });+ result.markdown_formatted = None;+}+#[cfg(test)]#[path = "middleware_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rsindex 9da4852d4c..b93818850c 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs@@ -8,8 +8,8 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{MiddlewareToolOutcome, ToolHandler, ToolMiddleware};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;use crate::security::approval::{redact_args, summarize_action, ApprovalGate, ExecutionOutcome, GateOutcome,@@ -24,7 +24,7 @@ use tinytools::Tool;/// once the tool resolves.////// This replaces the inline approval block that used to live in-/// `execute_openhuman_tool`, giving approval a stable middleware name and+/// canonical tool dispatch, giving approval a stable middleware name and/// letting it short-circuit cleanly. Tool-*internal* security (path/command/// policy via `live_policy`) stays inside each tool — it needs tool-specific/// operation semantics the harness boundary can't reconstruct generically.@@ -119,14 +119,7 @@ impl ToolMiddleware<()> for ApprovalSecurityMiddleware {reason = %reason,"[tinyagents::mw] approval gate denied tool call");- return Ok(MiddlewareToolOutcome::Result(TaToolResult {- call_id: call.id,- name: call.name,- content: reason.clone(),- raw: None,- error: Some(reason),- elapsed_ms: 0,- }));+ return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(reason)));}GateOutcome::Allow => audit_id = request_id,}@@ -145,12 +138,13 @@ impl ToolMiddleware<()> for ApprovalSecurityMiddleware {if let Some(id) = audit_id {if let Some(gate) = ApprovalGate::try_global() {if let MiddlewareToolOutcome::Result(res) = &outcome {- let exec = if res.error.is_some() {+ let exec = if res.is_error {ExecutionOutcome::Failure} else {ExecutionOutcome::Success};- gate.record_execution(&id, exec, res.error.as_deref());+ let error = res.is_error.then(|| res.output());+ gate.record_execution(&id, exec, error.as_deref());}}}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/arg_recovery.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/arg_recovery.rsindex d458c917f5..d6eda6d9e6 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/arg_recovery.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/arg_recovery.rs@@ -110,7 +110,7 @@ impl Middleware<()> for ArgRecoveryMiddleware {/// tool sets.////// Built via the same [`spec_to_schema`](crate::agent::tinyagents::convert::spec_to_schema)-/// conversion the runner uses for [`SharedToolAdapter::schema`], so the+/// conversion the runner uses for canonical tool schemas, so the/// `parameters` we validate against are byte-identical to the ones the crate's/// fatal `validate_call` gate checks — otherwise our pre-validation could/// disagree with the crate and either miss a fatal case or stub a call the cratediff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/cli_rpc_only.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/cli_rpc_only.rsindex 4b44f1d9f3..95055832df 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/cli_rpc_only.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/cli_rpc_only.rs@@ -8,8 +8,8 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{MiddlewareToolOutcome, ToolHandler, ToolMiddleware};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;use tinytools::Tool;@@ -61,14 +61,7 @@ impl ToolMiddleware<()> for CliRpcOnlyMiddleware {"Tool '{}' is only available via explicit CLI/RPC invocation, not in the autonomous agent loop.",call.name);- return Ok(MiddlewareToolOutcome::Result(TaToolResult {- call_id: call.id,- name: call.name,- content: content.clone(),- raw: None,- error: Some(content),- elapsed_ms: 0,- }));+ return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(content)));}next.run(ctx, state, call).await}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/credential_scrub.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/credential_scrub.rsindex c7efadd99a..b041e35f64 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/credential_scrub.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/credential_scrub.rs@@ -8,25 +8,6 @@ use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{MiddlewareToolOutcome, ToolHandler, ToolMiddleware};use tinyinference_llm::tool::ToolCall as TaToolCall;-/// Recursively scrub credential-shaped string leaves inside a JSON value.-fn scrub_json_credentials(value: serde_json::Value) -> serde_json::Value {- use serde_json::Value;- match value {- Value::String(s) => {- Value::String(crate::agent::harness::credentials::scrub_credentials(&s))- }- Value::Array(items) => {- Value::Array(items.into_iter().map(scrub_json_credentials).collect())- }- Value::Object(map) => Value::Object(- map.into_iter()- .map(|(k, v)| (k, scrub_json_credentials(v)))- .collect(),- ),- other => other,- }-}-/// `wrap_tool`: scrub credential-shaped secrets out of every tool result before/// it leaves the tool boundary (issue #4453). The legacy engine ran/// `scrub_credentials` over **every** tool output before it entered model@@ -40,7 +21,7 @@ fn scrub_json_credentials(value: serde_json::Value) -> serde_json::Value {/// RAW tool result first and scrubs it before any outer wrap, the `after_tool`/// chain (summarization/caps in [`ToolOutputMiddleware`]), the transcript push,/// or the [`ToolOutcomeCaptureMiddleware`] sink can see the unredacted content.-/// Scrubbing here — rather than inside `execute_openhuman_tool` — covers the+/// Scrubbing here — rather than inside tool dispatch — covers the/// parent chat path, sub-agent paths, the persisted transcript, and/// `ToolCallOutcome` records by construction, since every path runs the same/// `assemble_turn_harness` seam.@@ -75,32 +56,17 @@ impl ToolMiddleware<()> for CredentialScrubMiddleware {other => return Ok(other),};- let scrubbed_content =- crate::agent::harness::credentials::scrub_credentials(&result.content);- if scrubbed_content != result.content {+ let content = crate::agent::tinyagents::middleware::tool_result_text(&result);+ let scrubbed_content = crate::agent::harness::credentials::scrub_credentials(&content);+ if scrubbed_content != content {tracing::warn!(tool = %tool_name,"[tinyagents::mw] credential_scrub redacted secret(s) from tool result content");- result.content = scrubbed_content;- }-- if let Some(err) = result.error.as_ref() {- let scrubbed_err = crate::agent::harness::credentials::scrub_credentials(err);- if &scrubbed_err != err {- tracing::warn!(- tool = %tool_name,- "[tinyagents::mw] credential_scrub redacted secret(s) from tool result error"- );- result.error = Some(scrubbed_err);- }- }-- // Raw JSON payloads (rarely populated on this path) can carry the same- // secrets — walk their string leaves so a scrubbed `content` isn't- // undermined by an unredacted `raw` mirror.- if let Some(raw) = result.raw.take() {- result.raw = Some(scrub_json_credentials(raw));+ crate::agent::tinyagents::middleware::replace_tool_result_text(+ &mut result,+ scrubbed_content,+ );}Ok(MiddlewareToolOutcome::Result(result))diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rsindex d407fea9a4..10762cdc37 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/embedder_hooks.rs@@ -6,8 +6,8 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;/// Delivers tool lifecycle events to hooks installed by an embedding host.pub(crate) struct EmbedderToolHooksMiddleware {@@ -103,7 +103,7 @@ impl Middleware<()> for EmbedderToolHooksMiddleware {self.arguments_by_call_id.lock().expect("embedder tool-hook arguments poisoned")- .insert(call.id.clone(), call.arguments.clone());+ .insert(call.name.clone(), call.arguments.clone());Ok(())}@@ -111,23 +111,30 @@ impl Middleware<()> for EmbedderToolHooksMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {let arguments = self.arguments_by_call_id.lock().expect("embedder tool-hook arguments poisoned")- .remove(&result.call_id)+ .remove(tool_name).unwrap_or(serde_json::Value::Null);let context = crate::agent::hooks::ToolHookContext {event: crate::agent::hooks::ToolHookEvent::PostToolUse,- call_id: result.call_id.clone(),- tool_name: result.name.clone(),+ // The canonical post-tool hook supplies the canonical tool name;+ // call ids are intentionally not duplicated in ToolResult.+ call_id: tool_name.to_string(),+ tool_name: tool_name.to_string(),arguments,- success: Some(result.error.is_none()),- duration_ms: Some(result.elapsed_ms),- output: Some(result.content.clone()),- error: result.error.clone(),+ success: Some(!result.is_error),+ duration_ms: None,+ output: Some(crate::agent::tinyagents::middleware::tool_result_text(+ result,+ )),+ error: result+ .is_error+ .then(|| crate::agent::tinyagents::middleware::tool_result_text(result)),session_id: None,agent_id: None,};@@ -144,8 +151,10 @@ impl Middleware<()> for EmbedderToolHooksMiddleware {chars = additional.chars().count(),"[tinyagents::mw] tool hook appended context to the result");- result.content.push_str("\n\n");- result.content.push_str(additional.trim_end());+ crate::agent::tinyagents::middleware::append_tool_result_text(+ result,+ format!("\n\n{}", additional.trim_end()),+ );}}}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rsindex 9b3f3c9300..102c2d409c 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs@@ -6,8 +6,8 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{AgentRun, Middleware};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;/// Agents are told to follow a **read-index → dedupe → write → update-index**/// cycle around durable memory, but the contract was never enforced, so it was@@ -70,7 +70,7 @@ impl Middleware<()> for MemoryProtocolMiddleware {crate::agent::harness::memory_protocol::classify_memory_op(&call.name, &call.arguments);if op != crate::agent::harness::memory_protocol::MemoryOp::Other {if let Ok(mut ops) = self.pending_ops.lock() {- ops.insert(call.id.clone(), op);+ ops.insert(call.name.clone(), op);}}Ok(())@@ -80,6 +80,7 @@ impl Middleware<()> for MemoryProtocolMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {// Consume the op captured for this call (removing it so the map can't@@ -88,13 +89,13 @@ impl Middleware<()> for MemoryProtocolMiddleware {.pending_ops.lock().ok()- .and_then(|mut ops| ops.remove(&result.call_id));+ .and_then(|mut ops| ops.remove(tool_name));let Some(op) = op else {return Ok(());};// Only successful memory ops advance the protocol — a failed write did// not mutate memory and must not demand an index update.- if result.error.is_some() {+ if result.is_error {return Ok(());}let observation = {@@ -104,17 +105,17 @@ impl Middleware<()> for MemoryProtocolMiddleware {};tracker.observe(op)};- if let Some(note) = observation.guidance(&result.name) {+ if let Some(note) = observation.guidance(tool_name) {tracing::debug!(- tool = result.name.as_str(),+ tool = tool_name,missing_index_read = observation.missing_index_read,index_drift = observation.index_drift,"[tinyagents::mw] memory-protocol guidance appended to tool result");- if !result.content.is_empty() {- result.content.push_str("\n\n");- }- result.content.push_str(¬e);+ crate::agent::tinyagents::middleware::append_tool_result_text(+ result,+ format!("\n\n{note}"),+ );}Ok(())}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rsindex 5e1e232fd5..83b80bbe12 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_progress.rs@@ -15,9 +15,9 @@ use tinyagents_harness::no_progress::{fingerprint_arguments, SuccessfulRepeat, SuccessfulRepeatTracker,};use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::message::{ContentBlock, Message};use tinyinference_llm::model::{ModelRequest, ModelResponse};+use tinytools::ToolResult as TaToolResult;use super::loop_guards::is_repeat_call_exempt;use crate::agent::context::CLEARED_PLACEHOLDER;@@ -218,14 +218,15 @@ impl Middleware<()> for RepeatProgressMiddleware {assistant_visible_text(&response.message).trim(),call_sig);- // Per-call signatures for the recurrence ledger, keyed by `call_id` so- // each result can be matched to the arguments that produced it.+ // Per-tool signatures for the recurrence ledger. The canonical+ // post-tool hook supplies the resolved tool name rather than copying+ // transport call ids into `ToolResult`.let call_sigs = tool_calls.iter().filter(|call| !is_repeat_call_exempt(&call.name)).map(|call| {(- call.id.clone(),+ call.name.clone(),format!("{}\u{1}{}",call.name,@@ -258,6 +259,7 @@ impl Middleware<()> for RepeatProgressMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {// Fold this result into the pending batch; the call guard only acts once@@ -271,12 +273,15 @@ impl Middleware<()> for RepeatProgressMiddleware {};let already_halted = batch.halted;let mut recurrence = SuccessfulRepeat::Continue;- if result.error.is_some() {+ if result.is_error {batch.all_ok = false;- } else if let Some(sig) = batch.call_sigs.get(&result.call_id) {- recurrence = self.state.tracker.record_call_outcome(sig, &result.content);+ } else if let Some(sig) = batch.call_sigs.get(tool_name) {+ recurrence = self.state.tracker.record_call_outcome(+ sig,+ &crate::agent::tinyagents::middleware::tool_result_text(result),+ );if let Ok(mut recorded) = self.state.recorded.lock() {- recorded.insert(result.call_id.clone());+ recorded.insert(tool_name.to_string());}}if matches!(recurrence, SuccessfulRepeat::Halt(_)) {@@ -316,7 +321,7 @@ impl Middleware<()> for RepeatProgressMiddleware {_ => return Ok(()),};tracing::warn!(- tool = %result.name,+ tool = tool_name,"[tinyagents::mw] crate successful-repeat tracker halted the run");self.halt(summary);diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rsindex 033176b791..f2f763fa25 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs@@ -11,9 +11,9 @@ use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::Middleware;use tinyagents_harness::no_progress::{NoProgress, NoProgressTracker, ToolAttempt};use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::message::Message as TaMessage;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;use super::loop_guards::{is_recoverable_tool_failure, is_repeat_call_exempt, recoverable_identical_halt_summary,@@ -235,7 +235,7 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// The tool result carries no arguments, so capture a fingerprint here and// correlate it by call_id in `after_tool`.if let Ok(mut sigs) = self.arg_sigs.lock() {- sigs.insert(call.id.clone(), args_fingerprint(&call.arguments));+ sigs.insert(call.name.clone(), args_fingerprint(&call.arguments));}Ok(())}@@ -244,13 +244,15 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {+ let content = crate::agent::tinyagents::middleware::tool_result_text(result);let arg_fp = self.arg_sigs.lock().ok()- .and_then(|mut sigs| sigs.remove(&result.call_id))+ .and_then(|mut sigs| sigs.remove(tool_name)).unwrap_or_default();let step = self.step.fetch_add(1, Ordering::SeqCst) + 1;@@ -259,16 +261,15 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// `"ok": false` — see `is_body_level_failure`. Only meaningful when// `result.error` is `None`; when both are set, `result.error` already// drives every check below, so this never double-counts one failure.- let body_level_failure =- result.error.is_none() && is_body_level_failure(&result.name, &result.content);+ let body_level_failure = !result.is_error && is_body_level_failure(tool_name, &content);// Combined failure text for classification: the model-facing content plus// the (redundant but authoritative) error field. Both are scanned for the// policy / terminal-inference / recoverable markers below.- let failure_text = match result.error.as_deref() {- Some(err) => format!("{}\n{}", result.content, err),- None if body_level_failure => result.content.clone(),- None => String::new(),+ let failure_text = match result.is_error {+ true => content.clone(),+ false if body_level_failure => content.clone(),+ false => String::new(),};// ── Part 5 (#3104): terminal delegated-inference fast-halt ──────────────@@ -279,17 +280,17 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// *before* the count-based thresholds, because the orchestrator otherwise// re-emits the doomed step under varied delegation-tool names so the// identical-retry threshold never trips in time.- if result.error.is_some() {+ if result.is_error {if let Some(kind) = terminal_inference_failure_kind(&failure_text) {tracing::warn!(- tool = %result.name,+ tool = tool_name,kind = ?kind,"[tinyagents::mw] terminal delegated-inference failure — halting on first occurrence with root cause");if let Ok(mut slot) = self.halt_summary.lock() {*slot = Some(terminal_inference_halt_summary(kind,- &result.name,+ tool_name,&failure_text,));}@@ -311,15 +312,14 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {s.contains(crate::security::POLICY_BLOCKED_MARKER)|| s.contains(crate::security::POLICY_DENIED_MARKER)};- let hard_reject =- policy_marked(&result.content) || result.error.as_deref().is_some_and(policy_marked);+ let hard_reject = policy_marked(&content);// ── Part 4: recoverable-failure headroom ────────────────────────────────// Transient failures (timeouts, connection resets, rate limits, 5xx) get// the legacy extended headroom instead of the crate's deterministic 3/6.// Route them to the recoverable ladder; a success or a non-recoverable// failure resets that streak and feeds the crate tracker as before.- let recoverable = result.error.is_some()+ let recoverable = result.is_error&& !hard_reject&& (is_recoverable_tool_failure(&failure_text)|| matches!(@@ -338,12 +338,12 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// done. `RepeatProgressMiddleware` already honours this exemption on// the success side; the failure ladder must agree, or the exemption// only holds while the wait happens to return early.- if is_repeat_call_exempt(&result.name) {+ if is_repeat_call_exempt(tool_name) {return Ok(());}- if let Some(summary) = self.record_recoverable(&result.name, &arg_fp, &failure_text) {+ if let Some(summary) = self.record_recoverable(tool_name, &arg_fp, &failure_text) {tracing::warn!(- tool = %result.name,+ tool = tool_name,"[tinyagents::mw] recoverable-failure headroom exhausted — halting run so the root cause surfaces");if let Ok(mut slot) = self.halt_summary.lock() {@@ -366,13 +366,13 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// success/failure signal — `None` means "progress was made, reset every// counter") sees the repeat as a failure and feeds it into the same// nudge/halt ladder as a real tool error.- let attempt_error: Option<&str> = match result.error.as_deref() {- Some(err) => Some(err),- None if body_level_failure => Some(failure_text.as_str()),- None => None,+ let attempt_error: Option<&str> = match result.is_error {+ true => Some(failure_text.as_str()),+ false if body_level_failure => Some(failure_text.as_str()),+ false => None,};let attempt = ToolAttempt {- tool: &result.name,+ tool: tool_name,arg_fingerprint: &arg_fp,error: attempt_error,hard_reject,@@ -385,7 +385,7 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {NoProgress::Continue => {}NoProgress::Nudge(instruction) => {tracing::warn!(- tool = %result.name,+ tool = tool_name,step,hard_reject,"[tinyagents::mw] no-progress nudge — steering the model to change strategy before the retry cap"@@ -408,14 +408,11 @@ impl Middleware<()> for RepeatedToolFailureMiddleware {// #4092: if the blocker is user-actionable (a missing connection),// escalate with a concrete ask instead of the crate's generic// "unreachable environment, report back" summary.- let escalation = user_actionable_escalation(- &result.name,- result.error.as_deref().unwrap_or(result.content.as_str()),- );+ let escalation = user_actionable_escalation(tool_name, &content);let user_actionable = escalation.is_some();let summary = escalation.unwrap_or(summary);tracing::warn!(- tool = %result.name,+ tool = tool_name,step,hard_reject,user_actionable,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rsindex 7a5dfaf121..9bfd0d9b53 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_outcome_capture.rs@@ -7,7 +7,7 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::tool::ToolResult as TaToolResult;+use tinytools::ToolResult as TaToolResult;/// `after_tool`: capture each tool call's execution outcome (success + content)/// into a shared sink before the harness folds the result into a `Message::tool`@@ -47,6 +47,7 @@ impl Middleware<()> for ToolOutcomeCaptureMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {// Enrich a raw security-policy / autonomy block (issue #4094): the ~20@@ -59,17 +60,17 @@ impl Middleware<()> for ToolOutcomeCaptureMiddleware {// carry a `Workaround:` suffix) are left untouched. This runs before// classification below, which still recognises the preserved marker.if let Some(enriched) = crate::agent::tinyagents::policy_denial::maybe_enrich_policy_block(- &result.name,- &result.content,+ tool_name,+ &crate::agent::tinyagents::middleware::tool_result_text(result),) {tracing::debug!(- tool = result.name.as_str(),+ tool = tool_name,"[tinyagents::mw] enriched raw security-policy block with workaround + relay");- result.content = enriched;+ crate::agent::tinyagents::middleware::replace_tool_result_text(result, enriched);}- let success = result.error.is_none();+ let success = !result.is_error;// Classify the failure so the live `ToolCallCompleted` event and the// persisted timeline can explain it in plain language. The classifier// owns all marker precedence now (policy-blocked / policy-denied / TTL@@ -83,14 +84,7 @@ impl Middleware<()> for ToolOutcomeCaptureMiddleware {let failure = if success {None} else {- let error = result.error.as_deref().unwrap_or("");- let combined: std::borrow::Cow<'_, str> = if error.is_empty() {- std::borrow::Cow::Borrowed(result.content.as_str())- } else if result.content.is_empty() || result.content == error {- std::borrow::Cow::Borrowed(error)- } else {- std::borrow::Cow::Owned(format!("{error}\n{}", result.content))- };+ let combined = crate::agent::tinyagents::middleware::tool_result_text(result);let timed_out = combined.contains("timed out");Some(crate::tools::status::classify(&combined, timed_out))};@@ -99,21 +93,23 @@ impl Middleware<()> for ToolOutcomeCaptureMiddleware {// for old/deserialized completion events; TinyAgents 1.6 supplies// these fields directly on live `ToolCompleted` events.map.insert(- result.call_id.clone(),+ tool_name.to_string(),(success,failure,- result.elapsed_ms,- result.content.chars().count(),+ 0,+ crate::agent::tinyagents::middleware::tool_result_text(result)+ .chars()+ .count(),),);}if let Ok(mut sink) = self.sink.lock() {sink.push(crate::agent::tinyagents::ToolCallOutcome {- call_id: result.call_id.clone(),- name: result.name.clone(),+ call_id: tool_name.to_string(),+ name: tool_name.to_string(),success,- content: result.content.clone(),+ content: crate::agent::tinyagents::middleware::tool_result_text(result),});}Ok(())diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rsindex fd5ae37fd4..34f8147662 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs@@ -11,8 +11,8 @@ use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::events::AgentEvent;use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use crate::agent::harness::tool_result_artifacts::{apply_per_result_persistence, artifact_read_target, page_artifact_read, ArtifactRead,@@ -145,7 +145,7 @@ impl Middleware<()> for ToolOutputMiddleware {"[tinyagents::mw] call reads a persisted tool-result artifact");if let Ok(mut reads) = self.artifact_reads.lock() {- reads.insert(call.id.clone(), read);+ reads.insert(call.name.clone(), read);}}Ok(())@@ -155,8 +155,10 @@ impl Middleware<()> for ToolOutputMiddleware {&self,ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {+ let mut content = crate::agent::tinyagents::middleware::tool_result_text(result);// A read of a persisted artifact is the model following the envelope's// `read_with` instruction. Every stage below would defeat it: the// summarizer re-summarizes the body the model asked to see, TokenJuice@@ -167,21 +169,17 @@ impl Middleware<()> for ToolOutputMiddleware {.artifact_reads.lock().ok()- .and_then(|mut reads| reads.remove(&result.call_id));+ .and_then(|mut reads| reads.remove(tool_name));if let Some(read) = artifact_read {tracing::info!(- tool = %result.name,- call_id = %result.call_id,+ tool = tool_name,path = %read.path,offset = read.offset,- bytes = result.content.len(),+ bytes = content.len(),"[tinyagents::mw] artifact read: skipping summarizer, compaction and re-persistence");- result.content = page_artifact_read(- std::mem::take(&mut result.content),- &read,- self.budget_bytes,- );+ content = page_artifact_read(content, &read, self.budget_bytes);+ crate::agent::tinyagents::middleware::replace_tool_result_text(result, content);return Ok(());}@@ -199,19 +197,19 @@ impl Middleware<()> for ToolOutputMiddleware {// breaks the whole-string JSON parse both proposal consumers do. See// [`is_compaction_exempt`]/[`is_truncation_exempt`] for which stages// each tool family skips and why.- let compaction_exempt = is_compaction_exempt(&result.name);- let truncation_exempt = is_truncation_exempt(&result.name);+ let compaction_exempt = is_compaction_exempt(tool_name);+ let truncation_exempt = is_truncation_exempt(tool_name);if compaction_exempt {tracing::debug!(- tool = %result.name,- bytes = result.content.len(),+ tool = tool_name,+ bytes = content.len(),"[tinyagents::mw] compaction-exempt: skipping payload summarizer + tokenjuice");}if truncation_exempt {tracing::debug!(- tool = %result.name,- bytes = result.content.len(),+ tool = tool_name,+ bytes = content.len(),"[tinyagents::mw] truncation-exempt: skipping per-tool char cap + shared byte-budget backstop");}@@ -247,27 +245,22 @@ impl Middleware<()> for ToolOutputMiddleware {// when the raw body is larger than `file_read` will open: an artifact// nobody can read back is worse than the processed copy.let full_output = (!truncation_exempt- && self.tool_char_cap(&result.name).is_none()+ && self.tool_char_cap(tool_name).is_none()&& self.budget_bytes > 0&& self.artifact_store.is_some()- && result.content.len() > self.budget_bytes- && result.content.len() as u64 <= crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES)- .then(|| result.content.clone());+ && content.len() > self.budget_bytes+ && content.len() as u64 <= crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES)+ .then(|| content.clone());if !compaction_exempt {if let Some(ps) = &self.payload_summarizer {match ps- .maybe_summarize_in_parent(- ctx,- &result.name,- self.task_hint.as_deref(),- &result.content,- )+ .maybe_summarize_in_parent(ctx, tool_name, self.task_hint.as_deref(), &content).await{Ok(SummarizeOutcome::Summarized(payload)) => {tracing::info!(- tool = %result.name,+ tool = tool_name,from_bytes = payload.original_bytes,to_bytes = payload.summary_bytes,"[tinyagents::mw] payload_summarizer compressed tool output"@@ -277,15 +270,15 @@ impl Middleware<()> for ToolOutputMiddleware {to_tokens: estimate_output_tokens(payload.summary_bytes),});summarized_from_bytes = Some(payload.original_bytes);- result.content = payload.summary;+ content = payload.summary;}// The payload was fine as it was. Say nothing: a notice on// every small tool result would be pure noise.Ok(SummarizeOutcome::NotNeeded) => {}Ok(SummarizeOutcome::Unavailable(reason)) => {tracing::warn!(- tool = %result.name,- bytes = result.content.len(),+ tool = tool_name,+ bytes = content.len(),?reason,"[tinyagents::mw] payload_summarizer unavailable; disclosing raw output");@@ -296,8 +289,8 @@ impl Middleware<()> for ToolOutputMiddleware {// told the output is raw for the same reason as above.Err(error) => {tracing::warn!(- tool = %result.name,- bytes = result.content.len(),+ tool = tool_name,+ bytes = content.len(),error = %error,"[tinyagents::mw] payload_summarizer errored; disclosing raw output");@@ -309,17 +302,17 @@ impl Middleware<()> for ToolOutputMiddleware {// 2. TokenJuice content-aware compaction. This mirrors the legacy// `agent_tool_exec` stage that ran after semantic summarization and// before the hard output caps.- let before_tokenjuice_bytes = result.content.len();+ let before_tokenjuice_bytes = content.len();let compacted = crate::inference::tokenjuice::compact_output_with_config(- std::mem::take(&mut result.content),- &result.name,+ std::mem::take(&mut content),+ tool_name,self.tokenjuice_compaction_enabled,self.tokenjuice_compression,self.runtime_config.as_ref(),).await;- result.content = compacted;- let after_tokenjuice_bytes = result.content.len();+ content = compacted;+ let after_tokenjuice_bytes = content.len();if after_tokenjuice_bytes < before_tokenjuice_bytes {ctx.emit(AgentEvent::Compressed {from_tokens: estimate_output_tokens(before_tokenjuice_bytes),@@ -335,21 +328,21 @@ impl Middleware<()> for ToolOutputMiddleware {// for truncation-exempt tools (see [`is_truncation_exempt`]) — the tool// cap is still *computed* below (step 4's "no cap of its own" check// reads it), just not applied to `result.content`.- let tool_cap = self.tool_char_cap(&result.name);+ let tool_cap = self.tool_char_cap(tool_name);if !truncation_exempt {if let Some(cap) = tool_cap {- let char_count = result.content.chars().count();+ let char_count = content.chars().count();if char_count > cap {- let truncated: String = result.content.chars().take(cap).collect();+ let truncated: String = content.chars().take(cap).collect();let dropped = char_count - cap;tracing::debug!(- tool = %result.name,+ tool = tool_name,cap,char_count,dropped,"[tinyagents::mw] per-tool char cap applied");- result.content = format!(+ content = format!("{truncated}\n\n[truncated by tool cap: {dropped} more chars not shown]");}@@ -368,27 +361,27 @@ impl Middleware<()> for ToolOutputMiddleware {// tool's budget accounting.if !truncation_exempt && tool_cap.is_none() && self.budget_bytes > 0 {let (capped, outcome) = apply_per_result_persistence(- std::mem::take(&mut result.content),+ std::mem::take(&mut content),full_output,self.artifact_store.as_ref(),- &result.name,- Some(&result.call_id),+ tool_name,+ Some(tool_name),self.budget_bytes,).await;if outcome.persisted {tracing::info!(- tool = %result.name,+ tool = tool_name,from_bytes = outcome.original_bytes,to_bytes = outcome.final_bytes,"[tinyagents::mw] tool_result_artifact persisted oversized output");if let Some(path) = outcome.artifact_path.as_deref() {if let Some(store) = ctx.stores.get(TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE) {- let key = result.call_id.clone();+ let key = tool_name.to_string();let mut fields = serde_json::Map::new();- fields.insert("tool".to_string(), result.name.clone().into());- fields.insert("call_id".to_string(), result.call_id.clone().into());+ fields.insert("tool".to_string(), tool_name.into());+ fields.insert("call_id".to_string(), tool_name.into());fields.insert("artifact_path".to_string(), path.to_string().into());fields.insert("original_bytes".to_string(),@@ -402,15 +395,13 @@ impl Middleware<()> for ToolOutputMiddleware {store.put("tool_results", &key, fields.into()).await;if let Err(err) = index_result {tracing::warn!(- tool = %result.name,- call_id = %result.call_id,+ tool = tool_name,error = %err,"[tinyagents::mw] failed to index tool_result_artifact");} else {tracing::debug!(- tool = %result.name,- call_id = %result.call_id,+ tool = tool_name,artifact_path = %path,"[tinyagents::mw] indexed tool_result_artifact in run store");@@ -419,13 +410,13 @@ impl Middleware<()> for ToolOutputMiddleware {}} else if outcome.original_bytes != outcome.final_bytes {tracing::debug!(- tool = %result.name,+ tool = tool_name,from_bytes = outcome.original_bytes,to_bytes = outcome.final_bytes,"[tinyagents::mw] tool_result_budget truncated tool output");}- result.content = capped;+ content = capped;}// 5. The disclosure, last, so no cap above can eat it. The model has to@@ -433,15 +424,16 @@ impl Middleware<()> for ToolOutputMiddleware {// not summarize it — a half-truncated notice is worse than none,// because it still looks like tool output.if let Some(notice) = pending_notice {- result.content = format!("{notice}\n\n{}", result.content);+ content = format!("{notice}\n\n{content}");}if let Some(bytes) = summarized_from_bytes {- result.content = format!(- "[openhuman: summary of {bytes} bytes of tool output, complete]\n\n{}",- result.content+ content = format!(+ "[openhuman: summary of {bytes} bytes of tool output, complete]\n\n{content}");}+ crate::agent::tinyagents::middleware::replace_tool_result_text(result, content);+Ok(())}}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rsindex e6fb92db87..489944e723 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs@@ -9,8 +9,8 @@ use async_trait::async_trait;use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::{MiddlewareToolOutcome, ToolHandler, ToolMiddleware};-use tinyagents_harness::tool::ToolResult as TaToolResult;use tinyinference_llm::tool::ToolCall as TaToolCall;+use tinytools::ToolResult as TaToolResult;use crate::agent::tinyagents::policy_denial::PolicyDenial;use tinytools::Tool;@@ -178,17 +178,9 @@ impl ToolPolicyMiddleware {&is_callable,&route,);- let (content, error) = match rendered {- Ok(text) => (text, None),- Err(message) => (message.clone(), Some(message)),- };- Some(TaToolResult {- call_id: call.id.clone(),- name: call.name.clone(),- content,- raw: None,- error,- elapsed_ms: 0,+ Some(match rendered {+ Ok(text) => TaToolResult::success(text),+ Err(message) => TaToolResult::error(message),})}@@ -328,14 +320,7 @@ impl ToolMiddleware<()> for ToolPolicyMiddleware {channel = self.channel.as_str(),"[tinyagents::mw] tool blocked by channel permission ceiling");- return Ok(MiddlewareToolOutcome::Result(TaToolResult {- call_id: call.id,- name: call.name,- content: message.clone(),- raw: None,- error: Some(message),- elapsed_ms: 0,- }));+ return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(message)));}let context = ToolCallContext::session(@@ -384,14 +369,7 @@ impl ToolMiddleware<()> for ToolPolicyMiddleware {},}.render();- return Ok(MiddlewareToolOutcome::Result(TaToolResult {- call_id: call.id,- name: call.name,- content: content.clone(),- raw: None,- error: Some(content),- elapsed_ms: 0,- }));+ return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(content)));}// `use_skill`'s disclosure half (a `skill` with no `tool`) renders itsdiff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rsindex a01a87cc44..239c42e176 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs@@ -11,9 +11,9 @@ use tinyagents_harness::context::RunContext;use tinyagents_harness::error::Result as TaResult;use tinyagents_harness::middleware::Middleware;use tinyagents_harness::runtime::AgentHarness;-use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use tinyinference_llm::message::Message;use tinyinference_llm::model::{ModelRequest, ModelResponse};+use tinytools::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;use crate::agent::tinyagents::payload_summarizer::PayloadSummarizer;@@ -172,14 +172,15 @@ impl Middleware<()> for TranscriptSnapshotMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {// A tool result reaches a provider only with the next request, so it// also sits past `accepted_len` until that request is answered.if let Ok(mut guard) = self.sink.lock() {guard.messages.push(Message::tool(- result.call_id.clone(),- result.content.clone(),+ tool_name,+ crate::agent::tinyagents::middleware::tool_result_text(result),));}Ok(())@@ -379,7 +380,7 @@ impl Middleware<()> for HandoffMiddleware {.is_some(){if let Ok(mut reads) = self.artifact_reads.lock() {- reads.insert(call.id.clone());+ reads.insert(call.name.clone());}}Ok(())@@ -389,29 +390,30 @@ impl Middleware<()> for HandoffMiddleware {&self,_ctx: &mut RunContext<()>,_state: &(),+ tool_name: &str,result: &mut TaToolResult,) -> TaResult<()> {let artifact_read = self.artifact_reads.lock()- .map(|mut reads| reads.remove(&result.call_id))+ .map(|mut reads| reads.remove(tool_name)).unwrap_or(false);if artifact_read {tracing::debug!(- tool = %result.name,- call_id = %result.call_id,+ tool = tool_name,task_id = %self.task_id,"[tinyagents::mw] artifact read: skipping result handoff so the artifact pager sees the bytes");return Ok(());}- result.content = crate::agent::harness::subagent_runner::apply_handoff(+ let handoff = crate::agent::harness::subagent_runner::apply_handoff(&self.cache,- &result.name,+ tool_name,&self.task_id,&self.agent_id,- std::mem::take(&mut result.content),+ crate::agent::tinyagents::middleware::tool_result_text(result),);+ crate::agent::tinyagents::middleware::replace_tool_result_text(result, handoff);Ok(())}}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex d0a944ecba..2aa5358a23 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -16,10 +16,10 @@ use async_trait::async_trait;use tinyagents_harness::middleware::{AgentRun, BudgetTracker, Middleware};use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use tinyinference_llm::message::{ContentBlock, Message as TaMessage};use tinyinference_llm::model::{ModelResponse, SegmentRole};use tinyinference_llm::tool::{ToolCall as TaToolCall, ToolSchema};+use tinytools::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};use crate::agent::context::CLEARED_PLACEHOLDER;use crate::agent::tinyagents::payload_summarizer::{diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rsindex cef369e2a0..bf21497051 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs@@ -358,7 +358,7 @@ fn tool_char_cap_reads_the_tools_own_declared_cap() {max_retries: None,idempotent: false,cancelable: true,- sandbox: tinyagents_harness::tool::SandboxMode::Inherit,+ sandbox: tinytools::SandboxMode::Inherit,max_result_bytes: Some(10),streaming: false,}),@@ -397,7 +397,7 @@ async fn an_unavailable_notice_survives_a_tool_cap_shorter_than_itself() {max_retries: None,idempotent: false,cancelable: true,- sandbox: tinyagents_harness::tool::SandboxMode::Inherit,+ sandbox: tinytools::SandboxMode::Inherit,// Far shorter than the ~165-char notice.max_result_bytes: Some(12),streaming: false,@@ -458,7 +458,7 @@ async fn tool_output_honors_a_tools_own_cap() {max_retries: None,idempotent: false,cancelable: true,- sandbox: tinyagents_harness::tool::SandboxMode::Inherit,+ sandbox: tinytools::SandboxMode::Inherit,max_result_bytes: Some(20),streaming: false,}),@@ -697,7 +697,7 @@ async fn the_summarized_size_survives_a_tool_cap_shorter_than_the_summary() {max_retries: None,idempotent: false,cancelable: true,- sandbox: tinyagents_harness::tool::SandboxMode::Inherit,+ sandbox: tinytools::SandboxMode::Inherit,max_result_bytes: Some(12),streaming: false,}),diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rsindex 111042088a..27ce5413e7 100644--- a/crates/openhuman-core/src/agent/tinyagents/model.rs+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs@@ -160,6 +160,8 @@ fn response_to_model_response(resolved_model: None,continue_turn: None,served_from_cache: false,+ correlation: None,+ resolved_route: None,}}diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rsindex 5139902058..a48e99e532 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rs@@ -11,10 +11,10 @@ use tinyagents_harness::runtime::{AgentHarness, RunPolicy};use tinyagents_harness::steering::SteeringPolicy;use tinyagents_harness::subagent::SubAgent;use tinyagents_harness::testkit::{FakeTool, ScriptedModel, SlowModel};-use tinyagents_harness::tool::ToolResult;use tinyinference_llm::message::{AssistantMessage, Message};use tinyinference_llm::model::{ChatModel, ModelResponse};use tinyinference_llm::tool::ToolCall;+use tinytools::ToolResult;const CAP: usize = 3;diff --git a/crates/openhuman-core/src/agent/tinyagents/tools.rs b/crates/openhuman-core/src/agent/tinyagents/tools.rsindex 70090b9153..8319f7936e 100644--- a/crates/openhuman-core/src/agent/tinyagents/tools.rs+++ b/crates/openhuman-core/src/agent/tinyagents/tools.rs@@ -1,21 +1,14 @@//! `tinyagents` [`Tool`] adapter over an openhuman [`Tool`] (issue #4249).//!-//! Wraps `Arc<dyn tinytools::Tool>` so the harness agent-loop can invoke-//! the exact same tools the legacy loop runs. The harness calls `call` with a-//! validated [`TaToolCall`] (parsed JSON arguments + correlation id); we execute-//! the underlying tool and render the [`ToolResult`] the way the LLM should see-//! it (rendered via `output_for_llm`, matching the legacy tool loop).+//! It resolves a tool from the session's shared registry and delegates through+//! the canonical `tinytools::Tool` contract without creating a second tool+//! result vocabulary.use std::sync::{Arc, Mutex, PoisonError};use async_trait::async_trait;use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use tinyagents_harness::tool::{- SandboxMode, Tool, ToolAccess, ToolExecutionContext, ToolPolicy, ToolResult as TaToolResult,- ToolRuntime, ToolSideEffects, ToolTimeout as TaToolTimeout, WorkspaceAccess,-};-use tinyinference_llm::tool::{ToolCall as TaToolCall, ToolSchema};-use tinytools::ToolRunContext;+use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};/// A captured early-exit: a sub-agent invoked an early-exit tool (e.g./// `ask_user_clarification`), so the loop should pause and surface `question`@@ -75,292 +68,51 @@ impl EarlyExitHook {}}-/// A harness tool backed by an openhuman [`Tool`].-#[cfg(test)]-pub(crate) struct ToolAdapter {- inner: Arc<dyn tinytools::Tool>,-}--#[cfg(test)]-impl ToolAdapter {- /// Wrap a resolved openhuman tool.- pub(crate) fn new(inner: Arc<dyn tinytools::Tool>) -> Self {- Self { inner }- }-}--#[cfg(test)]-#[async_trait]-impl Tool<()> for ToolAdapter {- fn name(&self) -> &str {- self.inner.name()- }-- fn description(&self) -> &str {- self.inner.description()- }-- fn schema(&self) -> ToolSchema {- super::convert::spec_to_schema(&self.inner.spec())- }-- fn policy(&self) -> ToolPolicy {- tool_policy_from_openhuman_tool(self.inner.as_ref())- }-- async fn call(- &self,- _state: &(),- call: TaToolCall,- ) -> tinyagents_harness::Result<TaToolResult> {- Ok(execute_openhuman_tool(self.inner.as_ref(), call, None).await)- }-- async fn call_with_context(- &self,- _state: &(),- call: TaToolCall,- context: ToolExecutionContext,- ) -> tinyagents_harness::Result<TaToolResult> {- Ok(execute_openhuman_tool(self.inner.as_ref(), call, Some(&context)).await)- }-}--pub(crate) fn tool_policy_from_openhuman_tool(tool: &dyn tinytools::Tool) -> ToolPolicy {- use tinytools::PermissionLevel;- use tinytools::ToolTimeout;-- let permission = tool.permission_level();- let external_effect = tool.external_effect();- let read_only = matches!(- permission,- PermissionLevel::None | PermissionLevel::ReadOnly- ) && !external_effect;-- let timeout_ms = match tool.timeout_policy(&serde_json::Value::Null) {- ToolTimeout::Secs(seconds) => Some(seconds.saturating_mul(1000)),- ToolTimeout::Inherit | ToolTimeout::Unbounded => None,- };-- ToolPolicy::classified()- .with_side_effects(ToolSideEffects {- read_only,- writes_files: matches!(- permission,- PermissionLevel::Write | PermissionLevel::Execute | PermissionLevel::Dangerous- ),- network: false,- installs_dependencies: false,- destructive: matches!(permission, PermissionLevel::Dangerous),- external_service: external_effect,- payment: false,- })- .with_runtime(ToolRuntime {- timeout_ms,- // tinyagents 1.7 added a structured timeout field alongside the- // numeric timeout_ms. Inherit the run/global policy and keep the- // numeric timeout_ms above as the only per-tool deadline signal.- timeout: TaToolTimeout::Inherit,- max_retries: None,- idempotent: tool.is_concurrency_safe(&serde_json::Value::Null),- cancelable: true,- sandbox: SandboxMode::Inherit,- max_result_bytes: tool.max_result_size_chars(),- streaming: false,- })- .with_access(ToolAccess {- workspace: match permission {- PermissionLevel::None | PermissionLevel::ReadOnly => WorkspaceAccess::None,- PermissionLevel::Write | PermissionLevel::Execute | PermissionLevel::Dangerous => {- WorkspaceAccess::Any- }- },- trusted_roots: Vec::new(),- credentials: Vec::new(),- approval_required: external_effect || matches!(permission, PermissionLevel::Dangerous),- background_safe: !external_effect && !matches!(permission, PermissionLevel::Dangerous),- })-}--/// `session_id` stamped on the per-tool `DomainEvent`s this executor publishes.-/// The tinyagents adapter carries no per-turn session handle at this seam, so a-/// stable module label groups its tool-execution telemetry (matches the fixed-/// `"javascript"` label the node runtime uses for the same events).-const TINYAGENTS_TOOL_SESSION: &str = "tinyagents";--/// Execute an openhuman [`Tool`](tinytools::Tool) for a harness-/// [`TaToolCall`] and render the [`TaToolResult`] the way the LLM should see it-/// (mirrors the live-path `HarnessToolExecutor`).-pub(crate) async fn execute_openhuman_tool(- tool: &dyn tinytools::Tool,- call: TaToolCall,- context: Option<&dyn ToolRunContext>,-) -> TaToolResult {- let workspace_root = context- .and_then(|ctx| ctx.workspace())- .map(|workspace| workspace.root.display().to_string());- tracing::debug!(- tool = %call.name,- call_id = %call.id,- workspace_root = workspace_root.as_deref().unwrap_or("none"),- "[tinyagents] executing openhuman tool via harness adapter"- );-- // Measure the real execution duration (#4467, item 4) and re-publish the- // per-tool `DomainEvent`s the legacy session loop emitted so SSE consumers- // keep per-tool start/complete telemetry on the tinyagents path (#4467,- // item 5). `tool_name` is cloned up front because `call.name` is moved into- // the `TaToolResult` below.- let started = std::time::Instant::now();- let tool_name = call.name.clone();- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ToolExecutionStarted {- tool_name: tool_name.clone(),- session_id: TINYAGENTS_TOOL_SESSION.to_string(),- });-- // Approval (HITL) now runs in `ApprovalSecurityMiddleware`- // (`tinyagents/middleware.rs`, a `wrap_tool` middleware) so a denial- // short-circuits before this executor is reached.- //- // Execute through the session tool semantics the live path used- // (`agent_tool_exec`): `execute_with_context` (so markdown-capable tools- // render markdown and context-aware tools can see TinyAgents run metadata)- // under the tool's resolved timeout deadline. Without the deadline an- // inherited/long-running tool call could hang the turn indefinitely.- // Per-call `ToolPolicy`/permission gating needs the session policy context,- // which the per-tool adapter does not carry; approval covers external- // effects, and `RunPolicy::unknown_tool` recovers unregistered tool names- // before execution reaches this adapter.- let options = tinytools::ToolCallOptions {- prefer_markdown: true,- };- let (deadline, timeout_secs) =- crate::tools::timeout::resolve_tool_deadline(tool.timeout_policy(&call.arguments));- let exec = tool.execute_with_context(call.arguments.clone(), options, context);- let outcome = match deadline {- Some(d) => match tokio::time::timeout(d, exec).await {- Ok(r) => r,- Err(_) => {- let elapsed_ms = started.elapsed().as_millis() as u64;- tracing::warn!(- tool = %call.name,- timeout_secs,- elapsed_ms,- "[tinyagents] tool timed out"- );- crate::core::bus::BUS.publish(- crate::core::events::DomainEvent::ToolExecutionCompleted {- tool_name: tool_name.clone(),- session_id: TINYAGENTS_TOOL_SESSION.to_string(),- success: false,- elapsed_ms,- },- );- return TaToolResult {- call_id: call.id,- name: call.name.clone(),- content: format!(- "Error: tool '{}' timed out after {timeout_secs}s",- call.name- ),- raw: None,- error: Some(format!("tool '{}' timed out", call.name)),- elapsed_ms,- };- }- },- None => exec.await,- };- let elapsed_ms = started.elapsed().as_millis() as u64;- let result = match outcome {- Ok(result) => {- let content = result.output_for_llm(true);- let error = if result.is_error {- Some(content.clone())- } else {- None- };- TaToolResult {- call_id: call.id,- name: call.name,- content,- raw: None,- error,- elapsed_ms,- }- }- Err(e) => {- tracing::warn!(tool = %call.name, error = %e, "[tinyagents] tool failed");- TaToolResult {- call_id: call.id,- name: call.name.clone(),- content: crate::tools::status::tool_execution_error(&call.name, &e),- raw: None,- error: Some(e.to_string()),- elapsed_ms,- }- }- };- // Terminal per-tool telemetry (#4467, item 5): success is derived from the- // rendered result's error channel so a tool-reported error surfaces as a- // failed completion, mirroring the node-runtime bridge.- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ToolExecutionCompleted {- tool_name,- session_id: TINYAGENTS_TOOL_SESSION.to_string(),- success: result.error.is_none(),- elapsed_ms,- });- result-}--/// A harness tool backed by the routes' shared, `Arc`-owned tool registry sets-/// (`Arc<Vec<Box<dyn Tool>>>`). One adapter is registered per advertised tool-/// name; on call it locates the named tool across the shared sets and executes-/// it — the tinyagents analogue of the live path's `SharedToolExecutor`, which-/// lets a route reuse the same `Arc`-shared tools the legacy loop runs without-/// cloning them.-pub(crate) struct SharedToolAdapter {- sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,+/// Canonical TinyTools adapter over the shared session tool sets.+///+/// The runtime now executes the canonical `tinytools::Tool` contract directly;+/// this wrapper only resolves a non-cloneable tool from the shared registry and+/// preserves the early-exit control hook.+pub(crate) struct CanonicalSharedToolAdapter {+ sets: Vec<Arc<Vec<Box<dyn Tool>>>>,name: String,description: String,- schema: ToolSchema,- policy: ToolPolicy,- /// When set, a successful call records an [`EarlyExit`] and pauses the loop.+ parameters_schema: serde_json::Value,early_exit: Option<EarlyExitHook>,}-impl SharedToolAdapter {- /// Build an adapter for the tool named `name`, locating it across `sets` to- /// capture its advertised spec. Returns `None` when no set contains it.- pub(crate) fn for_name(- sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,- name: &str,- ) -> Option<Self> {- let (spec, policy) = sets+impl CanonicalSharedToolAdapter {+ pub(crate) fn for_name(sets: Vec<Arc<Vec<Box<dyn Tool>>>>, name: &str) -> Option<Self> {+ let spec = sets.iter().flat_map(|set| set.iter())- .find(|t| t.name() == name)- .map(|t| (t.spec(), tool_policy_from_openhuman_tool(t.as_ref())))?;+ .find(|tool| tool.name() == name)+ .map(|tool| tool.spec())?;Some(Self {sets,- name: spec.name.clone(),- description: spec.description.clone(),- schema: super::convert::spec_to_schema(&spec),- policy,+ name: spec.name,+ description: spec.description,+ parameters_schema: spec.parameters,early_exit: None,})}- /// Treat this tool as an early-exit tool: a successful call records the- /// question and pauses the run via `hook`.pub(crate) fn with_early_exit(mut self, hook: EarlyExitHook) -> Self {self.early_exit = Some(hook);self}++ fn resolved_tool(&self) -> Option<&dyn Tool> {+ self.sets+ .iter()+ .flat_map(|set| set.iter())+ .find(|tool| tool.name() == self.name)+ .map(|tool| tool.as_ref())+ }}#[async_trait]-impl Tool<()> for SharedToolAdapter {+impl Tool for CanonicalSharedToolAdapter {fn name(&self) -> &str {&self.name}@@ -369,71 +121,45 @@ impl Tool<()> for SharedToolAdapter {&self.description}- fn schema(&self) -> ToolSchema {- self.schema.clone()- }-- fn policy(&self) -> ToolPolicy {- self.policy.clone()+ fn parameters_schema(&self) -> serde_json::Value {+ self.parameters_schema.clone()}- async fn call(- &self,- _state: &(),- call: TaToolCall,- ) -> tinyagents_harness::Result<TaToolResult> {- self.call_openhuman_tool(call, None).await+ fn policy(&self) -> tinytools::ToolPolicy {+ self.resolved_tool().map(Tool::policy).unwrap_or_default()}- async fn call_with_context(- &self,- _state: &(),- call: TaToolCall,- context: ToolExecutionContext,- ) -> tinyagents_harness::Result<TaToolResult> {- self.call_openhuman_tool(call, Some(&context)).await+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(+ args,+ ToolCallOptions {+ prefer_markdown: true,+ },+ None,+ )+ .await}-}-impl SharedToolAdapter {- async fn call_openhuman_tool(+ async fn execute_with_context(&self,- call: TaToolCall,+ args: serde_json::Value,+ options: ToolCallOptions,context: Option<&dyn ToolRunContext>,- ) -> tinyagents_harness::Result<TaToolResult> {- let found = self- .sets- .iter()- .flat_map(|set| set.iter())- .find(|t| t.name() == self.name);- match found {- Some(tool) => {- let result = execute_openhuman_tool(tool.as_ref(), call, context).await;- // Early-exit (e.g. `ask_user_clarification`): on a successful- // call, record the question and pause so the runner can- // checkpoint and surface the prompt — matching the legacy seam.- if let Some(hook) = &self.early_exit {- if result.error.is_none() {- hook.trigger(&self.name, result.content.clone());- }- }- Ok(result)- }- None => {- tracing::warn!(tool = %self.name, "[tinyagents] shared tool not found");- Ok(TaToolResult {- call_id: call.id,- name: call.name,- content: format!("Error: unknown tool '{}'", self.name),- raw: None,- error: Some("unknown tool".to_string()),- elapsed_ms: 0,- })+ ) -> anyhow::Result<ToolResult> {+ let Some(tool) = self.resolved_tool() else {+ tracing::warn!(tool = %self.name, "[tinyagents] shared tool not found");+ return Ok(ToolResult::error(format!("unknown tool '{}'", self.name)));+ };+ let result = tool.execute_with_context(args, options, context).await?;+ if !result.is_error {+ if let Some(hook) = &self.early_exit {+ hook.trigger(&self.name, result.output_for_llm(true));}}+ Ok(result)}}#[cfg(test)]-#[path = "tools_tests.rs"]+#[path = "tools_canonical_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rsnew file mode 100644index 0000000000..c376483d44--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs@@ -0,0 +1,196 @@+use super::*;++use std::sync::atomic::{AtomicBool, Ordering};++use tinytools::{ToolContent, ToolPolicy};++struct RecordingTool {+ saw_context: AtomicBool,+}++#[async_trait]+impl Tool for RecordingTool {+ fn name(&self) -> &str {+ "recording"+ }++ fn description(&self) -> &str {+ "Preserves the canonical TinyTools contract."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({"type": "object", "properties": {"fail": {"type": "boolean"}}})+ }++ fn policy(&self) -> ToolPolicy {+ ToolPolicy::read_only().requiring_approval()+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ self.saw_context.store(+ context.is_some() && options.prefer_markdown,+ Ordering::SeqCst,+ );+ Ok(ToolResult {+ content: vec![+ ToolContent::Text {+ text: "plain content".to_string(),+ },+ ToolContent::Json {+ data: serde_json::json!({"preserved": true}),+ },+ ],+ is_error: args["fail"].as_bool().unwrap_or(false),+ markdown_formatted: Some("markdown content".to_string()),+ })+ }+}++struct TestToolRunContext;+impl ToolRunContext for TestToolRunContext {}++#[tokio::test]+async fn canonical_adapter_preserves_spec_policy_context_and_result() {+ let seen_context = Arc::new(AtomicBool::new(false));+ struct SharedRecordingTool(Arc<AtomicBool>);+ #[async_trait]+ impl Tool for SharedRecordingTool {+ fn name(&self) -> &str {+ "recording"+ }+ fn description(&self) -> &str {+ "Preserves the canonical TinyTools contract."+ }+ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({"type": "object"})+ }+ fn policy(&self) -> ToolPolicy {+ ToolPolicy::read_only().requiring_approval()+ }+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }+ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ self.0.store(+ context.is_some() && options.prefer_markdown,+ Ordering::SeqCst,+ );+ Ok(ToolResult {+ content: vec![+ ToolContent::Text {+ text: "plain content".into(),+ },+ ToolContent::Json {+ data: serde_json::json!({"preserved": true}),+ },+ ],+ is_error: args["fail"].as_bool().unwrap_or(false),+ markdown_formatted: Some("markdown content".into()),+ })+ }+ }+ let sets: Vec<Arc<Vec<Box<dyn Tool>>>> = vec![Arc::new(vec![Box::new(SharedRecordingTool(+ seen_context.clone(),+ ))])];+ let adapter = CanonicalSharedToolAdapter::for_name(sets, "recording").expect("registered tool");++ assert_eq!(adapter.name(), "recording");+ assert_eq!(+ adapter.description(),+ "Preserves the canonical TinyTools contract."+ );+ assert_eq!(+ adapter.parameters_schema(),+ serde_json::json!({"type": "object"})+ );+ assert_eq!(+ adapter.policy(),+ ToolPolicy::read_only().requiring_approval()+ );++ let result = adapter+ .execute_with_context(+ serde_json::json!({"fail": true}),+ ToolCallOptions::prefer_markdown(),+ Some(&TestToolRunContext),+ )+ .await+ .expect("canonical result");+ assert!(seen_context.load(Ordering::SeqCst));+ assert!(result.is_error);+ assert_eq!(+ result.markdown_formatted.as_deref(),+ Some("markdown content")+ );+ assert_eq!(result.content.len(), 2);+ assert!(matches!(result.content[0], ToolContent::Text { ref text } if text == "plain content"));+ assert!(+ matches!(result.content[1], ToolContent::Json { ref data } if data == &serde_json::json!({"preserved": true}))+ );+}++#[tokio::test]+async fn canonical_adapter_fails_closed_when_the_registered_tool_is_gone() {+ let adapter = CanonicalSharedToolAdapter {+ sets: Vec::new(),+ name: "missing".to_string(),+ description: "missing".to_string(),+ parameters_schema: serde_json::json!({"type": "object"}),+ early_exit: None,+ };++ let result = adapter+ .execute(serde_json::json!({}))+ .await+ .expect("reported failure");+ assert!(result.is_error);+ assert_eq!(result.output(), "unknown tool 'missing'");+}++#[tokio::test]+async fn early_exit_only_fires_after_a_successful_canonical_result() {+ let sets: Vec<Arc<Vec<Box<dyn Tool>>>> = vec![Arc::new(vec![Box::new(RecordingTool {+ saw_context: AtomicBool::new(false),+ })])];+ let hook = EarlyExitHook::new(SteeringHandle::allow_all());+ let adapter = CanonicalSharedToolAdapter::for_name(sets, "recording")+ .expect("registered tool")+ .with_early_exit(hook.clone());++ let failed = adapter+ .execute(serde_json::json!({"fail": true}))+ .await+ .expect("reported failure");+ assert!(failed.is_error);+ assert!(+ hook.take().is_none(),+ "reported tool errors must not pause the run"+ );++ let successful = adapter+ .execute(serde_json::json!({"fail": false}))+ .await+ .expect("success");+ assert!(!successful.is_error);+ let early_exit = hook+ .take()+ .expect("successful early-exit tool pauses the run");+ assert_eq!(early_exit.tool, "recording");+ assert_eq!(early_exit.question, "markdown content");+}diff --git a/crates/openhuman-core/src/agent/tinyagents/tools_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tools_tests.rsdeleted file mode 100644index 1e13825326..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/tools_tests.rs+++ /dev/null@@ -1,83 +0,0 @@-use super::*;-use tinytools::ToolResult as OhToolResult;-use tinytools::ToolTimeout;--/// A tool whose `execute_with_options` sleeps forever but declares a short-/// per-call timeout, so the adapter's deadline must fire.-struct HangingTool;--#[async_trait]-impl tinytools::Tool for HangingTool {- fn name(&self) -> &str {- "hang"- }- fn description(&self) -> &str {- "hangs"- }- fn parameters_schema(&self) -> serde_json::Value {- serde_json::json!({ "type": "object" })- }- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<OhToolResult> {- futures_util::future::pending::<()>().await;- Ok(OhToolResult::success("never"))- }- fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {- ToolTimeout::Secs(1)- }-}--/// A fast tool that echoes an argument, to prove the normal path still runs.-struct EchoTool;--#[async_trait]-impl tinytools::Tool for EchoTool {- fn name(&self) -> &str {- "echo"- }- fn description(&self) -> &str {- "echoes"- }- fn parameters_schema(&self) -> serde_json::Value {- serde_json::json!({ "type": "object" })- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<OhToolResult> {- let m = args.get("msg").and_then(|v| v.as_str()).unwrap_or("");- Ok(OhToolResult::success(format!("echoed:{m}")))- }-}--fn call(name: &str, args: serde_json::Value) -> TaToolCall {- TaToolCall {- id: "c1".into(),- name: name.into(),- arguments: args,- invalid: None,- }-}--#[tokio::test]-async fn tool_execution_respects_the_per_call_timeout() {- let result =- execute_openhuman_tool(&HangingTool, call("hang", serde_json::json!({})), None).await;- assert!(- result- .error- .as_deref()- .is_some_and(|e| e.contains("timed out")),- "a hanging tool must surface a timeout error, got {:?}",- result.error- );- assert!(result.content.contains("timed out"));-}--#[tokio::test]-async fn fast_tool_runs_to_completion() {- let result = execute_openhuman_tool(- &EchoTool,- call("echo", serde_json::json!({ "msg": "hi" })),- None,- )- .await;- assert!(result.error.is_none());- assert!(result.content.contains("echoed:hi"));-}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex fd68a7bcc7..da412bc7e9 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -19,8 +19,8 @@ use tinyagents_harness::agent_loop::AgentStreamItem;use tinyagents_harness::context::{RunConfig, RunContext};use tinyagents_harness::events::EventSink;use tinyagents_harness::store::StoreRegistry;-use tinyagents_harness::workspace::WorkspaceDescriptor;use tinyagents_registry::DiagnosticSeverity;+use tinytools::WorkspaceDescriptor;use tokio::sync::mpsc::Sender;use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;@@ -32,8 +32,6 @@ use crate::agent::tinyagents::host::steering::shared_steering_registry;use crate::agent::tinyagents::middleware::TurnContextMiddleware;use crate::agent::tinyagents::observability::{CapPauser, OpenhumanEventBridge, SubagentScope};use crate::agent::tinyagents::run_cancellation_context::with_run_cancellation;-#[cfg(test)]-use crate::agent::tinyagents::tools::ToolAdapter;use crate::agent::tinyagents::turn_models::TurnModels;use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;use crate::agent::tinyagents::turn_policy::effective_max_iterations;@@ -78,7 +76,7 @@ pub(crate) async fn run_turn_via_tinyagents(.set_default_model(model);let tool_count = resolved_tools.len();for tool in resolved_tools {- harness.register_tool(Arc::new(ToolAdapter::new(tool)));+ harness.register_tool(tool);}// Bound the run: one model call per legacy "iteration", and allow generous@@ -171,7 +169,7 @@ pub(crate) async fn run_turn_via_tinyagents(/// exactly `specs` (already filtered/deduped by the caller's visibility rules).////// This is the entry point the channel/sub-agent routes use to retire the-/// in-house `live` turn machine: it registers a [`SharedToolAdapter`](super::tools::SharedToolAdapter)+/// in-house `live` turn machine: it registers a canonical shared-tool adapter/// per advertised spec so the same `Arc`-shared tools the legacy loop runs are/// reused without cloning.///@@ -595,7 +593,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(terminal = Some(Ok(*run));break;}- AgentStreamItem::Failed(error) => {+ AgentStreamItem::Failed { error, .. } => {terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));break;}diff --git a/crates/openhuman-core/src/flows/ops/run_rows.rs b/crates/openhuman-core/src/flows/ops/run_rows.rsindex 55598c28cd..acc8524626 100644--- a/crates/openhuman-core/src/flows/ops/run_rows.rs+++ b/crates/openhuman-core/src/flows/ops/run_rows.rs@@ -243,13 +243,14 @@ pub(super) fn current_persisted_steps(config: &Config, run_id: &str) -> Vec<Flowpub(super) fn settle_steps(config: &Config, run_id: &str, output: &Value) -> Vec<FlowRunStep> {let persisted = current_persisted_steps(config, run_id);if persisted.is_empty() {+ let reconstructed = reconstruct_steps(output);tracing::debug!(target: "flows",run_id,reconstructed = reconstructed.len(),"[flows] settle_steps: no live-observed steps — using post-hoc reconstruction");- return reconstruct_steps(output);+ return reconstructed;}let merged = tinyflows_catalog::run_summary::settle_steps(persisted, output);tracing::debug!(diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rsindex 42e1edd25d..d9fda95890 100644--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs@@ -172,9 +172,7 @@ pub async fn agent_chat_for(// Also thread it as the turn's workspace descriptor so acting tools// that read `ToolExecutionContext::workspace` (shell) resolve their// default cwd here, and so spawned sub-agents inherit the same root.- agent.set_workspace_descriptor(Some(- tinyagents_harness::workspace::WorkspaceDescriptor::new(root.clone()),- ));+ agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(root.clone())));agent}None => build_turn_agent(config, &target)?,diff --git a/crates/openhuman-core/src/platform/cost/catalog.rs b/crates/openhuman-core/src/platform/cost/catalog.rsindex 4105cd75fd..2bf1a26def 100644--- a/crates/openhuman-core/src/platform/cost/catalog.rs+++ b/crates/openhuman-core/src/platform/cost/catalog.rs@@ -505,7 +505,7 @@ pub fn tinyagents_catalog_entry(price: &ModelPrice) -> tinyagents_registry::Modemax_input_tokens: Some(u64::from(price.context_window)),max_output_tokens: None,deprecation_date: None,- pricing: tinyagents_registry::ModelPricing {+ pricing: tinyagents_harness::cost::ModelPricing {input_per_token: per_token(price.input_per_mtok_usd),output_per_token: per_token(price.output_per_mtok_usd),cache_read_input_per_token: per_token(price.cached_input_per_mtok_usd),@@ -570,7 +570,7 @@ fn local_catalog_entry(model: &LocalCatalogModel) -> tinyagents_registry::ModelCdeprecation_date: None,// Local runtimes are not billed per token; leave every price unset (not// zero — `None` means "not applicable", not "free of charge").- pricing: tinyagents_registry::ModelPricing::default(),+ pricing: tinyagents_harness::cost::ModelPricing::default(),capabilities: tinyagents_registry::ModelCapabilities {streaming: model.streaming,tool_calling: model.tool_calling,diff --git a/crates/openhuman-core/src/tools/impl/filesystem/git_operations_tests.rs b/crates/openhuman-core/src/tools/impl/filesystem/git_operations_tests.rsindex 4aa1cba60b..fdceec4138 100644--- a/crates/openhuman-core/src/tools/impl/filesystem/git_operations_tests.rs+++ b/crates/openhuman-core/src/tools/impl/filesystem/git_operations_tests.rs@@ -93,7 +93,7 @@ fn sanitize_git_allows_safe() {#[test]fn git_resolves_cwd_from_workspace_descriptor() {use tinyagents_harness::context::{RunConfig, RunContext};- use tinyagents_harness::workspace::WorkspaceDescriptor;+ use tinytools::WorkspaceDescriptor;let action_tmp = TempDir::new().unwrap();let worktree_tmp = TempDir::new().unwrap();diff --git a/crates/openhuman-core/src/tools/impl/filesystem/mod_tests.rs b/crates/openhuman-core/src/tools/impl/filesystem/mod_tests.rsindex ca2ed420d8..77822e16be 100644--- a/crates/openhuman-core/src/tools/impl/filesystem/mod_tests.rs+++ b/crates/openhuman-core/src/tools/impl/filesystem/mod_tests.rs@@ -10,7 +10,7 @@ use crate::security::policy::TrustedAccess;use std::path::Path;use tinyagents_harness::context::{RunConfig, RunContext};use tinyagents_harness::tool::ToolExecutionContext;-use tinyagents_harness::workspace::WorkspaceDescriptor;+use tinytools::WorkspaceDescriptor;/// A run context carrying a workspace descriptor rooted at `root`, exactly as/// the session builder / sub-agent runner / `cwd` RPC param produce one.diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rsindex 2b34f1598f..5fe35a1e77 100644--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/node_exec.rs@@ -612,7 +612,7 @@ fn pool_outcome_to_result(fn node_timeout_policy(args: &serde_json::Value) -> ToolTimeout {match args.get("timeout_secs").and_then(|v| v.as_u64()) {None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Secs(secs.min(NODE_TIMEOUT_MAX_SECS)),+ Some(secs) => ToolTimeout::Millis(secs.min(NODE_TIMEOUT_MAX_SECS).saturating_mul(1000)),}}diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rsindex d773bf0930..d72629549b 100644--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs@@ -484,7 +484,7 @@ impl NpmExecTool {fn npm_timeout_policy(args: &serde_json::Value) -> ToolTimeout {match args.get("timeout_secs").and_then(|v| v.as_u64()) {None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Secs(secs.min(NPM_TIMEOUT_MAX_SECS)),+ Some(secs) => ToolTimeout::Millis(secs.min(NPM_TIMEOUT_MAX_SECS).saturating_mul(1000)),}}diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rsindex 727011be95..3c367a5522 100644--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs+++ b/crates/openhuman-core/src/tools/impl/system/python_exec.rs@@ -519,7 +519,7 @@ fn pool_outcome_to_result(fn python_timeout_policy(args: &serde_json::Value) -> ToolTimeout {match args.get("timeout_secs").and_then(|v| v.as_u64()) {None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Secs(secs.min(PYTHON_TIMEOUT_MAX_SECS)),+ Some(secs) => ToolTimeout::Millis(secs.min(PYTHON_TIMEOUT_MAX_SECS).saturating_mul(1000)),}}diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex 8c5bdb84a4..7eb0c33a75 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -231,7 +231,7 @@ impl Tool for ShellTool {match args.get("timeout_secs").and_then(|v| v.as_u64()) {// `0` (or absent) means "no deadline".None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Secs(secs),+ Some(secs) => ToolTimeout::Millis(secs.saturating_mul(1000)),}}diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests.rsindex c19baecde0..5cc4544c5c 100644--- a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests.rs@@ -43,7 +43,7 @@ fn tool_context_with_workspace() -> tinyagents_harness::tool::ToolExecutionContext {use tinyagents_harness::context::{RunConfig, RunContext};use tinyagents_harness::tool::ToolExecutionContext;- use tinyagents_harness::workspace::WorkspaceDescriptor;+ use tinytools::WorkspaceDescriptor;let ws = WorkspaceDescriptor::new(root.to_path_buf()).with_policy_id("test-worktree");let ctx: RunContext = RunContext::new(RunConfig::new("test-run"), ()).with_workspace(ws);ToolExecutionContext::from_run_context(&ctx)diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rsindex 04ddc1cc40..245f6c0a98 100644--- a/crates/openhuman-core/src/tools/timeout/mod.rs+++ b/crates/openhuman-core/src/tools/timeout/mod.rs@@ -161,7 +161,7 @@ const TOOL_TIMEOUT_GRACE_SECS: u64 = 5;/// Resolve a tool's [`ToolTimeout`] policy into the `(deadline, timeout_secs)`/// pair the agent tool-execution loop enforces:/// - `Inherit` → the global config-driven timeout (a finite deadline).-/// - `Secs(req)` → the clamped request, padded by [`TOOL_TIMEOUT_GRACE_SECS`]+/// - `Millis(req)` → the clamped request, padded by [`TOOL_TIMEOUT_GRACE_SECS`]/// for the actual deadline while `timeout_secs` reports the un-padded budget./// - `Unbounded` → `(None, 0)`: no deadline; the tool runs to completion.///@@ -174,8 +174,11 @@ pub fn resolve_tool_deadline(policy: tinytools::ToolTimeout) -> (Option<Durationlet s = tool_execution_timeout_secs();(Some(Duration::from_secs(s)), s)}- ToolTimeout::Secs(req) => {- let s = req.clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);+ ToolTimeout::Millis(req) => {+ let s = req+ .saturating_add(999)+ .saturating_div(1000)+ .clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);(Some(Duration::from_secs(s.saturating_add(TOOL_TIMEOUT_GRACE_SECS),diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.mdindex c35a861e5e..e1ea65bbf9 100644--- a/gitbooks/developing/architecture/agent-harness.md+++ b/gitbooks/developing/architecture/agent-harness.md@@ -486,9 +486,21 @@ Every provider response carries a `UsageInfo` block - input tokens, output tokenWhen the backend doesn't surface a charged amount (older builds, providers that don't bill through it), a small per-tier rate table provides a token-rate floor estimate. Direct cost from the backend always wins when available.-## Fork context - KV-cache reuse across the harness--The harness uses a task-local `ParentExecutionContext` to thread parent state into sub-agents without exploding every function signature. The same pattern carries the current sandbox mode, the interrupt fence, and the stop-hook list. Sub-agents that inherit the parent's provider, model, and prompt prefix get to **share the parent's KV-cache prefix** on the inference backend - measurably cheaper than re-prefilling from scratch.+## Explicit run context and host capabilities++Every TinyAgents turn receives an explicit `OpenHumanRunContext`, converted to+the canonical `RunContext`. It carries OpenHuman-only values such as origin,+parent execution state, progress, attachment/artifact scope, dispatch and+recency state, sandbox/depth, route observation, cancellation, thread,+workspace and stop hooks. Child contexts inherit shared tree handles while+isolating child route observation and usage accounting, so a child cannot+overwrite the parent turn's persisted facts.++`OpenHumanHostBundleFactory` is the one host composition point. It constructs+the context, definition, security, model, memory, budget, progress, learning,+tool-outcome and experience adapters from the same session/runtime inputs.+OpenHuman retains all policy decisions; TinyAgents receives only the resulting+capabilities and canonical run context.## Self-healing recapdiff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex 45f644f3c2..6add23f753 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -62,20 +62,6 @@"text": "pub(super) fn assemble_turn_harness(","occurrence": 1},- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs",- "line": 14,- "text": "use crate::agent::tinyagents::tools::{EarlyExitHook, SharedToolAdapter};",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs",- "line": 82,- "text": "if let Some(mut adapter) = SharedToolAdapter::for_name(tool_sets.to_vec(), name) {",- "occurrence": 1- },{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/middleware/arg_recovery.rs",@@ -90,111 +76,6 @@"text": "pub(crate) use turn_runner::run_turn_via_tinyagents_shared;","occurrence": 1},- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools_tests.rs",- "line": 61,- "text": "execute_openhuman_tool(&HangingTool, call(\"hang\", serde_json::json!({})), None).await;",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools_tests.rs",- "line": 75,- "text": "let result = execute_openhuman_tool(",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 80,- "text": "pub(crate) struct ToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 85,- "text": "impl ToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 94,- "text": "impl Tool<()> for ToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 104,- "text": "super::convert::spec_to_schema(&self.inner.spec())",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 116,- "text": "Ok(execute_openhuman_tool(self.inner.as_ref(), call, None).await)",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 125,- "text": "Ok(execute_openhuman_tool(self.inner.as_ref(), call, Some(&context)).await)",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 194,- "text": "pub(crate) async fn execute_openhuman_tool(",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 322,- "text": "pub(crate) struct SharedToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 332,- "text": "impl SharedToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 348,- "text": "schema: super::convert::spec_to_schema(&spec),",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 363,- "text": "impl Tool<()> for SharedToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 398,- "text": "impl SharedToolAdapter {",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/tools.rs",- "line": 411,- "text": "let result = execute_openhuman_tool(tool.as_ref(), call, context).await;",- "occurrence": 1- },{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",@@ -205,28 +86,14 @@{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 36,- "text": "use crate::agent::tinyagents::tools::ToolAdapter;",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 81,- "text": "harness.register_tool(Arc::new(ToolAdapter::new(tool)));",- "occurrence": 1- },- {- "rule": "openhuman-runtime-bridge",- "path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 203,+ "line": 201,"text": "pub(crate) async fn run_turn_via_tinyagents_shared(","occurrence": 1},{"rule": "openhuman-runtime-bridge","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 258,+ "line": 256,"text": "} = assemble_turn_harness(","occurrence": 1},@@ -555,7 +422,7 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/harness/session/builder/factory.rs",- "line": 1514,+ "line": 1513,"text": "let root = crate::agent::turn_workspace::current()?;","occurrence": 1},@@ -1444,7 +1311,7 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/model.rs",- "line": 439,+ "line": 441,"text": "super::record_resolved_provider_route(&self.provider, &self.model);","occurrence": 1},@@ -1619,28 +1486,28 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 478,+ "line": 476,"text": ".then(crate::agent::harness::turn_dispatch_guard::current)","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 511,+ "line": 509,"text": "}) = crate::agent::turn_origin::current()","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 532,+ "line": 530,"text": ".or_else(|| match crate::agent::turn_origin::current() {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/tinyagents/turn_runner.rs",- "line": 587,+ "line": 585,"text": "let run_result = with_run_cancellation(cancellation.clone(), async {","occurrence": 1},@@ -1927,28 +1794,28 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs",- "line": 219,+ "line": 217,"text": "if let Some(tx) = crate::agent::progress_sink::current_progress_sink() {","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs",- "line": 230,+ "line": 228,"text": "let run = crate::agent::turn_origin::with_origin(","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs",- "line": 237,+ "line": 235,"text": "crate::agent::tinyagents::thread_context::with_thread_id(id, run).await","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs",- "line": 295,+ "line": 293,"text": "crate::agent::tinyagents::thread_context::with_thread_id(id, run).await","occurrence": 1},@@ -2312,7 +2179,7 @@{"rule": "openhuman-upstream-reexport","path": "crates/openhuman-core/src/agent/orchestration/worktree.rs",- "line": 56,+ "line": 54,"text": "pub use tinyagents_harness::workspace::{","occurrence": 1},