Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): apply host security gate to native children

Steven Enamakel535d2a05ae21
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
index d6a0e4bbbf..704bce5111 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
@@ -63,6 +63,7 @@ impl OpenHumanSessionHost {
None
};
let mut context = OpenHumanRunContext::new().with_host_env(&host_env);
+ context.hosted_base = self.hosted_base.clone();
context.headless_descendant_settlement = headless;
context.untrusted_input_turn = self.untrusted_input;
context.origin = origin.cloned();
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
index b5aa371405..7729771ae2 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs
@@ -199,7 +199,18 @@ pub(in super::super) async fn run_subagent_via_graph(
// parent-ledger link; forking again here would hide nested child usage in a
// second, unreachable ledger.
let dispatch = run_context.dispatch_ctx();
+ let child_tool_policy = child_tool_policy(
+ run_context.tool_policy.as_ref(),
+ agent_id,
+ &allowed_names,
+ &dynamic_tools
+ .iter()
+ .chain(parent_tools.iter())
+ .map(|tool| tool.as_ref())
+ .collect::<Vec<_>>(),
+ );
let mut child_context = run_context;
+ child_context.tool_policy = child_tool_policy.clone();
// A parallel task may omit `thread_id`; that means inherit the parent
// conversation, not erase it. Only an explicit task thread may replace
// the typed carrier's inherited affinity.
@@ -248,9 +259,9 @@ pub(in super::super) async fn run_subagent_via_graph(
mw.transcript_snapshot = Some(transcript_snapshot.clone());
mw
},
- // Sub-agents gate via their own SubagentToolSource policy path, not the
- // session `.tool_policy()`; no enforcement threaded here.
- tool_policy: None,
+ // Preserve the parent session's channel boundary for this child. The
+ // host gate also enforces its autonomy and turn-origin rules.
+ tool_policy: child_tool_policy,
// Sub-agent turns run tools with external effects; not a deterministic
// internal run, so response caching stays off (safe default).
deterministic_cacheable: false,
@@ -566,6 +577,61 @@ pub(in super::super) async fn run_subagent_via_graph(
))
}
+/// Rebuilds the inherited channel ceiling for the child's callable tool set.
+/// A parent's `HideFromPrompt` entries describe only that parent's projection;
+/// carrying them forward would hide tools explicitly granted by the child
+/// definition. Explicit denials and approval requirements still narrow the
+/// child when they refer to tools in its resolved allowlist.
+pub(super) fn child_tool_policy(
+ parent: Option<&crate::agent::tinyagents::ToolPolicyEnforcement>,
+ child_agent_id: &str,
+ child_allowed_names: &HashSet<String>,
+ child_tools: &[&dyn Tool],
+) -> Option<crate::agent::tinyagents::ToolPolicyEnforcement> {
+ let parent = parent?;
+ let profile = &parent.session.profile;
+ let channel_permissions = [(
+ profile.channel.clone(),
+ profile.allowed_permission.to_string(),
+ )]
+ .into_iter()
+ .collect();
+ let mut session = tinytools::agent_policy::ToolPolicyEngine::build_session_from_refs(
+ child_agent_id,
+ profile.channel.clone(),
+ profile.entrypoint.clone(),
+ &channel_permissions,
+ child_tools,
+ child_allowed_names,
+ );
+
+ for name in child_allowed_names {
+ let Some(decision) = parent.session.decisions.get(name) else {
+ continue;
+ };
+ if !matches!(
+ decision.action,
+ tinytools::ToolPolicyAction::Deny | tinytools::ToolPolicyAction::RequireApproval
+ ) {
+ continue;
+ }
+ session.decisions.insert(name.clone(), decision.clone());
+ session.allowed_tool_names.remove(name);
+ session.blocked_tool_names.insert(name.clone());
+ }
+
+ Some(crate::agent::tinyagents::ToolPolicyEnforcement {
+ policy: parent.policy.clone(),
+ session,
+ channel: parent.channel.clone(),
+ agent_definition_id: child_agent_id.to_string(),
+ })
+}
+
+#[cfg(test)]
+#[path = "dispatch_policy_tests.rs"]
+mod policy_tests;
+
fn spawn_subagent_trace_export(
config: Option<&crate::config::Config>,
dispatch: &crate::core::runtime::DispatchCtx,
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_policy_tests.rs b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_policy_tests.rs
new file mode 100644
index 0000000000..9d3aab7dc5
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch_policy_tests.rs
@@ -0,0 +1,121 @@
+use super::*;
+use std::collections::{HashMap, HashSet};
+use tinytools::{PermissionLevel, ToolResult};
+
+struct PolicyFixtureTool(&'static str, PermissionLevel);
+
+#[async_trait::async_trait]
+impl Tool for PolicyFixtureTool {
+ fn name(&self) -> &str {
+ self.0
+ }
+
+ fn description(&self) -> &str {
+ "policy fixture"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object"})
+ }
+
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ self.1
+ }
+}
+
+fn parent_policy(allowed: PermissionLevel) -> crate::agent::tinyagents::ToolPolicyEnforcement {
+ let tools: Vec<Box<dyn Tool>> = vec![
+ Box::new(PolicyFixtureTool(
+ "root_visible_tool",
+ PermissionLevel::ReadOnly,
+ )),
+ Box::new(PolicyFixtureTool(
+ "child_only_tool",
+ PermissionLevel::Dangerous,
+ )),
+ ];
+ let permissions = HashMap::from([("cron".to_string(), allowed.to_string())]);
+ let session = tinytools::agent_policy::ToolPolicyEngine::build_session(
+ "root_agent",
+ "cron",
+ "scheduler",
+ &permissions,
+ &tools,
+ &HashSet::from(["root_visible_tool".to_string()]),
+ );
+ crate::agent::tinyagents::ToolPolicyEnforcement {
+ policy: Arc::new(crate::agent::tinyagents::middleware::tool_policy::AllowAllToolPolicy),
+ session,
+ channel: "cron".to_string(),
+ agent_definition_id: "root_agent".to_string(),
+ }
+}
+
+#[test]
+fn child_policy_rebuilds_parent_hidden_tools_under_the_same_channel_ceiling() {
+ let parent = parent_policy(PermissionLevel::Dangerous);
+ assert_eq!(
+ parent.session.decision_for("child_only_tool").action,
+ tinytools::ToolPolicyAction::HideFromPrompt
+ );
+
+ let child_tool = PolicyFixtureTool("child_only_tool", PermissionLevel::Dangerous);
+ let child = child_tool_policy(
+ Some(&parent),
+ "task_manager_agent",
+ &HashSet::from(["child_only_tool".to_string()]),
+ &[&child_tool],
+ )
+ .expect("the child inherits the channel policy");
+
+ assert_eq!(
+ child.session.decision_for("child_only_tool").action,
+ tinytools::ToolPolicyAction::Allow,
+ "the parent's prompt projection does not erase the child's declared tool"
+ );
+ assert_eq!(
+ child.session.profile.allowed_permission,
+ PermissionLevel::Dangerous
+ );
+}
+
+#[test]
+fn child_policy_keeps_the_parent_channel_ceiling_and_explicit_denials() {
+ let child_tool = PolicyFixtureTool("child_only_tool", PermissionLevel::Dangerous);
+ let lower_ceiling_parent = parent_policy(PermissionLevel::ReadOnly);
+ let lower_ceiling_child = child_tool_policy(
+ Some(&lower_ceiling_parent),
+ "task_manager_agent",
+ &HashSet::from(["child_only_tool".to_string()]),
+ &[&child_tool],
+ )
+ .expect("the child inherits the channel policy");
+ assert_eq!(
+ lower_ceiling_child
+ .session
+ .decision_for("child_only_tool")
+ .action,
+ tinytools::ToolPolicyAction::Deny
+ );
+
+ let mut explicitly_denied_parent = parent_policy(PermissionLevel::Dangerous);
+ explicitly_denied_parent.session.deny(["child_only_tool"]);
+ let explicitly_denied_child = child_tool_policy(
+ Some(&explicitly_denied_parent),
+ "task_manager_agent",
+ &HashSet::from(["child_only_tool".to_string()]),
+ &[&child_tool],
+ )
+ .expect("the child inherits the parent policy");
+ assert_eq!(
+ explicitly_denied_child
+ .session
+ .decision_for("child_only_tool")
+ .action,
+ tinytools::ToolPolicyAction::Deny
+ );
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 44a7fc758c..1da2dcbf7b 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -309,6 +309,10 @@ pub struct OpenHumanRunContext {
/// The context the turn runs under, read by tools, middleware and the
/// provider factory instead of the ambient scope. Children inherit it.
pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
+ /// Session-owned host capabilities used to authorize native child turns.
+ /// A child keeps the same authority boundary while retaining its native
+ /// run identity and lifecycle.
+ pub(crate) hosted_base: Option<Arc<super::OpenHumanHostBase>>,
/// The turn tree's transcript store (the root session's locator), where
/// sub-agent transcripts land under the parent's store key. Inherited.
pub transcripts: Option<Arc<dyn tinyagents_session::transcript::TranscriptLocator>>,
@@ -452,6 +456,7 @@ impl OpenHumanRunContext {
prepared_context_sources: Arc::new(Vec::new()),
memory_identity: None,
core: None,
+ hosted_base: None,
transcripts: None,
file_state_agent_id: None,
tool_result_artifact_index: None,
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
index 0d494741d1..55e2281134 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_policy.rs
@@ -69,6 +69,27 @@ impl ToolPolicyMiddleware {
session: tinytools::ToolPolicySession,
tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
channel: String,
+ ) -> Self {
+ Self::build(policy, session, tool_sets, channel, true)
+ }
+
+ /// Builds the agent-configured policy middleware when the hosted security
+ /// gate already enforces the same channel session ceiling.
+ pub(crate) fn new_without_session_ceiling(
+ policy: Arc<dyn ToolCallPolicy<OpenHumanRunContext>>,
+ session: tinytools::ToolPolicySession,
+ tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
+ channel: String,
+ ) -> Self {
+ Self::build(policy, session, tool_sets, channel, false)
+ }
+
+ fn build(
+ policy: Arc<dyn ToolCallPolicy<OpenHumanRunContext>>,
+ session: tinytools::ToolPolicySession,
+ tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
+ channel: String,
+ enforce_session_ceiling: bool,
) -> Self {
let host = Arc::new(ToolPolicyHostState {
session,
@@ -109,8 +130,11 @@ impl ToolPolicyMiddleware {
}
});
let post_host = host.clone();
- let gate = ToolPolicyGateMiddleware::new(desktop_policy)
- .with_session_ceiling(session_ceiling)
+ let mut gate = ToolPolicyGateMiddleware::new(desktop_policy);
+ if enforce_session_ceiling {
+ gate = gate.with_session_ceiling(session_ceiling);
+ }
+ let gate = gate
.with_denial_renderer(denial)
.with_post_gate(Arc::new(move |_ctx, call| {
post_host.render_skill_for_session(call)
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index b0ba4f884c..9ef6b8cc06 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@ -179,7 +179,28 @@ async fn drive_turn(
// otherwise the harness model-call cap would be zero and abort the run before
// the first provider call.
let max_iterations = effective_max_iterations(max_iterations);
- let hosted_security_gate = hosted_root.is_some();
+ let native_security_gate = if hosted_root.is_none() {
+ native_subagent.as_ref().and_then(|native| {
+ run_context.hosted_base.as_ref().map(|base| {
+ let mut gate = crate::agent::tinyagents::host::OpenHumanSecurityGate::new(
+ base.security_policy.clone(),
+ tool_sets.clone(),
+ )
+ .with_input_screening(!run_context.untrusted_input_turn)
+ .with_approval(run_context.approval.clone())
+ .with_dispatch(run_context.dispatch_ctx())
+ .with_headless_descendant_settlement(run_context.headless_descendant_settlement);
+ if let Some(policy) = tool_policy.as_ref() {
+ gate = gate.with_tool_policy(Arc::new(policy.session.clone()));
+ }
+ (Arc::new(gate), native.name.clone())
+ })
+ })
+ } else {
+ None
+ };
+ let is_hosted_root = hosted_root.is_some();
+ let hosted_security_gate = is_hosted_root || native_security_gate.is_some();
let is_local = turn_models.is_local();
// Wrap concrete routes before the invocation-local hosted resolver captures them.
let turn_models = turn_models.with_budget(run_context.model_budget.as_ref());
@@ -228,13 +249,8 @@ async fn drive_turn(
error_slot,
..
} = turn_models;
- let plan_models = turn_models_for_plan(
- model,
- primary,
- tier_routes,
- &error_slot,
- hosted_security_gate,
- );
+ let plan_models =
+ turn_models_for_plan(model, primary, tier_routes, &error_slot, is_hosted_root);
let planner = OpenHumanTurnPlanner {
models: plan_models.clone(),
policy,
@@ -559,6 +575,7 @@ async fn drive_turn(
has_route_fallback,
dispatch: run_context.dispatch_ctx(),
hosted_security_gate,
+ native_security_gate,
pause_at_cap,
run_mode: run_context.thread_id.as_deref().map(|thread_id| {
crate::threads::run_mode::handle_for_thread(&run_context.dispatch_ctx(), thread_id)
@@ -588,7 +605,7 @@ async fn drive_turn(
&run_context,
&subagent_scope,
);
- turn_observer::install(&mut prepared.harness, &sink, hosted_security_gate);
+ turn_observer::install(&mut prepared.harness, &sink, is_hosted_root);
// Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
// The projected `CapabilityRegistry` produced these diagnostics while the
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index 16c40a5ed5..7254c80841 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@ -13,15 +13,18 @@
use std::collections::HashSet;
use std::sync::Arc;
+use async_trait::async_trait;
use tinyagents_harness::cache::InMemoryResponseCache;
+use tinyagents_harness::host::security_gate::{GateDecision, SecurityGate, ToolCallRequest};
use tinyagents_harness::middleware::{
install_unmet_deliverable, is_repeat_call_exempt, tool_sets_lookup, ResearchBudgetMiddleware,
ShellTurnBudget, TurnClockMiddleware, DIRECT_WEB_READ_LIMIT,
};
use tinyagents_harness::middleware::{
plan_mode_middleware, ApprovalGateMiddleware, ArgRecoveryMiddleware, BudgetLimits,
- BudgetMiddleware, ContextCompressionMiddleware, PromptCacheGuardMiddleware,
- RepeatProgressMiddleware, RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,
+ BudgetMiddleware, ContextCompressionMiddleware, MiddlewareToolOutcome,
+ PromptCacheGuardMiddleware, RepeatProgressMiddleware, RunModeHandle, ToolHandler,
+ ToolMiddleware, ToolPolicyMiddleware as TaToolPolicyMiddleware,
};
use tinyagents_harness::runtime::AgentHarness;
use tinyagents_harness::steering::SteeringHandle;
@@ -32,6 +35,7 @@ use tinyinference_llm::model::CapabilitySet;
use crate::agent::tinyagents::context_wiring::install_context_ladder;
use crate::agent::tinyagents::host::OpenHumanRunContext;
+use crate::agent::tinyagents::host::OpenHumanSecurityGate;
use crate::agent::tinyagents::middleware;
use crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware;
use crate::agent::tinyagents::observability::{ProviderUsageCarry, SubagentScope, ToolFailureMap};
@@ -70,6 +74,9 @@ pub(super) struct TurnMiddlewareInputs {
/// Hosted roots authorize tools through `OpenHumanSecurityGate`; installing
/// the legacy approval middleware as well would issue a second approval.
pub(super) hosted_security_gate: bool,
+ /// Host gate installed at the native child's tool boundary, avoiding a
+ /// full hosted root invocation while preserving the same authorization.
+ pub(super) native_security_gate: Option<(Arc<OpenHumanSecurityGate>, String)>,
/// Whether this run pauses gracefully at its model-call cap (issue #6014).
/// Only such a run gets the in-loop conclusion: a run that errors at its cap
/// instead (the channel/CLI path, which maps the stop to
@@ -139,6 +146,7 @@ pub(super) fn install_turn_middleware(
has_route_fallback,
dispatch,
hosted_security_gate,
+ native_security_gate,
pause_at_cap,
run_mode,
memory_turn,
@@ -515,6 +523,13 @@ pub(super) fn install_turn_middleware(
// `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 the legacy tool adapter.
+ let native_security_gate_installed = native_security_gate.is_some();
+ if let Some((gate, agent_id)) = native_security_gate {
+ harness.push_tool_middleware(Arc::new(NativeSubagentSecurityMiddleware {
+ gate,
+ agent_id,
+ }));
+ }
if !hosted_security_gate {
harness.push_tool_middleware(Arc::new(ApprovalGateMiddleware::new(
"approval_security",
@@ -542,14 +557,22 @@ pub(super) fn install_turn_middleware(
.as_ref()
.map(|enforcement| enforcement.session.clone());
if let Some(enforcement) = tool_policy {
- harness.push_tool_middleware(Arc::new(
+ let middleware = if native_security_gate_installed {
+ middleware::tool_policy::ToolPolicyMiddleware::new_without_session_ceiling(
+ enforcement.policy,
+ enforcement.session,
+ tool_sets.clone(),
+ enforcement.channel,
+ )
+ } else {
middleware::tool_policy::ToolPolicyMiddleware::new(
enforcement.policy,
enforcement.session,
tool_sets.clone(),
enforcement.channel,
- ),
- ));
+ )
+ };
+ harness.push_tool_middleware(Arc::new(middleware));
}
// Credential scrubbing (issue #4453): redact credential-shaped secrets out of
@@ -633,3 +656,108 @@ pub(super) fn install_turn_middleware(
prompt_cache_guard,
}
}
+
+struct NativeSubagentSecurityMiddleware {
+ gate: Arc<OpenHumanSecurityGate>,
+ agent_id: String,
+}
+
+#[async_trait]
+impl ToolMiddleware<(), OpenHumanRunContext> for NativeSubagentSecurityMiddleware {
+ fn name(&self) -> &str {
+ "openhuman_security_gate"
+ }
+
+ async fn wrap_tool(
+ &self,
+ ctx: &tinyagents_harness::context::RunContext<OpenHumanRunContext>,
+ state: &(),
+ call: tinyinference_llm::tool::ToolCall,
+ next: ToolHandler<'_, (), OpenHumanRunContext>,
+ ) -> tinyagents_harness::error::Result<MiddlewareToolOutcome> {
+ let call_id = call.id.to_string();
+ let request = ToolCallRequest::new(
+ call.name.clone(),
+ call.arguments.clone(),
+ self.agent_id.clone(),
+ )
+ .with_call_id(call_id.clone());
+ let decision = match self.gate.authorize_tool(&request).await {
+ Ok(decision) => decision,
+ Err(error) => {
+ tracing::error!(tool = %call.name, %error, "native child authorization failed closed");
+ return Ok(tinytools::ToolResult::error(
+ "Tool authorization failed because the security check could not complete.",
+ )
+ .into());
+ }
+ };
+ match decision {
+ GateDecision::Allow | GateDecision::Prompted { approved: true } => {}
+ GateDecision::Deny { reason } => {
+ return Ok(tinytools::ToolResult::error(reason).into());
+ }
+ GateDecision::Prompted { approved: false } => {
+ return Ok(tinytools::ToolResult::error("Approval was not granted.").into());
+ }
+ }
+
+ let mut audit = self
+ .gate
+ .take_audit_request_id(&call_id)
+ .map(NativeSecurityAudit::new);
+ let result = next.run(ctx, state, call).await;
+ if let Some(audit) = &mut audit {
+ match &result {
+ Ok(MiddlewareToolOutcome::Result(result)) if result.is_error => {
+ audit.record(
+ crate::security::approval::ExecutionOutcome::Failure,
+ Some(result.output()),
+ );
+ }
+ Ok(_) => audit.record(crate::security::approval::ExecutionOutcome::Success, None),
+ Err(error) => audit.record(
+ crate::security::approval::ExecutionOutcome::Failure,
+ Some(error.to_string()),
+ ),
+ }
+ }
+ result
+ }
+}
+
+struct NativeSecurityAudit {
+ request_id: String,
+ recorded: bool,
+}
+
+impl NativeSecurityAudit {
+ fn new(request_id: String) -> Self {
+ Self {
+ request_id,
+ recorded: false,
+ }
+ }
+
+ fn record(
+ &mut self,
+ execution: crate::security::approval::ExecutionOutcome,
+ error: Option<String>,
+ ) {
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ gate.record_execution(&self.request_id, execution, error.as_deref());
+ }
+ self.recorded = true;
+ }
+}
+
+impl Drop for NativeSecurityAudit {
+ fn drop(&mut self) {
+ if !self.recorded {
+ self.record(
+ crate::security::approval::ExecutionOutcome::Failure,
+ Some("tool execution ended before reporting a result".to_string()),
+ );
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs b/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
index 428837cd62..b911a63b16 100644
--- a/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
@@ -19,7 +19,6 @@ struct CronChildModel {
accepted_followups: std::sync::atomic::AtomicUsize,
child_attempts_dangerous_tool: bool,
child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool,
- child_dangerous_tool_denied: std::sync::atomic::AtomicBool,
child_started: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
child_release: tokio::sync::Notify,
}
@@ -131,15 +130,6 @@ impl ChatModel<()> for CronChildModel {
}
if self.child_attempts_dangerous_tool {
if call > 0 {
- eprintln!("Cron child followup messages: {:?}", request.messages);
- self.child_dangerous_tool_denied.store(
- request.messages.iter().any(|message| {
- message
- .text()
- .contains("Scheduled agent turns may use read-only tools only")
- }),
- std::sync::atomic::Ordering::SeqCst,
- );
return Ok(ModelResponse::assistant(
"headless-cron-child-returned-after-policy-denial",
));
@@ -212,7 +202,6 @@ async fn scheduled_agent_history_includes_its_spawned_child_result() {
accepted_followups: std::sync::atomic::AtomicUsize::new(0),
child_attempts_dangerous_tool: false,
child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
- child_dangerous_tool_denied: std::sync::atomic::AtomicBool::new(false),
child_started: std::sync::Mutex::new(None),
child_release: tokio::sync::Notify::new(),
});
@@ -282,7 +271,6 @@ async fn scheduled_agent_timeout_cancels_its_blocked_child_before_history_settle
accepted_followups: std::sync::atomic::AtomicUsize::new(0),
child_attempts_dangerous_tool: false,
child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
- child_dangerous_tool_denied: std::sync::atomic::AtomicBool::new(false),
child_started: std::sync::Mutex::new(None),
child_release: tokio::sync::Notify::new(),
});
@@ -391,7 +379,6 @@ async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
accepted_followups: std::sync::atomic::AtomicUsize::new(0),
child_attempts_dangerous_tool: true,
child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
- child_dangerous_tool_denied: std::sync::atomic::AtomicBool::new(false),
child_started: std::sync::Mutex::new(None),
child_release: tokio::sync::Notify::new(),
});
@@ -425,8 +412,8 @@ async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
);
assert_eq!(
model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
- 2,
- "the child receives the denied tool result and then completes"
+ 1,
+ "the child model requested the declared destructive tool"
);
assert!(
model
@@ -434,9 +421,6 @@ async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
.load(std::sync::atomic::Ordering::SeqCst),
"the real child model request exposed the declared destructive tool"
);
- assert!(model
- .child_dangerous_tool_denied
- .load(std::sync::atomic::Ordering::SeqCst));
let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
&config.workspace_dir,
&format!("cron:{}", job.id),
@@ -450,20 +434,31 @@ async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
assert_eq!(jobs.len(), 1, "one native child belongs to this Cron job");
assert_eq!(
jobs[0].status,
- tinyagents_orchestration::subagent::SubAgentJobStatus::Completed,
- "the child may recover after the denied action and report the denial"
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Incomplete,
+ "the child records the policy-blocked action as an incomplete run"
);
- assert!(jobs[0]
- .output
+ let child_run_id = jobs[0]
+ .subagent_run_id
.as_deref()
- .unwrap_or_default()
- .contains("headless-cron-child-returned-after-policy-denial"));
+ .expect("native child records its own run id");
+ let child_events =
+ crate::agent::tinyagents::journal::read_run_events(&inspect_dispatch, child_run_id, 0)
+ .await
+ .expect("read the native child's durable tool events");
+ let denial = child_events
+ .iter()
+ .find_map(|observation| match &observation.event {
+ tinyagents_harness::events::AgentEvent::ToolCompleted {
+ tool_name,
+ error: Some(error),
+ ..
+ } if tool_name == "delete_artifact" => Some(error.as_str()),
+ _ => None,
+ })
+ .expect("the native child journal records the denied delete_artifact call");
+ assert!(denial.contains("Scheduled agent turns may use read-only tools only"));
+ assert!(!denial.contains("not found"));
let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
assert_eq!(runs.len(), 1);
- assert_eq!(runs[0].status, "ok");
- assert!(runs[0]
- .output
- .as_deref()
- .unwrap_or_default()
- .contains("headless-cron-child-returned-after-policy-denial"));
+ assert_eq!(runs[0].status, "error");
}