Skip to content

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

Merge remote-tracking branch 'origin/main' into epic-8088-final-rollup

Steven Enamakelf8c565a2015d
diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 37129da1b4,5d51e64404..e68afd2869
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@@ -312,6 -301,10 +312,9 @@@ pub struct OpenHumanRunContext
/// binding the compaction summarizer recalls under. A child run has its
/// own and does not inherit it.
pub(crate) memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
- /// Shell commands this turn left running past their yield point
- /// (`sandbox::shell_processes`). Each run, child runs included, has its
- /// own; dropping the last copy at the end of the run stops them.
++ /// Shell commands this turn left running past their yield point. Each run,
++ /// including child runs, has its own registry; dropping the last copy stops them.
+ pub(crate) shell_processes: Arc<crate::sandbox::shell_processes::ShellProcesses>,
}
/// The host callbacks and caps a turn's harness assembly installs, taken from
@@@ -332,11 -323,336 +333,14 @@@ pub use super::operation_context::{appr
pub(crate) use super::operation_context::{
command_environment_for_tool, dispatch_ctx_for_tool, memory_identity_for_tool,
memory_in_prompt_for_tool, parent_agent_id_for_tool, sandbox_mode_for_tool,
- task_recency_window_for_tool, turn_origin_for_tool, HostOperationContext,
+ shell_processes_for_tool, task_recency_window_for_tool, turn_origin_for_tool,
+ HostOperationContext,
};
+ #[cfg(test)]
+ pub(crate) use super::operation_context::{test_turn_run, tool_context_with_approval};
-impl Default for OpenHumanRunContext {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl OpenHumanRunContext {
- /// Builds an unbound context. Entry points set only the values their turn
- /// actually owns; `None` is an explicit absence, not an ambient fallback.
- pub fn new() -> Self {
- Self {
- model_budget: None,
- dispatch_admission: None,
- response_shape: None,
- max_spawn_depth: None,
- origin: None,
- approval: Default::default(),
- progress: None,
- stop_hooks: Vec::new(),
- goal_suppressed: false,
- tool_hooks: Vec::new(),
- tool_call_limit: None,
- untrusted_input_turn: false,
- turn_deadline: None,
- parent: None,
- prepared_context_sources: Arc::new(Vec::new()),
- memory_identity: None,
- core: None,
- transcripts: None,
- file_state_agent_id: None,
- tool_result_artifact_index: None,
- attachment_placeholders: Arc::new(Vec::new()),
- dispatch: None,
- task_recency_window: None,
- command_environment: None,
- autonomous_iter_cap: None,
- sandbox_mode: None,
- spawn_depth: 0,
- subagent_usage: Arc::new(Mutex::new(Vec::new())),
- parent_subagent_usage: None,
- resolved_route: Arc::new(Mutex::new(None)),
- cancellation: tinyagents_harness::cancel::CancellationToken::default(),
- thread_id: None,
- root_run_id: None,
- workspace: None,
- tool_outcomes: None,
- tool_policy: None,
- current_tools: None,
- current_synthesized_tools: None,
- recorded_tool_names: Arc::new(std::collections::HashSet::new()),
- deferred_tool_names: Arc::new(std::collections::HashSet::new()),
- tool_rules: None,
- context_middleware: None,
- session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())),
- required_output: None,
- tool_dialect: tinyagents_harness::config::ToolDispatcher::Auto,
- memory_turn: None,
- shell_processes: crate::sandbox::shell_processes::ShellProcesses::new(),
- }
- }
-
- /// Pins the harness tool dialect to the one the session prompt speaks.
- #[must_use]
- pub(crate) fn with_tool_dialect(
- mut self,
- dialect: tinyagents_harness::config::ToolDispatcher,
- ) -> Self {
- self.tool_dialect = dialect;
- self
- }
-
- /// Binds the context this run acts under, held weakly so a run kept past its turn never pins the tenant.
- #[must_use]
- pub fn with_core(mut self, core: Option<Arc<crate::core::runtime::CoreContext>>) -> Self {
- self.core = core.as_ref().map(Arc::downgrade);
- self
- }
-
- /// The dispatch context this run's readers use: its own `core`, else the
- /// calling task's (a run assembled by a caller that did not bind one).
- pub fn dispatch_ctx(&self) -> crate::core::runtime::DispatchCtx {
- crate::core::runtime::DispatchCtx::from_weak(self.core.as_ref())
- }
-
- /// The connected-identities prompt section, read under this run's context.
- pub(crate) fn connected_identities_md(&self) -> String {
- crate::integrations::render_connected_identities(&self.dispatch_ctx())
- }
-
- /// Sets the direct TinyTools workspace descriptor for this run.
- pub fn with_workspace(mut self, workspace: tinytools::WorkspaceDescriptor) -> Self {
- self.workspace = Some(workspace);
- self
- }
-
- /// Creates (once) this host turn's durable-unique root config.
- ///
- /// The returned root id is stable across the session/runtime and hosted
- /// harness boundaries for this one actual turn. Callers creating a new
- /// root must call this once rather than construct a config from a repeated
- /// literal; callers creating children must use [`direct_subagent_child`].
- pub(crate) fn root_run_config(&mut self, kind: &str) -> tinyagents_harness::context::RunConfig {
- let run_id = self
- .root_run_id
- .get_or_insert_with(|| fresh_root_run_config(kind).run_id.as_str().to_owned())
- .clone();
- tinyagents_harness::context::RunConfig::new(run_id)
- }
-
- /// Binds a direct runner to its explicit parent without exposing the
- /// child-ledger link reserved for recursive [`Self::child`] calls.
- pub(crate) fn with_parent(mut self, parent: ParentExecutionContext) -> Self {
- self.parent = Some(parent);
- self
- }
-
- /// Installs this turn's parent snapshot, binding the run's live progress
- /// sink to it.
- ///
- /// The snapshot is built from a prelude that captured `on_progress` when
- /// the runtime session was first created. A web-chat turn checks out a
- /// cached session — so that build is a no-op — and only afterwards calls
- /// `set_on_progress`, leaving the prelude's copy `None` for the rest of the
- /// session's life. Sub-agent spawn and completion are the only progress
- /// events that ride this parent sink instead of the harness event
- /// projection, so a stale `None` drops them outright: no `subagent_spawned`
- /// socket event, no run-ledger row, and a "Background tasks" panel that
- /// reads "none running" while sub-agents are working. The run context's own
- /// sink is the live one (it is what `driver.rs` hands the turn graph), so
- /// prefer it and keep the snapshot as the fallback.
- ///
- /// Returns the installed parent so a caller that must launch a sub-agent
- /// *before* the rest of the turn is assembled — `inject_triggered_memory_agent_context`
- /// is the one such caller — hands it the bound context rather than the
- /// stale snapshot it started from.
- pub(crate) fn attach_parent(
- &mut self,
- mut parent: ParentExecutionContext,
- ) -> &ParentExecutionContext {
- parent.on_progress = self.progress.clone().or(parent.on_progress);
- self.parent.insert(parent)
- }
-
- /// The callbacks and caps this turn's harness assembly installs.
- pub(crate) fn harness_host_policy(&self) -> HarnessHostPolicy {
- HarnessHostPolicy {
- stop_hooks: self.stop_hooks.clone(),
- tool_hooks: self.tool_hooks.clone(),
- tool_call_cap: self.tool_call_limit,
- }
- }
-
- /// The real tool invocation budget for a turn of `max_iterations`: the
- /// product default, narrowed by the host's explicit cap.
- pub(crate) fn tool_call_limit_for(&self, max_iterations: usize) -> usize {
- crate::agent::tinyagents::turn_policy::tool_call_limit(max_iterations, self.tool_call_limit)
- }
-
- /// Applies the host environment an entry point handed to the session:
- /// shared budget, delegation depth, cancellation, deadline and hooks.
- #[must_use]
- pub(crate) fn with_host_env(mut self, env: &crate::agent::turn_env::HostTurnEnv) -> Self {
- self.model_budget = env.model_budget.clone().or(self.model_budget);
- self.dispatch_admission = env.dispatch_admission.clone().or(self.dispatch_admission);
- self.max_spawn_depth = env.spawn_depth_limit.or(self.max_spawn_depth);
- if let Some(cancellation) = &env.cancellation {
- self.cancellation = cancellation.clone();
- }
- self.turn_deadline = env.turn_deadline.or(self.turn_deadline);
- self.tool_call_limit = env.tool_call_limit.or(self.tool_call_limit);
- self.command_environment = env.command_environment.clone().or(self.command_environment);
- self.memory_identity = env.memory_identity.clone().or(self.memory_identity);
- self.core = env.core.clone().or(self.core);
- self.stop_hooks
- .extend(env.hooks.stop_hooks().iter().cloned());
- self.tool_hooks
- .extend(env.hooks.tool_hooks().iter().cloned());
- self
- }
-
- /// Sets the same cancellation token on this context and its TinyAgents run.
- pub fn with_cancellation(
- mut self,
- cancellation: tinyagents_harness::cancel::CancellationToken,
- ) -> Self {
- self.cancellation = cancellation;
- self
- }
-
- /// Builds a child context that inherits authority, cancellation and shared
- /// workspace policy while keeping route observation and usage isolated.
- pub fn child(&self) -> Self {
- let mut child = self.clone();
- child.spawn_depth = self.spawn_depth.saturating_add(1);
- child.file_state_agent_id = None;
- child.parent_subagent_usage = Some(self.subagent_usage.clone());
- child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
- child.resolved_route = Arc::new(Mutex::new(None));
- child.memory_turn = None;
- child.response_shape = None;
- child.shell_processes = crate::sandbox::shell_processes::ShellProcesses::new();
- child
- }
-
- /// Builds the explicit carrier for detached background work.
- ///
- /// A detached task keeps the authority, thread and workspace descriptor it
- /// needs to execute and deliver its own result, but it is no longer part of
- /// the originating turn's dispatch timer or subagent usage roll-up. It
- /// still inherits the shared monetary budget and physical-dispatch policy,
- /// and it does not observe cancellation that only stopped the interactive
- /// turn.
- pub fn detached_child(&self) -> Self {
- let mut child = self.child();
- // The chat surface belongs to the turn that started it. A detached
- // child's parks route through the origin and are marked detached, so
- // their cards survive the parent turn's end (#5499).
- child.approval = Default::default();
- child.dispatch = None;
- child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
- child.parent_subagent_usage = None;
- // Detached work has its own terminal boundary; its typed refusal must
- // never be mistaken for the interactive parent's failure.
- child.session_sidecar = Arc::new(Mutex::new(SessionTurnSidecar::default()));
- child.cancellation = tinyagents_harness::cancel::CancellationToken::new();
- child
- }
-
- /// Converts this host context into TinyAgents' canonical run context.
- ///
- /// The canonical context receives the exact same cancellation and direct
- /// `tinytools::WorkspaceDescriptor`; no type alias, re-export or task-local
- /// bridge is involved.
- pub fn into_tinyagents(
- mut self,
- mut config: tinyagents_harness::context::RunConfig,
- ) -> tinyagents_harness::context::RunContext<Self> {
- // Imported transport facts and explicit child context must survive entry
- // into the native driver, which scopes the depth recorded in RunConfig.
- let depth = config
- .depth()
- .max(self.spawn_depth)
- .max(tinyagents_harness::context::current_run_depth().map_or(0, |facts| facts.depth));
- self.spawn_depth = depth;
- config = config.with_depth(depth);
- if config.thread_id.is_none() {
- if let Some(thread_id) = self.thread_id.as_deref() {
- config = config.with_thread(thread_id);
- }
- }
- let cancellation = self.cancellation.clone();
- let workspace = self.workspace.clone();
- let run_ext = OpenHumanRunExt::from_run_context(&self);
- let host_operations = Arc::new(HostOperationContext {
- origin: self.origin.clone(),
- approval: self.approval.clone(),
- sandbox_mode: self.sandbox_mode,
- parent_agent_id: self
- .parent
- .as_ref()
- .map(|parent| parent.agent_definition_id.clone()),
- memory_identity: self.memory_identity.clone(),
- memory_turn: self.memory_turn.clone(),
- core: self.core.clone(),
- });
- let context = tinyagents_harness::context::RunContext::new(config, self)
- .with_cancellation(cancellation)
- .with_state_view(host_operations)
- .with_host(run_ext);
- match workspace {
- Some(workspace) => context.with_workspace(workspace),
- None => context,
- }
- }
-
- /// Records a child usage entry without relying on a task-local collector.
- pub fn append_subagent_usage(&self, entry: SubagentUsageEntry) {
- self.subagent_usage
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .push(entry);
- }
-
- /// Record a completed child on the immediate parent's ledger. This makes
- /// completed children visible at the root without leaking siblings into one
- /// another's in-flight ledger. Direct/root callers retain their own entry.
- pub fn record_completed_subagent_usage(&self, entry: SubagentUsageEntry) {
- let ledger = self
- .parent_subagent_usage
- .as_ref()
- .unwrap_or(&self.subagent_usage);
- ledger
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .push(entry);
- }
-
- /// Snapshot child totals after the child has returned. A snapshot, rather
- /// than a task-local drain, preserves totals even when sibling futures are
- /// cancelled or one child fails after another has completed.
- pub fn subagent_usage_entries(&self) -> Vec<SubagentUsageEntry> {
- self.subagent_usage
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .clone()
- }
-
- /// Promote already-completed descendants when this run cannot produce its
- /// own terminal outcome. This is intentionally a snapshot: callers invoke
- /// it only from one terminal finalizer, so every completed descendant is
- /// promoted once without exposing a shared, in-flight sibling ledger.
- pub fn promote_completed_descendant_usage(&self) {
- for entry in self.subagent_usage_entries() {
- self.record_completed_subagent_usage(entry);
- }
- }
-
- /// Resolves whether a file-state scope has been assigned to this context.
- /// Keeping the conversion here makes file-state callers use the explicit
- /// context instead of discovering an ambient identifier.
- pub fn file_state_agent_id(&self) -> Option<String> {
- self.file_state_agent_id.clone()
- }
-}
+#[path = "run_context/behavior.rs"]
+mod behavior;
#[cfg(test)]
#[path = "run_context_tests.rs"]
diff --cc crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs
index ac81233928,0000000000..b7fda02670
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context/behavior.rs
@@@ -1,351 -1,0 +1,353 @@@
+use super::*;
+
+impl Default for OpenHumanRunContext {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl OpenHumanRunContext {
+ /// Builds an unbound context. Entry points set only the values their turn
+ /// actually owns; `None` is an explicit absence, not an ambient fallback.
+ pub fn new() -> Self {
+ Self {
+ model_budget: None,
+ dispatch_admission: None,
+ response_shape: None,
+ max_spawn_depth: None,
+ origin: None,
+ approval: Default::default(),
+ progress: None,
+ stop_hooks: Vec::new(),
+ goal_suppressed: false,
+ tool_hooks: Vec::new(),
+ tool_call_limit: None,
+ untrusted_input_turn: false,
+ turn_deadline: None,
+ parent: None,
+ prepared_context_sources: Arc::new(Vec::new()),
+ memory_identity: None,
+ core: None,
+ hosted_base: None,
+ transcripts: None,
+ file_state_agent_id: None,
+ tool_result_artifact_index: None,
+ headless_descendant_settlement: false,
+ headless_descendant_owner: None,
+ attachment_placeholders: Arc::new(Vec::new()),
+ dispatch: None,
+ task_recency_window: None,
+ command_environment: None,
+ autonomous_iter_cap: None,
+ sandbox_mode: None,
+ spawn_depth: 0,
+ subagent_usage: Arc::new(Mutex::new(Vec::new())),
+ parent_subagent_usage: None,
+ resolved_route: Arc::new(Mutex::new(None)),
+ cancellation: tinyagents_harness::cancel::CancellationToken::default(),
+ thread_id: None,
+ root_run_id: None,
+ workspace: None,
+ tool_outcomes: None,
+ tool_policy: None,
+ current_tools: None,
+ current_synthesized_tools: None,
+ recorded_tool_names: Arc::new(std::collections::HashSet::new()),
+ deferred_tool_names: Arc::new(std::collections::HashSet::new()),
+ tool_rules: None,
+ context_middleware: None,
+ session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())),
+ required_output: None,
+ tool_dialect: tinyagents_harness::config::ToolDispatcher::Auto,
+ memory_turn: None,
++ shell_processes: crate::sandbox::shell_processes::ShellProcesses::new(),
+ }
+ }
+
+ /// Returns the registry owner for a spawn. Headless turns retain one
+ /// root-scoped owner across native child thread identities so settlement
+ /// can see the complete descendant tree. Ordinary chat remains scoped to
+ /// the immediate parent session and thread.
+ pub(crate) fn subagent_owner_scope(
+ &self,
+ workspace: &std::path::Path,
+ parent_session: &str,
+ thread_id: Option<&str>,
+ ) -> String {
+ if self.headless_descendant_settlement {
+ if let Some(owner) = &self.headless_descendant_owner {
+ return owner.clone();
+ }
+ }
+ crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ workspace,
+ parent_session,
+ thread_id,
+ )
+ }
+
+ /// Pins the harness tool dialect to the one the session prompt speaks.
+ #[must_use]
+ pub(crate) fn with_tool_dialect(
+ mut self,
+ dialect: tinyagents_harness::config::ToolDispatcher,
+ ) -> Self {
+ self.tool_dialect = dialect;
+ self
+ }
+
+ /// Binds the context this run acts under, held weakly so a run kept past its turn never pins the tenant.
+ #[must_use]
+ pub fn with_core(mut self, core: Option<Arc<crate::core::runtime::CoreContext>>) -> Self {
+ self.core = core.as_ref().map(Arc::downgrade);
+ self
+ }
+
+ /// The dispatch context this run's readers use: its own `core`, else the
+ /// calling task's (a run assembled by a caller that did not bind one).
+ pub fn dispatch_ctx(&self) -> crate::core::runtime::DispatchCtx {
+ crate::core::runtime::DispatchCtx::from_weak(self.core.as_ref())
+ }
+
+ /// The connected-identities prompt section, loaded asynchronously under this run's context.
+ pub(crate) async fn connected_identities_md(&self) -> String {
+ crate::integrations::render_connected_identities_async(&self.dispatch_ctx()).await
+ }
+
+ /// Sets the direct TinyTools workspace descriptor for this run.
+ pub fn with_workspace(mut self, workspace: tinytools::WorkspaceDescriptor) -> Self {
+ self.workspace = Some(workspace);
+ self
+ }
+
+ /// Creates (once) this host turn's durable-unique root config.
+ ///
+ /// The returned root id is stable across the session/runtime and hosted
+ /// harness boundaries for this one actual turn. Callers creating a new
+ /// root must call this once rather than construct a config from a repeated
+ /// literal; callers creating children must use [`direct_subagent_child`].
+ pub(crate) fn root_run_config(&mut self, kind: &str) -> tinyagents_harness::context::RunConfig {
+ let run_id = self
+ .root_run_id
+ .get_or_insert_with(|| fresh_root_run_config(kind).run_id.as_str().to_owned())
+ .clone();
+ tinyagents_harness::context::RunConfig::new(run_id)
+ }
+
+ /// Binds a direct runner to its explicit parent without exposing the
+ /// child-ledger link reserved for recursive [`Self::child`] calls.
+ pub(crate) fn with_parent(mut self, parent: ParentExecutionContext) -> Self {
+ self.parent = Some(parent);
+ self
+ }
+
+ /// Installs this turn's parent snapshot, binding the run's live progress
+ /// sink to it.
+ ///
+ /// The snapshot is built from a prelude that captured `on_progress` when
+ /// the runtime session was first created. A web-chat turn checks out a
+ /// cached session — so that build is a no-op — and only afterwards calls
+ /// `set_on_progress`, leaving the prelude's copy `None` for the rest of the
+ /// session's life. Sub-agent spawn and completion are the only progress
+ /// events that ride this parent sink instead of the harness event
+ /// projection, so a stale `None` drops them outright: no `subagent_spawned`
+ /// socket event, no run-ledger row, and a "Background tasks" panel that
+ /// reads "none running" while sub-agents are working. The run context's own
+ /// sink is the live one (it is what `driver.rs` hands the turn graph), so
+ /// prefer it and keep the snapshot as the fallback.
+ ///
+ /// Returns the installed parent so a caller that must launch a sub-agent
+ /// *before* the rest of the turn is assembled — `inject_triggered_memory_agent_context`
+ /// is the one such caller — hands it the bound context rather than the
+ /// stale snapshot it started from.
+ pub(crate) fn attach_parent(
+ &mut self,
+ mut parent: ParentExecutionContext,
+ ) -> &ParentExecutionContext {
+ parent.on_progress = self.progress.clone().or(parent.on_progress);
+ self.parent.insert(parent)
+ }
+
+ /// The callbacks and caps this turn's harness assembly installs.
+ pub(crate) fn harness_host_policy(&self) -> HarnessHostPolicy {
+ HarnessHostPolicy {
+ stop_hooks: self.stop_hooks.clone(),
+ tool_hooks: self.tool_hooks.clone(),
+ tool_call_cap: self.tool_call_limit,
+ }
+ }
+
+ /// The real tool invocation budget for a turn of `max_iterations`: the
+ /// product default, narrowed by the host's explicit cap.
+ pub(crate) fn tool_call_limit_for(&self, max_iterations: usize) -> usize {
+ crate::agent::tinyagents::turn_policy::tool_call_limit(max_iterations, self.tool_call_limit)
+ }
+
+ /// Applies the host environment an entry point handed to the session:
+ /// shared budget, delegation depth, cancellation, deadline and hooks.
+ #[must_use]
+ pub(crate) fn with_host_env(mut self, env: &crate::agent::turn_env::HostTurnEnv) -> Self {
+ self.model_budget = env.model_budget.clone().or(self.model_budget);
+ self.dispatch_admission = env.dispatch_admission.clone().or(self.dispatch_admission);
+ self.max_spawn_depth = env.spawn_depth_limit.or(self.max_spawn_depth);
+ if let Some(cancellation) = &env.cancellation {
+ self.cancellation = cancellation.clone();
+ }
+ self.turn_deadline = env.turn_deadline.or(self.turn_deadline);
+ self.tool_call_limit = env.tool_call_limit.or(self.tool_call_limit);
+ self.command_environment = env.command_environment.clone().or(self.command_environment);
+ self.memory_identity = env.memory_identity.clone().or(self.memory_identity);
+ self.core = env.core.clone().or(self.core);
+ self.stop_hooks
+ .extend(env.hooks.stop_hooks().iter().cloned());
+ self.tool_hooks
+ .extend(env.hooks.tool_hooks().iter().cloned());
+ self
+ }
+
+ /// Sets the same cancellation token on this context and its TinyAgents run.
+ pub fn with_cancellation(
+ mut self,
+ cancellation: tinyagents_harness::cancel::CancellationToken,
+ ) -> Self {
+ self.cancellation = cancellation;
+ self
+ }
+
+ /// Builds a child context that inherits authority, cancellation and shared
+ /// workspace policy while keeping route observation and usage isolated.
+ pub fn child(&self) -> Self {
+ let mut child = self.clone();
+ child.spawn_depth = self.spawn_depth.saturating_add(1);
+ child.file_state_agent_id = None;
+ child.parent_subagent_usage = Some(self.subagent_usage.clone());
+ child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
+ child.resolved_route = Arc::new(Mutex::new(None));
+ child.memory_turn = None;
+ child.response_shape = None;
++ child.shell_processes = crate::sandbox::shell_processes::ShellProcesses::new();
+ child
+ }
+
+ /// Builds the explicit carrier for detached background work.
+ ///
+ /// A detached task keeps the authority, thread and workspace descriptor it
+ /// needs to execute and deliver its own result, but it is no longer part of
+ /// the originating turn's dispatch timer or subagent usage roll-up. It
+ /// still inherits the shared monetary budget and physical-dispatch policy,
+ /// and it does not observe cancellation that only stopped the interactive
+ /// turn.
+ pub fn detached_child(&self) -> Self {
+ let mut child = self.child();
+ // The chat surface belongs to the turn that started it. A detached
+ // child's parks route through the origin and are marked detached, so
+ // their cards survive the parent turn's end (#5499).
+ child.approval = Default::default();
+ child.dispatch = None;
+ child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
+ child.parent_subagent_usage = None;
+ // Detached work has its own terminal boundary; its typed refusal must
+ // never be mistaken for the interactive parent's failure.
+ child.session_sidecar = Arc::new(Mutex::new(SessionTurnSidecar::default()));
+ child.cancellation = tinyagents_harness::cancel::CancellationToken::new();
+ child.headless_descendant_settlement = false;
+ child.headless_descendant_owner = None;
+ child
+ }
+
+ /// Converts this host context into TinyAgents' canonical run context.
+ ///
+ /// The canonical context receives the exact same cancellation and direct
+ /// `tinytools::WorkspaceDescriptor`; no type alias, re-export or task-local
+ /// bridge is involved.
+ pub fn into_tinyagents(
+ mut self,
+ mut config: tinyagents_harness::context::RunConfig,
+ ) -> tinyagents_harness::context::RunContext<Self> {
+ // Imported transport facts and explicit child context must survive entry
+ // into the native driver, which scopes the depth recorded in RunConfig.
+ let depth = config
+ .depth()
+ .max(self.spawn_depth)
+ .max(tinyagents_harness::context::current_run_depth().map_or(0, |facts| facts.depth));
+ self.spawn_depth = depth;
+ config = config.with_depth(depth);
+ if config.thread_id.is_none() {
+ if let Some(thread_id) = self.thread_id.as_deref() {
+ config = config.with_thread(thread_id);
+ }
+ }
+ let cancellation = self.cancellation.clone();
+ let workspace = self.workspace.clone();
+ let run_ext = OpenHumanRunExt::from_run_context(&self);
+ let host_operations = Arc::new(HostOperationContext {
+ origin: self.origin.clone(),
+ approval: self.approval.clone(),
+ sandbox_mode: self.sandbox_mode,
+ parent_agent_id: self
+ .parent
+ .as_ref()
+ .map(|parent| parent.agent_definition_id.clone()),
+ memory_identity: self.memory_identity.clone(),
+ memory_turn: self.memory_turn.clone(),
+ core: self.core.clone(),
+ });
+ let context = tinyagents_harness::context::RunContext::new(config, self)
+ .with_cancellation(cancellation)
+ .with_state_view(host_operations)
+ .with_host(run_ext);
+ match workspace {
+ Some(workspace) => context.with_workspace(workspace),
+ None => context,
+ }
+ }
+
+ /// Records a child usage entry without relying on a task-local collector.
+ pub fn append_subagent_usage(&self, entry: SubagentUsageEntry) {
+ self.subagent_usage
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .push(entry);
+ }
+
+ /// Record a completed child on the immediate parent's ledger. This makes
+ /// completed children visible at the root without leaking siblings into one
+ /// another's in-flight ledger. Direct/root callers retain their own entry.
+ pub fn record_completed_subagent_usage(&self, entry: SubagentUsageEntry) {
+ let ledger = self
+ .parent_subagent_usage
+ .as_ref()
+ .unwrap_or(&self.subagent_usage);
+ ledger
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .push(entry);
+ }
+
+ /// Snapshot child totals after the child has returned. A snapshot, rather
+ /// than a task-local drain, preserves totals even when sibling futures are
+ /// cancelled or one child fails after another has completed.
+ pub fn subagent_usage_entries(&self) -> Vec<SubagentUsageEntry> {
+ self.subagent_usage
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .clone()
+ }
+
+ /// Promote already-completed descendants when this run cannot produce its
+ /// own terminal outcome. This is intentionally a snapshot: callers invoke
+ /// it only from one terminal finalizer, so every completed descendant is
+ /// promoted once without exposing a shared, in-flight sibling ledger.
+ pub fn promote_completed_descendant_usage(&self) {
+ for entry in self.subagent_usage_entries() {
+ self.record_completed_subagent_usage(entry);
+ }
+ }
+
+ /// Resolves whether a file-state scope has been assigned to this context.
+ /// Keeping the conversion here makes file-state callers use the explicit
+ /// context instead of discovering an ambient identifier.
+ pub fn file_state_agent_id(&self) -> Option<String> {
+ self.file_state_agent_id.clone()
+ }
+}
diff --cc crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
index 3c2bbfd1e9,0000000000..94fcfaf22a
mode 100644,000000..100644
--- a/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_headless_descendants_tests.rs
@@@ -1,519 -1,0 +1,519 @@@
+use super::*;
+use async_trait::async_trait;
+use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
+
+const CHILD_PROMPT: &str = "headless-cron-child-result-marker";
+
+struct ChildInvocationDrop(std::sync::Arc<std::sync::atomic::AtomicBool>);
+
+impl Drop for ChildInvocationDrop {
+ fn drop(&mut self) {
+ self.0.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+}
+
+struct CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize,
+ child_calls: std::sync::atomic::AtomicUsize,
+ child_invocation_dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ accepted_followups: std::sync::atomic::AtomicUsize,
+ accepted_followup: tokio::sync::Notify,
+ child_attempts_dangerous_tool: bool,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool,
+ child_started: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
+ child_release: tokio::sync::Notify,
+}
+
+#[cfg(feature = "storage-sqlite")]
+fn scheduled_agent_fixture(
+ timeout_secs: u64,
+) -> (
+ TempDir,
+ crate::storage::test_support::SqliteBackend,
+ crate::storage::test_support::InstalledBackendGuard,
+ Config,
+ std::sync::Arc<crate::core::runtime::CoreContext>,
+ crate::core::runtime::DispatchCtx,
+ tinyflows_bus::schedule::types::CronJob,
+) {
+ let temp = TempDir::new().expect("cron workspace");
+ let mut config = Config::default();
+ config.workspace_dir = temp.path().join("workspace");
+ config.action_dir = config.workspace_dir.clone();
+ let storage = crate::storage::test_support::sqlite_backend().expect("SQLite test backend");
+ config.storage.url = Some(storage.url.clone());
+ let storage_guard =
+ crate::storage::test_support::install_for_test(&storage.url, Arc::clone(&storage.backend));
+ config.default_model = Some("test-model".into());
+ config.chat_provider = Some("omlx:test-model".into());
+ config.agent.agent_timeout_secs = timeout_secs;
+ config.reliability.scheduler_retries = 0;
+ std::fs::create_dir_all(&config.workspace_dir).expect("workspace");
+
+ let definitions =
+ Arc::new(crate::agent_registry::host_definition::AgentDefinitionRegistry::builtins_only());
+ let core = crate::core::runtime::CoreContext::for_test_with_config(
+ crate::core::runtime::DomainSet::full(),
+ config.clone(),
+ )
+ .derive_with(
+ crate::core::runtime::ContextOverlay::new(
+ config.clone(),
+ crate::core::runtime::DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .definitions(definitions),
+ );
+ let dispatch = crate::core::runtime::DispatchCtx::new(std::sync::Arc::clone(&core));
+ let mut spec = tinyflows_bus::schedule::AgentJobSpec::new(
+ tinyflows_bus::schedule::types::Schedule::Every {
+ every_ms: 3_600_000,
+ },
+ "Delegate this scheduled task to its worker.",
+ );
+ spec.name = Some("headless child test".into());
+ spec.session_target = SessionTarget::Isolated;
+ spec.model = Some("test-model".into());
+ spec.enabled = true;
+ let job =
+ crate::cron::add_agent_job_from_spec(&config, spec).expect("persist scheduled agent job");
+ crate::cron::store::force_next_run_for_test(
+ &config,
+ &job.id,
+ chrono::Utc::now() - chrono::Duration::seconds(1),
+ )
+ .expect("make the job due");
+ (temp, storage, storage_guard, config, core, dispatch, job)
+}
+
+async fn dispatch_scheduled_agent(
+ core: std::sync::Arc<crate::core::runtime::CoreContext>,
+ dispatch: crate::core::runtime::DispatchCtx,
+ config: Config,
+) {
+ let security = Arc::new(SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let mut dispatcher = JobDispatcher::new(&dispatch, &config, &security);
+ crate::core::runtime::CoreContext::scope(
+ core,
+ Box::pin(async move {
+ let dispatched = dispatcher.tick(&config).await.expect("scheduler tick");
+ assert_eq!(dispatched, 1, "the persisted due job is dispatched");
+ dispatcher.drain().await;
+ }),
+ )
+ .await;
+}
+
+#[async_trait]
+impl ChatModel<()> for CronChildModel {
+ fn profile(&self) -> Option<&ModelProfile> {
+ static PROFILE: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();
+ Some(PROFILE.get_or_init(|| ModelProfile {
+ tool_calling: true,
+ parallel_tool_calls: true,
+ ..ModelProfile::default()
+ }))
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ request: ModelRequest,
+ ) -> tinyinference_llm::Result<ModelResponse> {
+ if request.messages.iter().any(|message| {
+ matches!(message, tinyinference_llm::message::Message::User(_))
+ && message.text().contains(CHILD_PROMPT)
+ }) {
+ let call = self
+ .child_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if let Some(started) = self.child_started.lock().unwrap().take() {
+ let _ = started.send(());
+ }
+ if self.child_attempts_dangerous_tool {
+ if call > 0 {
+ return Ok(ModelResponse::assistant(
+ "headless-cron-child-returned-after-policy-denial",
+ ));
+ }
+ self.child_dangerous_tool_schema_seen.store(
+ request
+ .tools
+ .iter()
+ .any(|tool| tool.name == "delete_artifact"),
+ std::sync::atomic::Ordering::SeqCst,
+ );
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-cron-forbidden-write",
+ "delete_artifact",
+ serde_json::json!({"artifact_id": "missing-headless-cron-artifact"}),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ return Ok(response);
+ }
+ if let Some(started) = self.child_started.lock().unwrap().take() {
+ let _ = started.send(());
+ }
+ let _drop = ChildInvocationDrop(std::sync::Arc::clone(&self.child_invocation_dropped));
+ self.child_release.notified().await;
+ return Ok(ModelResponse::assistant("headless-cron-child-result"));
+ }
+
+ if request.messages.iter().any(|message| {
+ matches!(message, tinyinference_llm::message::Message::Tool(_))
+ && message
+ .text()
+ .contains("Accepted async sub-agent `task_manager_agent`")
+ }) {
+ self.accepted_followups
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ self.accepted_followup.notify_one();
+ return Ok(ModelResponse::assistant("headless-cron-root-result"));
+ }
+
+ if self
+ .spawn_calls
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
+ > 0
+ {
+ return Ok(ModelResponse::assistant("headless-cron-root-result"));
+ }
+ let mut response = ModelResponse::assistant("");
+ response.message.tool_calls = vec![tinyinference_llm::tool::ToolCall::new(
+ "headless-cron-spawn",
+ "spawn_subagent",
+ serde_json::json!({
+ "agent_id": "task_manager_agent",
+ "prompt": CHILD_PROMPT,
+ "task_key": "headless-cron-child-task",
+ "context": "headless cron regression",
+ "model": "test-model"
+ }),
+ )];
+ response.finish_reason = Some("tool_calls".into());
+ Ok(response)
+ }
+}
+
+#[tokio::test]
+#[cfg(feature = "storage-sqlite")]
+async fn scheduled_agent_history_includes_its_spawned_child_result() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ accepted_followup: tokio::sync::Notify::new(),
+ child_attempts_dangerous_tool: false,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, _storage, _storage_guard, config, core, dispatch, job) =
+ scheduled_agent_fixture(900);
+
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
+ // These deadlines are watchdogs, not timing assertions. Give loaded CI
+ // workers enough room to start the isolated scheduler task.
+ match tokio::time::timeout(std::time::Duration::from_secs(30), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("child-start observation disconnected: {error}"),
+ Err(_) => {
+ model.child_release.notify_one();
+ let result = tokio::time::timeout(std::time::Duration::from_secs(30), run).await;
+ eprintln!(
+ "scheduled child start timeout diagnostics: spawn calls {}, followups {}, run result {result:?}",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.accepted_followups.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ panic!(
+ "scheduled child never reached its model (spawn calls: {}, followups: {}); run result: {result:?}",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.accepted_followups.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ }
+ }
+ model.child_release.notify_one();
+
+ run.await.expect("cron scheduler task");
+ let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
+ assert_eq!(runs.len(), 1, "scheduler persisted one completed run");
+ assert_eq!(runs[0].status, "ok", "agent job completed successfully");
+ assert!(
+ runs[0]
+ .output
+ .as_deref()
+ .unwrap_or_default()
+ .contains("headless-cron-child-result"),
+ "the persisted cron result must include its spawned child output: {}",
+ runs[0].output.as_deref().unwrap_or_default()
+ );
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model
+ .accepted_followups
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the parent accepted the real spawn result before the child completed"
+ );
+}
+
+#[tokio::test]
+#[cfg(feature = "storage-sqlite")]
+async fn scheduled_agent_timeout_cancels_its_blocked_child_before_history_settles() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ accepted_followup: tokio::sync::Notify::new(),
+ child_attempts_dangerous_tool: false,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, _storage, _storage_guard, config, core, dispatch, job) = scheduled_agent_fixture(5);
+ let inspect_dispatch = dispatch.clone();
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
+
+ match tokio::time::timeout(std::time::Duration::from_secs(30), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("scheduled child exited before its model blocked: {error}"),
+ Err(_) => {
+ model.child_release.notify_one();
+ let _ = tokio::time::timeout(std::time::Duration::from_secs(30), run).await;
+ panic!(
+ "scheduled child never reached its blocking model (spawns: {}, accepted followups: {})",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.accepted_followups.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ }
+ }
+
+ tokio::time::timeout(
+ std::time::Duration::from_secs(4),
+ model.accepted_followup.notified(),
+ )
+ .await
+ .expect("the root acknowledges the spawned child before its deadline");
+
+ tokio::time::timeout(std::time::Duration::from_secs(6), run)
+ .await
+ .expect("cron timeout should settle the blocked run")
+ .expect("cron scheduler task");
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &config.workspace_dir,
+ &format!("cron:{}", job.id),
+ None,
+ );
+ let registry = crate::core::runtime::slot_for::<
+ tinyagents_orchestration::subagent::SubAgentJobRegistry,
+ >(&inspect_dispatch);
+ let jobs = registry
+ .try_list_owned(owner.as_str())
+ .expect("inspect this Cron run's native descendants");
+ assert_eq!(jobs.len(), 1, "one native child belongs to this Cron job");
+ assert_eq!(
+ jobs[0].status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Cancelled,
+ "the descendant is terminal when the scheduled run drains"
+ );
+ let child = tokio::time::timeout(
+ std::time::Duration::from_secs(2),
+ registry.wait_owned(jobs[0].id.as_str(), owner),
+ )
+ .await
+ .expect("root timeout cancellation reaches its child")
+ .expect("the child remains available until its terminal state");
+ assert_eq!(
+ child.status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Cancelled,
+ "the bounded registry wait confirms terminal cancellation"
+ );
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model
+ .accepted_followups
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the root accepted the child before waiting on it"
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert!(
+ model
+ .child_invocation_dropped
+ .load(std::sync::atomic::Ordering::SeqCst),
+ "the root deadline dropped the child model future"
+ );
+
+ let runs = crate::cron::list_runs(&config, &job.id, 10).expect("read persisted run history");
+ assert_eq!(runs.len(), 1, "scheduler persisted one completed attempt");
+ assert_ne!(runs[0].status, "ok", "the configured deadline expired");
+ assert!(!runs[0]
+ .output
+ .as_deref()
+ .unwrap_or_default()
+ .contains("headless-cron-child-result"));
+ assert_eq!(
+ child.status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Cancelled,
+ "the root deadline cancels the blocked native child"
+ );
+}
+
+#[tokio::test]
+#[cfg(feature = "storage-sqlite")]
+async fn scheduled_cron_child_cannot_run_its_declared_destructive_tool() {
+ let _inference = crate::inference::inference_test_guard_async().await;
+ let model = std::sync::Arc::new(CronChildModel {
+ spawn_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_calls: std::sync::atomic::AtomicUsize::new(0),
+ child_invocation_dropped: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
+ accepted_followups: std::sync::atomic::AtomicUsize::new(0),
+ accepted_followup: tokio::sync::Notify::new(),
+ child_attempts_dangerous_tool: true,
+ child_dangerous_tool_schema_seen: std::sync::atomic::AtomicBool::new(false),
+ child_started: std::sync::Mutex::new(None),
+ child_release: tokio::sync::Notify::new(),
+ });
+ let _model =
+ crate::inference::provider::factory::test_provider_override::install_model(model.clone());
+ let (_temp, _storage, _storage_guard, config, core, dispatch, job) =
+ scheduled_agent_fixture(900);
+ let inspect_dispatch = dispatch.clone();
+ let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
+ *model.child_started.lock().unwrap() = Some(child_started_tx);
+ let scheduler_config = config.clone();
+ let run =
+ tokio::spawn(
+ async move { dispatch_scheduled_agent(core, dispatch, scheduler_config).await },
+ );
- match tokio::time::timeout(std::time::Duration::from_secs(30), child_started_rx).await {
++ match tokio::time::timeout(std::time::Duration::from_secs(60), child_started_rx).await {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) => panic!("scheduled child exited before its model call: {error}"),
+ Err(_) => {
+ let result = tokio::time::timeout(std::time::Duration::from_secs(30), run).await;
+ let runs = crate::cron::list_runs(&config, &job.id, 10);
+ let events = match &runs {
+ Ok(runs) => match runs.first().and_then(|run| run.run_id.as_deref()) {
+ Some(run_id) => crate::agent::tinyagents::journal::read_run_events(
+ &inspect_dispatch,
+ run_id,
+ 0,
+ )
+ .await
+ .map(|events| {
+ events
+ .into_iter()
+ .map(|event| event.event)
+ .collect::<Vec<_>>()
+ }),
+ None => Ok(Vec::new()),
+ },
+ Err(error) => Err(anyhow::anyhow!("{error}")),
+ };
+ eprintln!(
+ "scheduled child never reached its model (spawn calls: {}, child calls: {}, result: {result:?}, runs: {runs:?}, events: {events:?})",
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ );
+ panic!("scheduled child never reached its model");
+ }
+ }
+ tokio::time::timeout(std::time::Duration::from_secs(30), run)
+ .await
+ .expect("Cron should settle the denied child result")
+ .expect("Cron scheduler task");
+
+ assert_eq!(
+ model.spawn_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1
+ );
+ assert_eq!(
+ model.child_calls.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the child model requested the declared destructive tool"
+ );
+ assert!(
+ model
+ .child_dangerous_tool_schema_seen
+ .load(std::sync::atomic::Ordering::SeqCst),
+ "the real child model request exposed the declared destructive tool"
+ );
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &config.workspace_dir,
+ &format!("cron:{}", job.id),
+ None,
+ );
+ let jobs = crate::core::runtime::slot_for::<
+ tinyagents_orchestration::subagent::SubAgentJobRegistry,
+ >(&inspect_dispatch)
+ .try_list_owned(owner)
+ .expect("inspect the exact Cron session owner");
+ assert_eq!(jobs.len(), 1, "one native child belongs to this Cron job");
+ assert_eq!(
+ jobs[0].status,
+ tinyagents_orchestration::subagent::SubAgentJobStatus::Incomplete,
+ "the child records the policy-blocked action as an incomplete run"
+ );
+ let child_run_id = jobs[0]
+ .subagent_run_id
+ .as_deref()
+ .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, "error");
+}
diff --cc crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
index aa324f3533,eb575e624b..581d75a6bb
--- a/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
+++ b/crates/openhuman-core/src/sandbox/shell_exec_fixture.rs
@@@ -112,7 -133,99 +133,99 @@@ pub(crate) async fn run(run: NativeShel
stdout: String::from_utf8_lossy(&stdout).into_owned(),
stderr: String::from_utf8_lossy(&stderr).into_owned(),
timed_out,
- })
+ }))
+ }
+
+ /// A fixture command past its yield point, read and stopped like the module's.
+ pub(crate) struct FixtureLive {
+ child: tokio::process::Child,
+ pid: Option<u32>,
+ stdout_pipe: Option<tokio::process::ChildStdout>,
+ stderr_pipe: Option<tokio::process::ChildStderr>,
+ /// Output read since the previous [`LiveRead`].
+ stdout: Vec<u8>,
+ stderr: Vec<u8>,
+ deadline: tokio::time::Instant,
+ ended: bool,
+ }
+
+ impl FixtureLive {
+ pub(crate) async fn read(&mut self, wait: Duration) -> anyhow::Result<LiveRead> {
+ if self.ended {
+ return Ok(self.take(LiveState::Stopped));
+ }
+ let until = (tokio::time::Instant::now() + wait).min(self.deadline);
+ let finished = tokio::time::timeout_at(until, async {
+ let (status, (), ()) = tokio::join!(
+ self.child.wait(),
+ drain(&mut self.stdout_pipe, &mut self.stdout),
+ drain(&mut self.stderr_pipe, &mut self.stderr),
+ );
+ status
+ })
+ .await;
+ let state = match finished {
+ Ok(status) => {
+ // Ended only once the wait itself succeeded.
+ let code = status?.code().unwrap_or(-1);
+ self.ended = true;
+ LiveState::Exited(code)
+ }
+ Err(_) if tokio::time::Instant::now() >= self.deadline => {
+ self.stop().await;
+ LiveState::TimedOut
+ }
+ Err(_) => LiveState::Running,
+ };
+ Ok(self.take(state))
+ }
+
+ pub(crate) fn finished(&self) -> bool {
+ self.ended
+ }
+
+ pub(crate) async fn kill(&mut self) -> anyhow::Result<LiveRead> {
+ if !self.ended {
+ self.stop().await;
+ }
+ Ok(self.take(LiveState::Stopped))
+ }
+
+ /// Stop the command and everything it started, keeping what is left in
+ /// the pipes.
+ async fn stop(&mut self) {
+ if let Some(pid) = self.pid {
- tinytools_std::timeout::kill_process_group(pid);
++ tinyagents_harness_tools::exec::timeout::kill_process_group(pid);
+ }
+ let _ = self.child.start_kill();
+ let _ = tokio::time::timeout(Duration::from_secs(2), async {
+ tokio::join!(
+ drain(&mut self.stdout_pipe, &mut self.stdout),
+ drain(&mut self.stderr_pipe, &mut self.stderr),
+ )
+ })
+ .await;
+ self.ended = true;
+ }
+
+ fn take(&mut self, state: LiveState) -> LiveRead {
+ LiveRead {
+ stdout: String::from_utf8_lossy(&std::mem::take(&mut self.stdout)).into_owned(),
+ stderr: String::from_utf8_lossy(&std::mem::take(&mut self.stderr)).into_owned(),
+ state,
+ }
+ }
+ }
+
+ impl Drop for FixtureLive {
+ fn drop(&mut self) {
+ if !self.ended {
+ if let Some(pid) = self.pid {
- tinytools_std::timeout::kill_process_group(pid);
++ tinyagents_harness_tools::exec::timeout::kill_process_group(pid);
+ }
+ let _ = self.child.start_kill();
+ }
+ }
}
/// Appends what `pipe` delivers to `into` until it closes. Reads are
diff --cc crates/openhuman-core/src/storage/sessions/host_stores.rs
index 75b54433ac,81e14bb3a5..e5209e4046
--- a/crates/openhuman-core/src/storage/sessions/host_stores.rs
+++ b/crates/openhuman-core/src/storage/sessions/host_stores.rs
@@@ -486,13 -409,6 +486,10 @@@ impl SessionStoreProvider for Workspace
Self::current().run_ledger_for_agent(agent_id)
}
- fn lease_for_agent(
- &self,
- agent_id: &str,
- ) -> Result<SessionStoreLease, SessionStoreLeaseError> {
++ fn lease_for_agent(&self, agent_id: &str) -> Result<SessionStoreLease, SessionStoreLeaseError> {
+ Self::current().lease_for_agent(agent_id)
+ }
+
fn conversations_for_agent(
&self,
agent_id: &str,
diff --cc crates/openhuman-core/src/storage/sessions/rebound.rs
index 162b83452c,1b0646cfa8..ebedd9083d
--- a/crates/openhuman-core/src/storage/sessions/rebound.rs
+++ b/crates/openhuman-core/src/storage/sessions/rebound.rs
@@@ -150,13 -147,6 +150,10 @@@ impl SessionStoreProvider for ReboundSe
SessionStoreProvider::try_for_agent(self.current().as_ref(), agent_id)
}
- fn lease_for_agent(
- &self,
- agent_id: &str,
- ) -> Result<SessionStoreLease, SessionStoreLeaseError> {
++ fn lease_for_agent(&self, agent_id: &str) -> Result<SessionStoreLease, SessionStoreLeaseError> {
+ self.current().lease_for_agent(agent_id)
+ }
+
fn bind_actor(
&self,
factory: AgentStorageFactory,
diff --cc crates/openhuman-core/src/storage/sessions/tenant_router.rs
index cabccfd281,da26d0b1ca..3c2a0d09cf
--- a/crates/openhuman-core/src/storage/sessions/tenant_router.rs
+++ b/crates/openhuman-core/src/storage/sessions/tenant_router.rs
@@@ -168,14 -144,6 +168,11 @@@ impl SessionStoreProvider for TenantSes
provider.try_for_agent(&agent)
}
- fn lease_for_agent(
- &self,
- agent_id: &str,
- ) -> Result<SessionStoreLease, SessionStoreLeaseError> {
++ fn lease_for_agent(&self, agent_id: &str) -> Result<SessionStoreLease, SessionStoreLeaseError> {
+ let (provider, agent) = self.route(agent_id);
+ provider.lease_for_agent(&agent)
+ }
+
fn bind_actor(
&self,
factory: AgentStorageFactory,
diff --cc crates/openhuman-core/src/tools/impl/system/exec_adapters.rs
index 349dd0a24f,0000000000..7840132cc0
mode 100644,000000..100644
--- a/crates/openhuman-core/src/tools/impl/system/exec_adapters.rs
+++ b/crates/openhuman-core/src/tools/impl/system/exec_adapters.rs
@@@ -1,392 -1,0 +1,116 @@@
+//! OpenHuman policy adapters for TinyAgents' generic execution tools.
+
- use std::{path::PathBuf, sync::Arc, time::Duration};
++use std::{path::PathBuf, sync::Arc};
+
+use async_trait::async_trait;
+use serde_json::Value;
+use tinyagents_harness_tools::exec::{
- ExecAuditEvent, ExecAuditOutcome, ExecAuthorizationRequest, ExecBackend, ExecBackendCapability,
- ExecBackendOutcome, ExecDenied, ExecGate, ExecOperation, ExecOutput, ExecPermit,
- ExecRefusalKind, ExecRequest, ExecTool, NativeExecCapability, ShellFlavor,
++ ExecAuditEvent, ExecAuditOutcome, ExecAuthorizationRequest, ExecBackendCapability, ExecDenied,
++ ExecGate, ExecOperation, ExecPermit, ExecRefusalKind, NativeExecCapability,
+};
- use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext, ToolTimeout};
++use tinytools::ToolRunContext;
+
+use crate::{
- agent::tinyagents::host::run_context::{
- approval_for_tool, command_environment_for_tool, dispatch_ctx_for_tool,
- },
- config::Config,
- core::runtime::DispatchCtx,
- modules::tinybox::host_runtime::RuntimeAdapter,
++ agent::tinyagents::host::run_context::approval_for_tool,
+ security::{AuditLogger, CommandExecutionLog, SecurityPolicy},
+};
+
- use super::shell::ShellHost;
-
+/// Host-owned gate for package installation. The generic TinyAgents tool owns
+/// argument validation and process-result formatting; OpenHuman owns whether
+/// a host install is permitted.
+pub(super) struct InstallGate {
+ pub security: Arc<SecurityPolicy>,
+ pub audit: Arc<AuditLogger>,
+ pub environment: std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>,
+}
+
+#[async_trait]
+impl ExecGate for InstallGate {
+ async fn prepare_authorization(&self, _args: &Value) -> anyhow::Result<Option<Value>> {
+ Ok(None)
+ }
+
+ fn external_effect_with_args(&self, _args: &Value) -> bool {
+ true
+ }
+
+ async fn authorize(
+ &self,
+ request: &ExecAuthorizationRequest,
+ context: Option<&dyn ToolRunContext>,
+ ) -> Result<ExecPermit, ExecDenied> {
+ let ExecOperation::Install { .. } = &request.operation else {
+ return Err(ExecDenied(
+ "install gate received a non-install operation".into(),
+ ));
+ };
+ if crate::core::runtime::is_saas() {
+ return Err(ExecDenied(
+ "[policy-denied] Package installation is unavailable in SaaS mode.".into(),
+ ));
+ }
+ if !approval_for_tool(context).is_interactive() {
+ return Err(ExecDenied(
+ "[policy-denied] install_tool requires interactive approval and is not available in autonomous (background) turns.".into(),
+ ));
+ }
+ if !self.security.allow_tool_install {
+ return Err(ExecDenied(
+ "[policy-denied] OS package installation is disabled. Enable it in the agent access settings (Full access mode / allow_tool_install) before installing tools.".into(),
+ ));
+ }
+ if !self.security.can_act() {
+ return Err(ExecDenied(
+ "[policy-blocked] Action blocked: autonomy is read-only.".into(),
+ ));
+ }
+ if self.security.is_rate_limited() {
+ return Err(ExecDenied(
+ "Rate limit exceeded: too many actions in the last hour".into(),
+ ));
+ }
+ if !self.security.record_action() {
+ return Err(ExecDenied(
+ "Rate limit exceeded: action budget exhausted".into(),
+ ));
+ }
+ Ok(ExecPermit {
+ action_dir: PathBuf::from(&self.security.workspace_dir),
+ environment: self.environment.clone(),
+ backend_selection: "native".into(),
+ backend_capability: ExecBackendCapability::new(NativeExecCapability),
+ })
+ }
+
+ fn record(&self, event: ExecAuditEvent) {
+ let (command, risk_level) = match &event.operation {
+ ExecOperation::Install { package, manager } => {
+ (format!("{manager} install {package}"), "install")
+ }
+ ExecOperation::Shell { command, category } => {
+ (command.clone(), category.as_deref().unwrap_or("unknown"))
+ }
+ };
+ let success = matches!(
+ event.outcome,
+ ExecAuditOutcome::Completed { success: true, .. }
+ );
+ if let Err(error) = self.audit.log_command_event(CommandExecutionLog {
+ channel: "tool:install_tool",
+ command: &command,
+ risk_level,
+ approved: event.approval_required,
+ allowed: event.allowed,
+ success,
+ duration_ms: u64::try_from(event.duration.as_millis()).unwrap_or(u64::MAX),
+ }) {
+ tracing::warn!(error = %error, "[install_tool] failed to persist execution audit event");
+ }
+ if let ExecAuditOutcome::BackendRefused {
+ kind: ExecRefusalKind::BackendUnavailable,
+ } = event.outcome
+ {
+ tracing::warn!("[install_tool] selected execution backend is unavailable");
+ }
+ }
+}
-
- #[derive(Debug, Clone, Copy)]
- struct HostShellCapability;
-
- /// Host-owned implementation of TinyAgents' execution ports. OpenHuman keeps
- /// its policy and runtime selection here; the upstream tool owns generic shell
- /// metadata and invocation behavior.
- struct ShellPorts {
- host: Arc<ShellHost>,
- }
-
- #[async_trait]
- impl ExecGate for ShellPorts {
- async fn prepare_authorization(&self, args: &Value) -> anyhow::Result<Option<Value>> {
- self.host.prepare_authorization(args).await
- }
-
- fn external_effect_with_args(&self, args: &Value) -> bool {
- self.host.external_effect_with_args(args)
- }
-
- async fn authorize(
- &self,
- request: &ExecAuthorizationRequest,
- context: Option<&dyn ToolRunContext>,
- ) -> Result<ExecPermit, ExecDenied> {
- let ExecOperation::Shell { command, .. } = &request.operation else {
- return Err(ExecDenied(
- "shell gate received a non-shell operation".into(),
- ));
- };
-
- // Recheck facts before issuing a permit. The backend repeats this
- // module analysis immediately before launch to close the approval race.
- #[cfg(feature = "modules")]
- {
- let Some(config) = self.host.analysis_config.as_deref() else {
- #[cfg(test)]
- self.host
- .security
- .check_gated_command(command)
- .map_err(ExecDenied)?;
- #[cfg(not(test))]
- return Err(ExecDenied("Command analysis is unavailable.".into()));
- #[cfg(test)]
- return self.permit(context);
- };
- let analysis = crate::modules::tinybox::analyze_command(config, command.clone())
- .await
- .map_err(|_| ExecDenied("Command analysis is unavailable.".into()))?;
- self.host
- .security
- .check_gated_command_analysis(&analysis)
- .map_err(ExecDenied)?;
- }
- #[cfg(not(feature = "modules"))]
- {
- #[cfg(test)]
- self.host
- .security
- .check_gated_command(command)
- .map_err(ExecDenied)?;
- #[cfg(not(test))]
- return Err(ExecDenied("Command analysis is unavailable.".into()));
- }
- self.permit(context)
- }
-
- fn record(&self, event: ExecAuditEvent) {
- let (command, risk_level) = match &event.operation {
- ExecOperation::Shell { command, .. } => (command.as_str(), "unknown"),
- ExecOperation::Install { .. } => ("<invalid shell operation>", "unknown"),
- };
- let success = matches!(
- event.outcome,
- ExecAuditOutcome::Completed { success: true, .. }
- );
- if let Err(error) = self.host.audit.log_command_event(CommandExecutionLog {
- channel: "tool:shell",
- command,
- risk_level,
- approved: event.approval_required,
- allowed: event.allowed,
- success,
- duration_ms: u64::try_from(event.duration.as_millis()).unwrap_or(u64::MAX),
- }) {
- tracing::warn!(error = %error, channel = "tool:shell", "failed to persist shell audit event");
- }
- }
- }
-
- impl ShellPorts {
- fn permit(&self, context: Option<&dyn ToolRunContext>) -> Result<ExecPermit, ExecDenied> {
- let action_dir = self.host.effective_action_dir_for_context(context);
- let environment = command_environment_for_tool(context)
- .as_deref()
- .into_iter()
- .flat_map(|environment| environment.iter())
- .map(|(name, value)| (name.into(), value.into()))
- .collect();
- Ok(ExecPermit {
- action_dir,
- environment,
- backend_selection: "openhuman-runtime".into(),
- backend_capability: ExecBackendCapability::new(HostShellCapability),
- })
- }
- }
-
- #[async_trait]
- impl ExecBackend for ShellPorts {
- fn shell_flavor(&self) -> ShellFlavor {
- match self.host.runtime.shell_flavor() {
- crate::modules::tinybox::host_runtime::ShellFlavor::Cmd => ShellFlavor::Cmd,
- _ => ShellFlavor::Posix,
- }
- }
-
- async fn execute(
- &self,
- request: ExecRequest,
- context: Option<&dyn ToolRunContext>,
- _progress: Option<tinyagents_harness_tools::exec::ExecProgress>,
- ) -> ExecBackendOutcome {
- if request.backend_selection != "openhuman-runtime"
- || request
- .backend_capability
- .downcast_ref::<HostShellCapability>()
- .is_none()
- {
- return ExecBackendOutcome::Refused {
- kind: ExecRefusalKind::Preflight,
- reason: "OpenHuman runtime was not selected or authorized".into(),
- };
- }
- let Some(command) = request.shell_command else {
- return ExecBackendOutcome::Refused {
- kind: ExecRefusalKind::Preflight,
- reason: "shell command is missing".into(),
- };
- };
- let timeout_secs = request.timeout.map(|timeout| timeout.as_secs());
- let (allowed, result) = crate::sandbox::shell_progress::with_shell_progress(
- context,
- crate::sandbox::shell_progress::HEARTBEAT_INTERVAL,
- |meter| async {
- self.host
- .run_with_security_in_context(
- &dispatch_ctx_for_tool(context),
- &command,
- timeout_secs,
- context,
- meter,
- )
- .await
- },
- )
- .await;
- if !allowed {
- return ExecBackendOutcome::Refused {
- kind: ExecRefusalKind::Preflight,
- reason: result.output(),
- };
- }
- ExecBackendOutcome::Completed(ExecOutput {
- stdout: result.output().into_bytes(),
- stderr: Vec::new(),
- exit_code: Some(if result.is_error { 1 } else { 0 }),
- timed_out: false,
- })
- }
- }
-
- /// Public OpenHuman adapter around the upstream generic `ExecTool`.
- pub struct ShellTool {
- inner: ExecTool,
- host: Arc<ShellHost>,
- }
-
- impl ShellTool {
- pub fn new(
- security: Arc<SecurityPolicy>,
- runtime: Arc<dyn RuntimeAdapter>,
- audit: Arc<AuditLogger>,
- ) -> Self {
- Self::from_host(Arc::new(ShellHost::new(security, runtime, audit)))
- }
-
- pub fn with_config(
- security: Arc<SecurityPolicy>,
- runtime: Arc<dyn RuntimeAdapter>,
- audit: Arc<AuditLogger>,
- config: Arc<Config>,
- ) -> Self {
- Self::from_host(Arc::new(ShellHost::with_config(
- security, runtime, audit, config,
- )))
- }
-
- fn from_host(host: Arc<ShellHost>) -> Self {
- let ports = Arc::new(ShellPorts {
- host: Arc::clone(&host),
- });
- let gate: Arc<dyn ExecGate> = ports.clone();
- let backend: Arc<dyn ExecBackend> = ports;
- Self {
- inner: ExecTool::new(gate, backend),
- host,
- }
- }
-
- pub(super) fn explicit_timeout(&self, requested: Option<u64>) -> Option<Duration> {
- self.host.explicit_timeout(requested)
- }
-
- /// Workflow commands share the same host execution policy.
- pub(crate) async fn run_with_security(
- &self,
- ctx: &DispatchCtx,
- command: &str,
- requested_timeout: Option<u64>,
- ) -> (bool, ToolResult) {
- self.host
- .run_with_security(ctx, command, requested_timeout)
- .await
- }
- }
-
- #[async_trait]
- impl Tool for ShellTool {
- fn name(&self) -> &str {
- "shell"
- }
- fn description(&self) -> &str {
- self.inner.description()
- }
- fn parameters_schema(&self) -> Value {
- self.inner.parameters_schema()
- }
- fn max_result_size_chars(&self) -> Option<usize> {
- self.inner.max_result_size_chars()
- }
- fn timeout_policy(&self, args: &Value) -> ToolTimeout {
- self.inner.timeout_policy(args)
- }
- fn permission_level(&self) -> PermissionLevel {
- self.inner.permission_level()
- }
- fn external_effect_with_args(&self, args: &Value) -> bool {
- self.inner.external_effect_with_args(args)
- }
- async fn prepare_authorization(&self, args: &Value) -> anyhow::Result<Option<Value>> {
- self.inner.prepare_authorization(args).await
- }
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.inner.execute(args).await
- }
- async fn execute_with_context(
- &self,
- args: Value,
- options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- self.inner
- .execute_with_context(args, options, context)
- .await
- }
- }
diff --cc crates/openhuman-core/src/tools/impl/system/mod.rs
index cb22c638e1,9a61f25611..2cf1ff1de8
--- a/crates/openhuman-core/src/tools/impl/system/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs
@@@ -1,27 -1,60 +1,61 @@@
//! Cross-cutting system tools: shell, Node/npm/Python execution, tool
- //! detection/install, time helpers, proxy config, update check/apply.
+ //! detection/install, time helpers, LSP, proxy config, update check/apply.
//! Each family, its tool structs, and its registration gates are catalogued in
- //! `tools/impl/README.md`.
+ //! `tools/impl/README.md`; `security_for_tool_context` below is the shared
+ //! `SecurityPolicy` resolver that must stay in step with the `filesystem` copy.
+mod exec_adapters;
mod install_tool;
+ mod lsp;
mod proxy_config;
mod retrieve_tool_output;
+ mod schedule;
mod shell;
+ mod shell_description;
+ mod shell_process;
+ mod shell_run;
mod shell_saas;
mod shell_support;
+ mod update_apply;
+ mod update_check;
-use crate::security::policy::{TrustedAccess, TrustedRoot};
use crate::security::SecurityPolicy;
+use crate::tools::implementations::filesystem::gate::security_scoped_to_root;
use tinytools::ToolRunContext;
- pub use exec_adapters::ShellTool;
pub use install_tool::InstallToolTool;
+ pub use lsp::{lsp_capability_enabled, LspTool, LSP_ENABLED_ENV};
pub use proxy_config::ProxyConfigTool;
pub use retrieve_tool_output::{retrieve_tool_output_tool, RetrieveToolOutputTool};
+ pub use schedule::ScheduleTool;
+ pub use shell::ShellTool;
+ pub use shell_process::ShellProcessTool;
+ pub(crate) use shell_support::YIELD_AFTER_ARG;
+ pub use update_apply::UpdateApplyTool;
+ pub use update_check::UpdateCheckTool;
- /// Clone and scope `security` to the run's workspace descriptor, if any.
+ /// Clone `security` and scope it to the run's workspace descriptor, if any.
+ ///
+ /// The process-tool counterpart of
+ /// `tools/impl/filesystem/gate.rs` (`security_scoped_to_root`), and it must stay in step
+ /// with it: the descriptor's root becomes both the relative-path resolution
+ /// root (`action_dir`) **and** a `ReadWrite` trusted root. The grant is the
+ /// load-bearing half — `action_dir` only decides where a relative path lands,
+ /// while the allow/deny decision reads `workspace_dir` + `trusted_roots`
+ /// (`SecurityPolicy::is_resolved_path_allowed_for`). Granting it in the
+ /// filesystem copy alone would let an agent read and edit a checkout it could
+ /// not then build, test, or commit, because the shell tool resolves its path through here.
+ ///
+ /// The grant is *additive and per-call*: it is pushed onto a clone, so nothing
+ /// process-global is mutated and concurrent turns cannot race each other. It
+ /// cannot widen the hard invariants either — `is_always_forbidden` and
+ /// `is_workspace_internal_path` are both evaluated *before* any trusted-root
+ /// shortcut.
+ ///
+ /// The root always originates from trusted in-process code (the session
+ /// builder, the sub-agent runner, or the `cwd` RPC parameter) — never from
+ /// model-supplied text.
-pub(super) fn security_for_tool_context(
+pub(in crate::tools::implementations) fn security_for_tool_context(
security: &SecurityPolicy,
context: Option<&dyn ToolRunContext>,
tool: &str,
diff --cc crates/openhuman-core/src/tools/impl/system/shell.rs
index 81a9cb5550,aa2424b680..d00b42ac44
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@@ -125,11 -129,11 +129,11 @@@ impl ShellTool
/// deadline applies only when the caller passes `timeout_secs` (issue
/// #4023). A `0` explicitly disables it. Any positive value is clamped to
/// `1..=3600`. See
- /// [`tinyagents_harness_tools::exec::timeout::explicit_call_timeout_duration`].
- pub(super) fn explicit_timeout(&self, requested: Option<u64>) -> Option<Duration> {
- /// [`tinytools_std::timeout::explicit_call_timeout_duration`].
++ /// `tinyagents_harness_tools::exec::timeout::explicit_call_timeout_duration`.
+ fn explicit_timeout(&self, requested: Option<u64>) -> Option<Duration> {
- tinytools_std::timeout::explicit_call_timeout_duration(
+ tinyagents_harness_tools::exec::timeout::explicit_call_timeout_duration(
requested,
- tinytools_std::timeout::MAX_TIMEOUT_SECS,
+ tinyagents_harness_tools::exec::timeout::MAX_TIMEOUT_SECS,
)
}
}
diff --cc crates/openhuman-core/src/tools/impl/system/shell_run.rs
index 0000000000,987b836903..be0ea2bda2
mode 000000,100644..100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_run.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_run.rs
@@@ -1,0 -1,266 +1,267 @@@
+ //! Running a `shell` call's command, and handing it to the turn when it is
+ //! still running at its yield point.
+ //!
+ //! Both the unsandboxed native shell and the sandbox backends come through
+ //! here. The native ones (no sandbox, TinyBox's native jail) can leave a
+ //! command running; Docker cannot, so there the model's own come-back time is
+ //! a deadline instead, as `timeout_secs` was before it yielded. A call yields
+ //! only when the turn moved the model's `timeout_secs` to [`YIELD_AFTER_ARG`]
+ //! (`agent::tinyagents::middleware::shell_yield`, which does so only when the
+ //! turn can follow a process with `shell_process`) and the turn has room for
+ //! another process.
+
+ use std::sync::{Arc, Mutex};
+ use std::time::{Duration, Instant};
+
+ use tinytools::{ToolResult, ToolRunContext};
+
+ use super::shell_support::{exec_result, yield_after, yielded_output, YIELD_AFTER_ARG};
+ use crate::sandbox::shell_exec::{ComeBack, ShellRunOutcome};
+ use crate::sandbox::shell_processes::{Ended, Slot};
+
+ /// Records the call's audit entry: whether the command passed the in-tool
+ /// checks, whether it succeeded, and how long it ran, in milliseconds.
+ pub(super) type AuditHook = Box<dyn FnOnce(bool, bool, u64) + Send>;
+
+ /// The call's audit entry, written once: right after the call, or, when the
+ /// command is left running, when the turn's registry sees it end.
+ pub(super) type AuditOnce = Mutex<Option<AuditHook>>;
+
+ /// What a call asked about coming back before its command ends.
+ #[derive(Clone, Copy, Debug, Default)]
+ pub(super) struct YieldRequest {
+ /// The turn lets this call yield: it moved the model's `timeout_secs` to
+ /// [`YIELD_AFTER_ARG`].
+ pub(super) allowed: bool,
+ /// The model's own come-back time, if it gave one.
+ pub(super) requested: Option<u64>,
+ }
+
+ impl YieldRequest {
+ pub(super) fn from_args(args: &serde_json::Value) -> Self {
+ let value = args.get(YIELD_AFTER_ARG);
+ Self {
+ allowed: value.is_some(),
+ requested: value.and_then(serde_json::Value::as_u64),
+ }
+ }
+
+ /// The deadline for a backend that cannot leave a command running: the
+ /// command's own deadline, or the model's come-back time if that is
+ /// sooner, so the model's `timeout_secs` still bounds the command there.
+ pub(super) fn deadline_instead(&self, deadline: Option<u64>) -> Option<u64> {
+ match (
+ deadline.filter(|secs| *secs > 0),
+ self.requested.filter(|secs| *secs > 0),
+ ) {
+ (Some(deadline), Some(requested)) => Some(deadline.min(requested)),
+ (deadline, requested) => deadline.or(requested),
+ }
+ }
+ }
+
+ /// A place in the turn's registry for this call, when it may yield.
+ fn slot(request: YieldRequest, context: Option<&dyn ToolRunContext>) -> Option<Slot> {
+ if !request.allowed {
+ return None;
+ }
+ let slot =
+ crate::agent::tinyagents::host::run_context::shell_processes_for_tool(context)?.reserve();
+ if slot.is_none() {
+ tracing::debug!(
+ "[shell] the turn is following its limit of processes; waiting for the end"
+ );
+ }
+ slot
+ }
+
+ /// The yield point for this call with a slot reserved for it, and the
+ /// command's deadline. A call that cannot yield (the turn has no place left,
+ /// or the command is a deliberate wait) keeps the model's come-back time as
+ /// its deadline, as `timeout_secs` was, so it still comes back by then.
+ fn come_back(
+ request: YieldRequest,
+ context: Option<&dyn ToolRunContext>,
+ command: &str,
+ deadline: Duration,
+ ) -> (Option<Slot>, Option<Duration>, Duration) {
+ let slot = slot(request, context);
+ let after = slot
+ .as_ref()
+ .and_then(|_| yield_after(request.requested, deadline, command));
+ if after.is_some() {
+ return (slot, after, deadline);
+ }
+ let deadline = request
+ .requested
+ .filter(|secs| *secs > 0)
+ .map_or(deadline, |secs| deadline.min(Duration::from_secs(secs)));
+ (None, None, deadline)
+ }
+
+ /// The tool result for a run, adopting a command still running into the
+ /// turn's registry; its audit entry then waits for the end.
+ fn finish(
+ outcome: anyhow::Result<ShellRunOutcome>,
+ slot: Option<Slot>,
+ command: &str,
+ started: Instant,
+ timeout: Duration,
+ audit: &AuditOnce,
+ ) -> ToolResult {
+ let live = match outcome {
+ Ok(ShellRunOutcome::Running(live)) => live,
+ Ok(ShellRunOutcome::Finished(result)) => return exec_result(Ok(result), timeout),
+ Err(error) => return exec_result(Err(error), timeout),
+ };
+ let Some(slot) = slot else {
+ // Unreachable: no yield point without a slot. The dropped handle
+ // stops the process.
+ return ToolResult::error("Command was left running unexpectedly.");
+ };
+ let (stdout, stderr) = (live.stdout.clone(), live.stderr.clone());
+ let on_end = audit
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take()
+ .map(|hook| -> crate::sandbox::shell_processes::OnEnd {
+ Box::new(move |ended: Ended, ran: Duration| {
+ hook(
+ true,
+ ended == Ended::Exited(0),
+ u64::try_from(ran.as_millis()).unwrap_or(u64::MAX),
+ );
+ })
+ });
+ let id = slot.adopt(live, command, started, timeout, on_end);
+ ToolResult::success(yielded_output(
+ &id,
+ started.elapsed(),
+ timeout,
+ &stdout,
+ &stderr,
+ ))
+ }
+
+ /// Run a native shell command for a `shell` call.
+ pub(super) async fn run_native(
+ ctx: &crate::core::runtime::DispatchCtx,
+ config: &crate::config::Config,
+ mut run: crate::sandbox::shell_exec::NativeShellRun,
+ request: YieldRequest,
+ context: Option<&dyn ToolRunContext>,
+ audit: &AuditOnce,
+ ) -> ToolResult {
+ let (slot, after, deadline) = come_back(request, context, &run.command, run.timeout);
+ run.yield_after = after;
+ run.timeout = deadline;
+ let (command, timeout) = (run.command.clone(), run.timeout);
+ let started = Instant::now();
+ let outcome = crate::sandbox::shell_exec::run_yielding(ctx, config, run).await;
+ finish(outcome, slot, &command, started, timeout, audit)
+ }
+
+ /// Run a command under a resolved sandbox `policy` for a `shell` call.
+ pub(super) async fn run_in_policy(
+ ctx: &crate::core::runtime::DispatchCtx,
+ policy: crate::sandbox::SandboxPolicy,
+ command: &str,
+ requested_timeout: Option<u64>,
+ request: YieldRequest,
+ action_dir: &std::path::Path,
+ context: Option<&dyn ToolRunContext>,
+ meter: Option<crate::sandbox::shell_progress::ShellOutputMeter>,
+ audit: &AuditOnce,
+ ) -> (bool, ToolResult) {
+ tracing::debug!(
+ backend = ?policy.backend,
+ command = command,
+ "[shell] routing to sandbox backend"
+ );
+
+ let mut extra_env = std::collections::HashMap::<std::ffi::OsString, std::ffi::OsString>::new();
+ let command_environment =
+ crate::agent::tinyagents::host::run_context::command_environment_for_tool(context);
+ super::shell_support::extend_explicit_environment(
+ &mut extra_env,
+ command_environment.as_deref(),
+ );
+ // Apply the same Git config hardening to local and sandboxed shells.
- extra_env.extend(tinytools_std::filesystem::shell_git_env());
++ extra_env.extend(tinyagents_harness_tools::fs::filesystem::shell_git_env());
+ // And the same Python defaults the native path sets.
+ for (var, val) in super::shell_support::python_env_defaults(|name| {
+ command_environment
+ .as_ref()
+ .and_then(|overrides| overrides.get(name).map(std::ffi::OsString::from))
+ .or_else(|| {
+ command_environment
+ .is_none()
+ .then(|| std::env::var_os(name))
+ .flatten()
+ })
+ }) {
+ extra_env.insert(var.into(), val);
+ }
+
+ // Sandbox backends require a finite deadline. Without an explicit
+ // `timeout_secs`, substitute the generous effective-unbounded cap so a
+ // long command isn't killed while still bounding a wedged sandbox.
- let explicit_timeout = tinytools_std::timeout::explicit_call_timeout_duration(
++ let explicit_timeout = tinyagents_harness_tools::exec::timeout::explicit_call_timeout_duration(
+ requested_timeout,
- tinytools_std::timeout::MAX_TIMEOUT_SECS,
++ tinyagents_harness_tools::exec::timeout::MAX_TIMEOUT_SECS,
+ );
- let effective = explicit_timeout
- .unwrap_or_else(|| Duration::from_secs(tinytools_std::timeout::SANDBOX_UNBOUNDED_CAP_SECS));
++ let effective = explicit_timeout.unwrap_or_else(|| {
++ Duration::from_secs(tinyagents_harness_tools::exec::timeout::SANDBOX_UNBOUNDED_CAP_SECS)
++ });
+ let (slot, yield_after, effective) = come_back(request, context, command, effective);
+ let deadline_instead = request
+ .deadline_instead(requested_timeout)
+ .map(Duration::from_secs);
+ tracing::debug!(
+ timeout_secs = effective.as_secs(),
+ requested_timeout_secs = ?requested_timeout,
+ unbounded = explicit_timeout.is_none(),
+ yield_after_secs = ?yield_after.map(|after| after.as_secs()),
+ "[shell] starting sandboxed command"
+ );
+
+ let started = Instant::now();
+ let outcome = crate::sandbox::ops::execute_in_sandbox_yielding(
+ ctx,
+ &policy,
+ command,
+ action_dir,
+ extra_env,
+ effective,
+ ComeBack {
+ yield_after,
+ deadline_instead,
+ },
+ meter,
+ )
+ .await;
+ // A command left running keeps its full deadline. One that finished was
+ // bounded by the model's time on Docker; a native run holding a slot
+ // yields before its deadline, so a timeout there is that same bound.
+ let timeout = match &outcome {
+ Ok(ShellRunOutcome::Running(_)) => effective,
+ _ => deadline_instead.map_or(effective, |deadline| effective.min(deadline)),
+ };
+ let result = finish(outcome, slot, command, started, timeout, audit);
+ (true, result)
+ }
+
+ /// The call's audit entry, to be written once by whoever learns the outcome.
+ pub(super) fn audit_once(
+ audit: Arc<crate::security::AuditLogger>,
+ command: String,
+ approved: bool,
+ ) -> AuditOnce {
+ Mutex::new(Some(Box::new(move |allowed, success, duration_ms| {
+ super::shell::record_audit(&audit, &command, approved, allowed, success, duration_ms);
+ })))
+ }
+
+ #[cfg(test)]
+ #[path = "shell_run_tests.rs"]
+ mod tests;
diff --cc vendor/tinyagents
index 0b2dd0d7e4,ed2880bbc5..f38929b1f2
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit 0b2dd0d7e491a0ea8c11040efc8d00d5e10c0443
-Subproject commit ed2880bbc5bc4bed33123e9180f792485c260973
++Subproject commit f38929b1f21741e230481298a1fb970a8bb67787