The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): correct tool policy and approval middleware for tinyagents integration
Steven Enamakele374e84be65b
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex c93cbdc70e..f0bc7fdf36 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -8,7 +8,7 @@ use tinyagents_harness::cache::InMemoryResponseCache;use tinyagents_harness::middleware::{plan_mode_middleware, ArgRecoveryMiddleware, BudgetLimits, BudgetMiddleware,ContextCompressionMiddleware, PromptCacheGuardMiddleware, RepeatProgressMiddleware,- RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,+ ApprovalGateMiddleware, RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,};use tinyagents_harness::runtime::AgentHarness;use tinyagents_harness::steering::SteeringHandle;@@ -610,8 +610,9 @@ pub(super) fn assemble_turn_harness(// an approved call records a terminal audit row. Replaces the inline approval// block that used to live in the legacy tool adapter.if !hosted_security_gate {- harness.push_tool_middleware(Arc::new(middleware::ApprovalSecurityMiddleware::new(- tool_sets.clone(),+ harness.push_tool_middleware(Arc::new(ApprovalGateMiddleware::new(+ "approval_security",+ Arc::new(middleware::ApprovalSecurityMiddleware::new(tool_sets.clone())),)));}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rsindex 43b7ff4c4c..36407f8925 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/approval.rs@@ -6,8 +6,7 @@ use std::sync::Arc;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::middleware::{ApprovalResolution, ApprovalResolver};use tinyinference_llm::tool::ToolCall as TaToolCall;use tinytools::ToolResult as TaToolResult;@@ -93,79 +92,76 @@ impl ApprovalSecurityMiddleware {}}+/// Host side of the harness approval seam: the tool-set lookup, the global+/// [`ApprovalGate`] hookup and the terminal audit row. The harness+/// `ApprovalGateMiddleware` drives it (see `harness_assembly`).#[async_trait]-impl ToolMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>+impl ApprovalResolver<crate::agent::tinyagents::host::OpenHumanRunContext>for ApprovalSecurityMiddleware{- fn name(&self) -> &str {- "approval_security"- }-- async fn wrap_tool(+ async fn requires_approval(&self,- ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- state: &(),- call: TaToolCall,- next: ToolHandler<'_, (), crate::agent::tinyagents::host::OpenHumanRunContext>,- ) -> TaResult<MiddlewareToolOutcome> {+ _ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ call: &TaToolCall,+ ) -> bool {// Resolve external-effect up front so no tool borrow is held across the// approval await.- let mut audit_id: Option<String> = None;let has_ext = self.requires_approval(&call.name, &call.arguments).await;tracing::debug!(tool = %call.name,has_external_effect = has_ext,"[tinyagents::mw] checking tool for approval");- if has_ext {- if let Some(gate) = ApprovalGate::try_global() {- let approval_name = approval_tool_name(&call.name, &call.arguments);- tracing::debug!(- tool = %call.name,- approval_name = %approval_name,- "[tinyagents::mw] routing external-effect tool through approval gate"- );- let summary = summarize_action(&call.name, &call.arguments);- let redacted = redact_args(&call.arguments);- let (outcome, request_id) = gate- .intercept_audited(approval_name.as_ref(), &summary, redacted)- .await;- match outcome {- GateOutcome::Deny { reason } => {- tracing::warn!(- tool = %call.name,- reason = %reason,- "[tinyagents::mw] approval gate denied tool call"- );- return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(reason)));- }- GateOutcome::Allow => audit_id = request_id,- }- } else {+ has_ext+ }++ async fn resolve(+ &self,+ _ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ call: &TaToolCall,+ ) -> ApprovalResolution {+ let Some(gate) = ApprovalGate::try_global() else {+ tracing::warn!(+ tool = %call.name,+ "[tinyagents::mw] approval gate unavailable; external-effect tool will run without interactive approval"+ );+ return ApprovalResolution::Allow { ticket: None };+ };+ let approval_name = approval_tool_name(&call.name, &call.arguments);+ tracing::debug!(+ tool = %call.name,+ approval_name = %approval_name,+ "[tinyagents::mw] routing external-effect tool through approval gate"+ );+ let summary = summarize_action(&call.name, &call.arguments);+ let redacted = redact_args(&call.arguments);+ let (outcome, request_id) = gate+ .intercept_audited(approval_name.as_ref(), &summary, redacted)+ .await;+ match outcome {+ GateOutcome::Deny { reason } => {tracing::warn!(tool = %call.name,- "[tinyagents::mw] approval gate unavailable; external-effect tool will run without interactive approval"+ reason = %reason,+ "[tinyagents::mw] approval gate denied tool call");+ ApprovalResolution::Deny { reason }}+ GateOutcome::Allow => ApprovalResolution::Allow { ticket: request_id },}+ }- let outcome = next.run(ctx, state, call).await?;-- // Record the terminal audit row for an approved external-effect call- // (idempotent; a no-op when the id is unknown).- if let Some(id) = audit_id {- if let Some(gate) = ApprovalGate::try_global() {- if let MiddlewareToolOutcome::Result(res) = &outcome {- let exec = if res.is_error {- ExecutionOutcome::Failure- } else {- ExecutionOutcome::Success- };- let error = res.is_error.then(|| res.output());- gate.record_execution(&id, exec, error.as_deref());- }- }+ /// Record the terminal audit row for an approved external-effect call+ /// (idempotent; a no-op when the id is unknown).+ fn record(&self, ticket: &str, result: &TaToolResult) {+ if let Some(gate) = ApprovalGate::try_global() {+ let exec = if result.is_error {+ ExecutionOutcome::Failure+ } else {+ ExecutionOutcome::Success+ };+ let error = result.is_error.then(|| result.output());+ gate.record_execution(ticket, exec, error.as_deref());}- Ok(outcome)}}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rsindex 4d728951b6..0b4d46e226 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs@@ -8,10 +8,14 @@ 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::middleware::{+ MiddlewareToolOutcome, PolicyDecision, ToolCallPolicy, ToolHandler, ToolMiddleware,+ ToolPolicyGate,+};use tinyinference_llm::tool::ToolCall as TaToolCall;use tinytools::ToolResult as TaToolResult;+use crate::agent::tinyagents::host::OpenHumanRunContext;use crate::agent::tinyagents::policy_denial::PolicyDenial;use tinytools::Tool;@@ -24,7 +28,9 @@ use tinytools::Tool;/// same `"Tool '<name>' <denied|requires approval> by policy '<policy>': <reason>"`/// wording the engine produced.pub(crate) struct ToolPolicyMiddleware {- policy: Arc<dyn crate::agent::tool_policy::ToolPolicy>,+ /// The builder policy behind the harness gate, adapted to the harness+ /// `ToolCallPolicy` seam (see [`SessionToolPolicy`]).+ gate: ToolPolicyGate<OpenHumanRunContext>,/// The session's channel-permission snapshot — enforces the per-channel deny/// + per-call permission-level ceiling the engine ran in `agent_tool_exec`.session: crate::tools::agent_policy::ToolPolicySession,@@ -32,318 +38,36 @@ pub(crate) struct ToolPolicyMiddleware {/// `Tool` can be resolved for its generated-tool runtime context and its/// per-call permission level.tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,- session_id: String,channel: String,- agent_definition_id: String,}-impl ToolPolicyMiddleware {- pub(crate) fn new(- policy: Arc<dyn crate::agent::tool_policy::ToolPolicy>,- session: crate::tools::agent_policy::ToolPolicySession,- tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,- session_id: String,- channel: String,- agent_definition_id: String,- ) -> Self {- Self {- policy,- session,- tool_sets,- session_id,- channel,- agent_definition_id,- }- }-- fn resolve_tool(&self, name: &str) -> Option<&Box<dyn Tool>> {- self.tool_sets- .iter()- .flat_map(|set| set.iter())- .find(|t| t.name() == name)- }-- /// The delegation tools this session can actually call that reach one of- /// `owners`, as tool names.- ///- /// Derived from the session's own tool set — every synthesised `delegate_*`- /// tool publishes its target agent on the erased host-extension slot- /// (`traits::delegation_target`). That is deliberately the only source: a- /// static owner-to-tool table would duplicate each agent's `delegate_name`- /// and could name a tool this session was never built with, sending the- /// model from one dead end into another. Asking the tool set cannot.- fn callable_delegates_for(&self, owners: &[&str]) -> Vec<String> {- let mut found: Vec<String> = Vec::new();- for tool in self.tool_sets.iter().flat_map(|set| set.iter()) {- let Some(target) = crate::tools::host_extensions::delegation_target(tool.as_ref())- else {- continue;- };- if !owners.contains(&target) {- continue;- }- let name = tool.name().to_string();- // Uses `is_denied()`, and that is deliberate — it is the same- // predicate as the gate this hint points at.- //- // Spelled out, because two predicates live in this file and a- // sentence that does not name one has been misread three times:- //- // * This hint names a tool for the model to call DIRECTLY.- // * The direct-call gate is `channel_permission_block`'s first- // check, `if decision.is_denied()` (this file, top of the fn).- // * `is_denied()` is `!matches!(action, Allow)`, so it is TRUE for- // `HideFromPrompt` — that check is what refuses a prompt-hidden- // tool called by name.- // * Therefore a prompt-hidden delegate is not a route, and- // `is_denied()` here is exactly what keeps it out.- //- // `blocks_execution()` would be wrong here: it deliberately admits- // `HideFromPrompt` for the `use_skill` path below, where hiding is- // the disclosure mechanism rather than a refusal. Same tool, two- // call paths, two answers. A hint must use the predicate of the gate- // it points at — the hint and the gate disagreeing is how this whole- // class of bug started.- //- // Pinned by `a_prompt_hidden_delegate_is_not_offered_as_a_direct_route`.- if self.session.decision_for(&name).is_denied() || found.contains(&name) {- continue;- }- found.push(name);- }- found- }-- /// The answer to a `use_skill` call naming a tool `pack` does not contain:- /// the tools in it this session can call, or the pack's route when none.- pub(crate) fn no_such_pack_tool<'a>(- &self,- pack: &'static tinyagents_harness::tool::packs::ToolPack,- tool: &'a str,- ) -> tinyagents_harness::tool::packs::NoSuchPackTool<'a> {- let callable = pack- .tools- .iter()- .copied()- .filter(|name| {- self.resolve_tool(name).is_some()- && !self.session.decision_for(name).blocks_execution()- })- .collect();- tinyagents_harness::tool::packs::NoSuchPackTool {- not_found_marker: crate::tools::status::NOT_FOUND_MARKER,- skill: pack.id,- tool,- callable,- route: self.route_for_pack(pack),- }- }-- /// The route sentence for a pack, resolved against THIS session.- pub(crate) fn route_for_pack(- &self,- pack: &tinyagents_harness::tool::packs::ToolPack,- ) -> String {- tinyagents_harness::tool::packs::route_sentence(- &self.callable_delegates_for(pack.owners),- pack.owners,- )- }-- /// Render a `use_skill` listing scoped to what this session may call.- ///- /// This lives in the middleware because the middleware is the only layer- /// that holds the session — `UseSkillTool` is built once per registry and- /// has no idea who is calling it. Only the disclosure half is rendered here:- /// a call that names a `tool` is the execution half, which- /// `channel_permission_block` has already gated and the tool's own- /// `execute` dispatches. Returns `None` when there is nothing to scope (a- /// tool named, no `skill` argument, no pack handle), so the call falls- /// through to the tool's own `execute` unchanged.- pub(crate) fn render_skill_for_session(&self, call: &TaToolCall) -> Option<TaToolResult> {- if tinyagents_harness::tool::packs::named_tool(&call.arguments).is_some() {- return None;- }- let skill = call- .arguments- .get("skill")- .and_then(serde_json::Value::as_str)?;- let tool = self.resolve_tool(&call.name)?;- let handle = crate::tools::host_extensions::pack_registry_handle(tool.as_ref())?;- let is_callable = |name: &str| !self.session.decision_for(name).blocks_execution();- let route = crate::tools::toolpacks::pack(skill)- .map(|pack| self.route_for_pack(pack))- .unwrap_or_default();- let rendered = tinyagents_harness::tool::packs::render_pack_filtered(- &crate::tools::toolpacks::CATALOG,- skill,- handle,- // The same predicate the gate applies to `use_skill`'s inner tool.- // Two sources of truth for "can this session call it" is the bug.- &is_callable,- &route,- );- Some(match rendered {- Ok(text) => TaToolResult::success(text),- Err(message) => TaToolResult::error(message),- })- }-- /// The channel-permission gate the engine ran before the builder policy: a- /// session-level deny, then a per-call permission-level ceiling check. Returns- /// the blocking message when the call must not execute.- pub(crate) fn channel_permission_block(- &self,- call: &TaToolCall,- desktop_approval_disabled: bool,- ) -> Option<String> {- let decision = self.session.decision_for(&call.name);- let approval_only = desktop_approval_disabled- && matches!(- decision.action,- crate::tools::agent_policy::ToolPolicyAction::RequireApproval- );- if decision.is_denied() && !approval_only {- return Some(- PolicyDenial::SessionForbidden {- tool: &call.name,- required: decision.required_permission,- allowed: decision.allowed_permission,- channel: &self.channel,- }- .render(),- );- }- // For `use_skill`, validate the resolved inner tool against the session- // allowlist. Role-hidden packed tools are not checked by the outer- // policy name; without this check `use_skill` would bypass the- // session's effective allowlist for any packed tool.- //- // This runs BEFORE the argument-level permission check below, and the- // order is load-bearing. That check asks- // `UseSkillTool::permission_level_with_args`, which reports the- // pack-wide CEILING for an inner name it cannot resolve — so on a- // channel sitting under that ceiling, an invented name came back as- // `PermissionTooLow`: a permission denial for a tool that does not- // exist. Existence is not a policy question (#6302).- if call.name == "use_skill" {- if let Some(inner_tool) = call- .arguments- .get("tool")- .and_then(serde_json::Value::as_str)- {- // Existence before permission. An invented name (`install_skill`- // in `skills`) is not a policy problem, and answering it with a- // denial reads as "installs are forbidden" (#6302). A tool the- // named skill does not contain gets that answer, with what this- // session can call in the skill instead — and so does a pack- // member this core never registered (feature gate, or an- // embedder's `ToolGroups::Off`), which is equally absent no- // matter what the static pack table says.- if let Some(pack) = call- .arguments- .get("skill")- .and_then(serde_json::Value::as_str)- .and_then(crate::tools::toolpacks::pack)- {- if !pack.owns(inner_tool) || self.resolve_tool(inner_tool).is_none() {- return Some(self.no_such_pack_tool(pack, inner_tool).render());- }- }- // `blocks_execution`, NOT `is_denied`. Every withheld packed- // tool is `HideFromPrompt`, and `use_skill` is the only route it- // has — gating that route on `is_denied` refused all of them.- let inner_decision = self.session.decision_for(inner_tool);- if inner_decision.blocks_execution() {- // Name the route. A bare denial gives the model nothing to- // do differently, and a model with no next step retries the- // same call: one live turn burned its whole budget on six- // identical `use_skill` denials and died on the- // repeated-failure breaker. Same sentence the listing uses,- // resolved against the same session, so the two cannot- // tell the model different stories.- let hint = crate::tools::toolpacks::pack_for_tool(inner_tool)- .map(|pack| self.route_for_pack(pack))- .filter(|h| !h.is_empty())- .map(|h| format!(" {h}"))- .unwrap_or_default();- return Some(format!(- "Tool `{inner_tool}` is not allowed in the current session and cannot be used through `use_skill`.{hint}"- ));- }- }- }-- // Per-call permission ceiling, last: an unregistered tool has no level- // to compare, and for `use_skill` the level comes from the INNER tool- // (`permission_level_with_args`), which the block above has already- // proved to exist and to be reachable in this session.- let tool = self.resolve_tool(&call.name)?;- let call_required = tool.permission_level_with_args(&call.arguments);- if call_required > decision.allowed_permission {- return Some(- PolicyDenial::PermissionTooLow {- tool: &call.name,- required: call_required,- allowed: decision.allowed_permission,- channel: &self.channel,- }- .render(),- );- }- None- }+/// Adapter from the host's [`ToolPolicy`](crate::agent::tool_policy::ToolPolicy)+/// (request + session context) to the harness `ToolCallPolicy` seam.+struct SessionToolPolicy {+ policy: Arc<dyn crate::agent::tool_policy::ToolPolicy>,+ session_id: String,+ channel: String,+ agent_definition_id: String,}#[async_trait]-impl ToolMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for ToolPolicyMiddleware-{+impl ToolCallPolicy<OpenHumanRunContext> for SessionToolPolicy {fn name(&self) -> &str {- "tool_policy"+ policy_name}- async fn wrap_tool(+ async fn check(&self,- ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- state: &(),- call: TaToolCall,- next: ToolHandler<'_, (), crate::agent::tinyagents::host::OpenHumanRunContext>,- ) -> TaResult<MiddlewareToolOutcome> {- use crate::agent::tool_policy::{ToolCallContext, ToolPolicyDecision, ToolPolicyRequest};-- // Channel-permission ceiling first (session deny + per-call permission- // level), mirroring the engine order in `agent_tool_exec`.- #[cfg(feature = "modules")]- let desktop_approval_disabled = match self.resolve_tool(&call.name) {- Some(tool) => crate::desktop::control::approvals_disabled_for(tool.as_ref()).await,- None => false,- };- #[cfg(not(feature = "modules"))]- let desktop_approval_disabled = false;- if let Some(message) = self.channel_permission_block(&call, desktop_approval_disabled) {- tracing::debug!(- tool = call.name.as_str(),- channel = self.channel.as_str(),- "[tinyagents::mw] tool blocked by channel permission ceiling"- );- return Ok(MiddlewareToolOutcome::Result(TaToolResult::error(message)));- }-- let context = ToolCallContext::session(- self.session_id.clone(),- self.channel.clone(),- self.agent_definition_id.clone(),- call.id.clone(),- 1,- );- let request = ToolPolicyRequest::new(call.name.clone(), call.arguments.clone(), context);-- let decision = self.policy.check(&request).await;- if let Some(reason) = decision.blocking_reason().filter(|_| {- !(desktop_approval_disabled- && matches!(&decision, ToolPolicyDecision::RequireApproval { .. }))- }) {+ _ctx: &RunContext<OpenHumanRunContext>,+ call: &TaToolCall,+ ) -> PolicyDecision {+ use crate::agent::tool_policy::{ToolCallContext, ToolPolicyRequest};+ let decision = self+ .gate+ .check(ctx, &call, desktop_approval_disabled)+ .await;+ let policy_name = self.gate.policy_name();+ if let Some(reason) = decision.blocking_reason() {let blocked_action = match &decision {ToolPolicyDecision::RequireApproval { .. } => "requires approval",ToolPolicyDecision::Deny { .. } => "denied",@@ -351,13 +75,13 @@ impl ToolMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>};crate::tools::registry::denials::record(call.name.as_str(),- self.policy.name(),+ policy_name,blocked_action,reason,);tracing::debug!(tool = call.name.as_str(),- policy = self.policy.name(),+ policy = policy_name,action = blocked_action,reason = %reason,"[tinyagents::mw] tool blocked by policy"@@ -365,12 +89,12 @@ impl ToolMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>let content = match &decision {ToolPolicyDecision::RequireApproval { .. } => PolicyDenial::ApprovalRequired {tool: &call.name,- policy: self.policy.name(),+ policy: policy_name,reason,},_ => PolicyDenial::PolicyDenied {tool: &call.name,- policy: self.policy.name(),+ policy: policy_name,reason,},}diff --git a/crates/openhuman-core/src/agent/tool_policy.rs b/crates/openhuman-core/src/agent/tool_policy.rsindex b48fefbe4a..ed70737655 100644--- a/crates/openhuman-core/src/agent/tool_policy.rs+++ b/crates/openhuman-core/src/agent/tool_policy.rs@@ -126,43 +126,11 @@ fn redact_for_debug(value: &str) -> String {}/// Decision returned by a [`ToolPolicy`].-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum ToolPolicyDecision {- Allow,- /// The policy requires an approval handoff before execution.- ///- /// Session execution currently treats this as fail-closed through- /// [`ToolPolicyDecision::blocking_reason`]. Callers that can prompt for- /// approval may branch on this variant and retry after approval is granted.- RequireApproval {- reason: String,- },- Deny {- reason: String,- },-}--impl ToolPolicyDecision {- pub fn require_approval(reason: impl Into<String>) -> Self {- Self::RequireApproval {- reason: reason.into(),- }- }-- pub fn deny(reason: impl Into<String>) -> Self {- Self::Deny {- reason: reason.into(),- }- }-- /// Reason used by fail-closed executors that cannot complete approvals inline.- pub fn blocking_reason(&self) -> Option<&str> {- match self {- Self::Allow => None,- Self::RequireApproval { reason } | Self::Deny { reason } => Some(reason.as_str()),- }- }-}+///+/// The vocabulary (allow / deny / require approval) is owned by the harness+/// (`tinyagents_harness::middleware::PolicyDecision`); this alias keeps the+/// host-facing name.+pub type ToolPolicyDecision = tinyagents_harness::middleware::PolicyDecision;/// Policy middleware invoked before an agent executes a tool.#[async_trait]diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 989685fe75..21c25adcf9 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 989685fe7564fbe8cb1a154531ab91cd92f1f793+Subproject commit 21c25adcf9708bb0445eb0ad16e43ddeb5f88008