Skip to content

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

fix: restore CI gates and native runtime tests

Steven Enamakel706c8447383a
diff --git a/crates/openhuman-app/src/core_process_tests.rs b/crates/openhuman-app/src/core_process_tests.rs
index 94264434b4..53ee161336 100644
--- a/crates/openhuman-app/src/core_process_tests.rs
+++ b/crates/openhuman-app/src/core_process_tests.rs
@@ -6,21 +6,7 @@ use super::{
// lsof is a unix tool, so its parser is only compiled there.
#[cfg(unix)]
use super::parse_lsof_pid;
-use std::sync::{Mutex, MutexGuard, OnceLock};
-
-fn env_lock() -> MutexGuard<'static, ()> {
- static ENV_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
- // Recover from poison: when one test panics while holding this lock
- // (e.g. an embedded-core readiness timeout under CI load), every
- // subsequent test in the suite would otherwise cascade-fail with
- // "env lock poisoned" — turning one real flake into three. The lock
- // only serializes process-wide env-var mutation; the inner `()`
- // carries no state that poisoning could corrupt.
- ENV_LOCK
- .get_or_init(|| Mutex::new(()))
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
-}
+use crate::test_env::env_lock;
/// Builds the same worker runtime that the desktop host uses. Some core-process
/// tests start an embedded agent server; Tokio's default 2 MiB worker stack is
@@ -62,6 +48,36 @@ impl Drop for EnvGuard {
}
}
+/// A private, unsigned-in workspace and loopback-only backend keep embedded
+/// boot tests independent of the operator's profile and other test cleanup.
+struct TestWorkspace {
+ _env: EnvGuard,
+ _backend: EnvGuard,
+ _api_key: EnvGuard,
+ _session: EnvGuard,
+ _storage: EnvGuard,
+ _rpc_url: EnvGuard,
+ _directory: tempfile::TempDir,
+}
+
+fn test_workspace() -> TestWorkspace {
+ // Empty values also prevent dotenv from restoring inherited credentials
+ // or an external storage backend during boot.
+ let directory = tempfile::tempdir().expect("test workspace");
+ TestWorkspace {
+ _env: EnvGuard::set(
+ "OPENHUMAN_WORKSPACE",
+ directory.path().to_str().expect("workspace path"),
+ ),
+ _backend: EnvGuard::set("BACKEND_URL", "http://127.0.0.1:9"),
+ _api_key: EnvGuard::set("OPENHUMAN_BACKEND_API_KEY", ""),
+ _session: EnvGuard::set("OPENHUMAN_BACKEND_SESSION_TOKEN", ""),
+ _storage: EnvGuard::set("OPENHUMAN_STORAGE_URL", ""),
+ _rpc_url: EnvGuard::unset("OPENHUMAN_CORE_RPC_URL"),
+ _directory: directory,
+ }
+}
+
#[test]
fn default_core_port_env_and_fallback() {
let _env_lock = env_lock();
@@ -81,6 +97,8 @@ fn core_process_handle_new_creates_instance() {
#[test]
fn ready_signal_updates_runtime_port_and_fallback_notice() {
+ let _env_lock = env_lock();
+ let _rpc_url = EnvGuard::unset("OPENHUMAN_CORE_RPC_URL");
let handle = CoreProcessHandle::new(7788);
handle.apply_embedded_ready_signal(openhuman_rpc::host::EmbeddedReadySignal {
port: 7789,
@@ -111,10 +129,11 @@ fn ready_signal_updates_runtime_port_and_fallback_notice() {
fn ensure_running_does_not_publish_token_to_env() {
let _env_lock = env_lock();
let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
// Force a clean slate so we can assert on the post-spawn value.
let _wipe = EnvGuard::unset("OPENHUMAN_CORE_TOKEN");
let rt = core_test_runtime();
- let (result, env_after, expected_token, env_during_spawn) = rt.block_on(async {
+ let (result, env_after, env_during_spawn) = rt.block_on(async {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind test listener");
@@ -124,17 +143,19 @@ fn ensure_running_does_not_publish_token_to_env() {
tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
let handle = CoreProcessHandle::new(port);
- let expected_token = handle.rpc_token().to_string();
- let result = handle.ensure_running().await;
- // Capture env immediately after spawn returns Ok — before any
- // tokio task could plausibly have set the var.
- let env_after = std::env::var("OPENHUMAN_CORE_TOKEN").ok();
- // Also peek midway via spawning a tiny check task in the same
- // runtime — guards against the codepath setting+removing the var
- // within the spawn window.
- let env_during_spawn = std::env::var("OPENHUMAN_CORE_TOKEN").ok();
+ let startup = handle.ensure_running();
+ tokio::pin!(startup);
+ let mut token_seen_during_spawn = false;
+ let result = loop {
+ token_seen_during_spawn |= std::env::var_os("OPENHUMAN_CORE_TOKEN").is_some();
+ tokio::select! {
+ result = &mut startup => break result,
+ _ = tokio::time::sleep(std::time::Duration::from_millis(1)) => {}
+ }
+ };
+ let env_after = std::env::var_os("OPENHUMAN_CORE_TOKEN");
handle.shutdown().await;
- (result, env_after, expected_token, env_during_spawn)
+ (result, env_after, token_seen_during_spawn)
});
assert!(
@@ -144,21 +165,51 @@ fn ensure_running_does_not_publish_token_to_env() {
assert!(
env_after.is_none(),
"ensure_running must NOT publish OPENHUMAN_CORE_TOKEN to the process env \
- (sidecar-era leak channel removed). Found: {env_after:?} (handle token was {expected_token:?})"
+ (sidecar-era leak channel removed)"
);
assert!(
- env_during_spawn.is_none(),
- "OPENHUMAN_CORE_TOKEN must remain unset even momentarily during spawn. \
- Found: {env_during_spawn:?}"
+ !env_during_spawn,
+ "OPENHUMAN_CORE_TOKEN must remain unset during spawn"
);
}
+#[test]
+fn ensure_running_preserves_an_inherited_token_without_publishing_its_bearer() {
+ let _env_lock = env_lock();
+ let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
+ let _inherited = EnvGuard::set("OPENHUMAN_CORE_TOKEN", "inherited-test-token");
+ let rt = core_test_runtime();
+ rt.block_on(async {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind test listener");
+ let port = listener.local_addr().expect("local addr").port();
+ drop(listener);
+ let handle = CoreProcessHandle::new(port);
+ assert_ne!(handle.rpc_token(), "inherited-test-token");
+ let result = handle.ensure_running().await;
+ let inherited_preserved = std::env::var("OPENHUMAN_CORE_TOKEN")
+ .is_ok_and(|value| value == "inherited-test-token");
+ handle.shutdown().await;
+ assert!(
+ result.is_ok(),
+ "embedded core must become ready: {result:?}"
+ );
+ assert!(
+ inherited_preserved,
+ "startup must leave inherited token configuration unchanged"
+ );
+ });
+}
+
/// Issue #1613: when the preferred port is occupied by a non-OpenHuman
/// listener, startup should fall back to a nearby port instead of failing.
#[test]
fn ensure_running_falls_back_for_unknown_listener_on_port() {
let _env_lock = env_lock();
let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
let rt = core_test_runtime();
let (result, chosen_port, notice) = rt.block_on(async {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
@@ -195,6 +246,7 @@ fn ensure_running_falls_back_for_unknown_listener_on_port() {
fn ensure_running_falls_back_to_7789_when_7788_is_busy() {
let _env_lock = env_lock();
let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
let rt = core_test_runtime();
rt.block_on(async {
let listener = match tokio::net::TcpListener::bind("127.0.0.1:7788").await {
@@ -550,11 +602,11 @@ fn core_process_handle_new_token_is_valid() {
/// `CoreProcessHandle::new()` must NOT publish the token to the global
/// `CURRENT_RPC_TOKEN`. The global is set only after `ensure_running()`
-/// successfully spawns the embedded server with `OPENHUMAN_CORE_TOKEN` in
-/// scope. Advertising the token before spawn would 401 against any process
+/// successfully spawns the embedded server with its in-memory bearer. Advertising the token before spawn would 401 against any process
/// already listening on the port that never received this token.
#[test]
fn new_does_not_publish_global_token() {
+ let _env_lock = env_lock();
let before = current_rpc_token();
let handle = CoreProcessHandle::new(19002);
let after = current_rpc_token();
@@ -764,6 +816,7 @@ fn validate_kill_target_refuses_protected_pids() {
fn recover_port_conflict_succeeds_when_port_is_free() {
let _env_lock = env_lock();
let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
let rt = core_test_runtime();
let outcome = rt.block_on(async {
@@ -797,6 +850,7 @@ fn recover_port_conflict_succeeds_when_port_is_free() {
fn recover_port_conflict_handles_stale_listener() {
let _env_lock = env_lock();
let _unset = EnvGuard::unset("OPENHUMAN_CORE_REUSE_EXISTING");
+ let _workspace = test_workspace();
let rt = core_test_runtime();
// Bind a port, attempt recovery — the recovery must still succeed because
diff --git a/crates/openhuman-app/src/file_logging_tests.rs b/crates/openhuman-app/src/file_logging_tests.rs
index 63fbba7099..620fd9c15a 100644
--- a/crates/openhuman-app/src/file_logging_tests.rs
+++ b/crates/openhuman-app/src/file_logging_tests.rs
@@ -1,13 +1,10 @@
use super::*;
-/// Lock around env-var mutation. Cargo runs unit tests in parallel
-/// threads in the same process, so concurrent `set_var` / `remove_var`
-/// can race; the lock keeps the env stable for each test's duration.
-static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+use crate::test_env::env_lock;
#[test]
fn resolve_data_dir_honors_workspace_override() {
- let _guard = ENV_LOCK.lock().unwrap();
+ let _guard = env_lock();
let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();
std::env::set_var("OPENHUMAN_WORKSPACE", "/tmp/openhuman-test-override");
let dir = resolve_data_dir();
@@ -20,7 +17,7 @@ fn resolve_data_dir_honors_workspace_override() {
#[test]
fn resolve_data_dir_ignores_empty_workspace() {
- let _guard = ENV_LOCK.lock().unwrap();
+ let _guard = env_lock();
let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();
std::env::set_var("OPENHUMAN_WORKSPACE", "");
// Empty string must NOT short-circuit — fall through to the
diff --git a/crates/openhuman-app/src/gateway/store_tests.rs b/crates/openhuman-app/src/gateway/store_tests.rs
index 6229f086dd..32a38cdf75 100644
--- a/crates/openhuman-app/src/gateway/store_tests.rs
+++ b/crates/openhuman-app/src/gateway/store_tests.rs
@@ -5,13 +5,13 @@
//! process and the variable is process-wide, so they take a lock rather than
//! racing each other's workspace.
-use std::sync::{Mutex, MutexGuard, PoisonError};
+use std::sync::MutexGuard;
+
+use crate::test_env::env_lock;
use super::store;
use super::types::{Confinement, Gateway, GatewaySpec, Reach, DESKTOP_ID};
-static ENV_LOCK: Mutex<()> = Mutex::new(());
-
/// A temporary workspace, restored when the guard drops.
struct Workspace {
_lock: MutexGuard<'static, ()>,
@@ -29,7 +29,7 @@ impl Drop for Workspace {
}
fn workspace() -> Workspace {
- let lock = ENV_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
+ let lock = env_lock();
let dir = tempfile::TempDir::new().expect("a temporary directory");
let prior = std::env::var("OPENHUMAN_WORKSPACE").ok();
std::env::set_var("OPENHUMAN_WORKSPACE", dir.path());
diff --git a/crates/openhuman-app/src/lib.rs b/crates/openhuman-app/src/lib.rs
index 3c00f868a0..ca342119fc 100644
--- a/crates/openhuman-app/src/lib.rs
+++ b/crates/openhuman-app/src/lib.rs
@@ -3531,6 +3531,9 @@ fn macos_os_version() -> Option<String> {
.filter(|s| !s.is_empty())
}
+#[cfg(test)]
+mod test_env;
+
#[cfg(test)]
#[path = "lib_tests.rs"]
mod tests;
diff --git a/crates/openhuman-app/src/lib_tests.rs b/crates/openhuman-app/src/lib_tests.rs
index 9bb5002a89..fa3d0328e3 100644
--- a/crates/openhuman-app/src/lib_tests.rs
+++ b/crates/openhuman-app/src/lib_tests.rs
@@ -1,4 +1,5 @@
use super::*;
+use crate::test_env::env_lock;
#[test]
fn main_window_centering_only_follows_failed_restore_and_maximize() {
@@ -8,12 +9,6 @@ fn main_window_centering_only_follows_failed_restore_and_maximize() {
assert!(should_center_main_window(false, false, false));
}
-// Tests that read/write process-global env vars must serialize through this
-// mutex. Rust's test runner executes tests in parallel by default; without
-// coordination, concurrent set_var / remove_var calls race and produce
-// spurious failures.
-static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
-
// NOTE: `is_daemon_mode_detects_daemon_flag` removed (plan.md §2.1) — it
// discarded the result with `let _` and asserted nothing.
@@ -52,7 +47,7 @@ fn restore_command_preserves_minimized_and_maximized_frames() {
/// the embedded port — is unchanged and still lives in that function.
#[test]
fn core_rpc_url_returns_expected_format() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var("OPENHUMAN_CORE_RPC_URL").ok();
std::env::set_var("OPENHUMAN_CORE_RPC_URL", "http://localhost:9999/rpc");
@@ -72,7 +67,7 @@ fn core_rpc_url_returns_expected_format() {
/// Test overlay_parent_rpc_url handles empty env var
#[test]
fn overlay_parent_rpc_url_handles_empty() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var("OPENHUMAN_CORE_RPC_URL").ok();
std::env::set_var("OPENHUMAN_CORE_RPC_URL", "");
@@ -656,7 +651,7 @@ fn sentry_release_tag_is_nonempty() {
#[test]
fn sentry_environment_reads_openhuman_app_env() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let key = "OPENHUMAN_APP_ENV";
let original = std::env::var(key).ok();
std::env::set_var(key, "staging");
@@ -670,7 +665,7 @@ fn sentry_environment_reads_openhuman_app_env() {
#[test]
fn sentry_environment_trims_whitespace_from_openhuman_app_env() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let key = "OPENHUMAN_APP_ENV";
let original = std::env::var(key).ok();
std::env::set_var(key, " dev ");
@@ -684,7 +679,7 @@ fn sentry_environment_trims_whitespace_from_openhuman_app_env() {
#[test]
fn sentry_environment_skips_empty_openhuman_app_env() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let key = "OPENHUMAN_APP_ENV";
let original = std::env::var(key).ok();
std::env::set_var(key, "");
@@ -699,7 +694,7 @@ fn sentry_environment_skips_empty_openhuman_app_env() {
#[test]
fn sentry_environment_skips_whitespace_only_openhuman_app_env() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let key = "OPENHUMAN_APP_ENV";
let original = std::env::var(key).ok();
std::env::set_var(key, " ");
@@ -716,7 +711,7 @@ fn sentry_environment_skips_whitespace_only_openhuman_app_env() {
/// asserts the hard default when no compile-time override is present.
#[test]
fn sentry_environment_defaults_to_production_when_unset() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
if option_env!("VITE_OPENHUMAN_APP_ENV").is_some() {
// A compile-time override is baked in; skip — the fallback path is
// exercised by sentry_environment_skips_empty_openhuman_app_env.
@@ -872,7 +867,7 @@ fn localhost_dev_fetch_noise_anchors_to_message_start() {
#[cfg(target_os = "linux")]
#[test]
fn path_has_executable_finds_file_on_path() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var_os("PATH");
let dir = tempfile::tempdir().expect("tempdir");
@@ -896,7 +891,7 @@ fn path_has_executable_finds_file_on_path() {
#[cfg(target_os = "linux")]
#[test]
fn path_has_executable_returns_false_when_missing() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var_os("PATH");
let dir = tempfile::tempdir().expect("tempdir");
@@ -919,7 +914,7 @@ fn path_has_executable_returns_false_when_missing() {
#[cfg(target_os = "linux")]
#[test]
fn path_has_executable_returns_false_when_path_unset() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var_os("PATH");
std::env::remove_var("PATH");
@@ -946,7 +941,7 @@ fn path_has_executable_returns_false_when_path_unset() {
#[cfg(target_os = "linux")]
#[test]
fn path_has_executable_returns_false_for_partial_xdg_utils_install() {
- let _g = ENV_LOCK.lock().unwrap();
+ let _g = env_lock();
let original = std::env::var_os("PATH");
let dir = tempfile::tempdir().expect("tempdir");
diff --git a/crates/openhuman-app/src/test_env.rs b/crates/openhuman-app/src/test_env.rs
new file mode 100644
index 0000000000..7df21168fe
--- /dev/null
+++ b/crates/openhuman-app/src/test_env.rs
@@ -0,0 +1,15 @@
+//! One lock for every desktop unit test that reads or changes process environment.
+//! Separate module-local locks cannot protect a core boot from another test's
+//! temporary workspace, RPC URL, or executable search path.
+
+use std::sync::{Mutex, MutexGuard};
+
+static ENV_LOCK: Mutex<()> = Mutex::new(());
+
+pub(crate) fn env_lock() -> MutexGuard<'static, ()> {
+ // Environment guards restore on unwind, so poisoning carries no state
+ // that could make the next test unsafe.
+ ENV_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
index a50fd418eb..b52624611e 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -19,6 +19,9 @@ use tinytools_agent::dialect::{
CodeDialect, NativeDialect, PFormatDialect, ToolDialect, XmlDialect,
};
+#[path = "factory_workflows.rs"]
+mod workflows;
+
impl OpenHumanSessionHost {
/// Returns whether `agent_id` resolves to a runnable definition for this
/// configuration. This is deliberately the same resolution path used by
@@ -800,14 +803,7 @@ impl OpenHumanSessionHost {
.workspace_dir(config.workspace_dir.clone())
.action_dir(config.action_dir.clone())
.workspace_descriptor(workspace_descriptor)
- .workflows(if host_only {
- Vec::new()
- } else {
- let mut catalogue = crate::skills::load_workflow_metadata(&config.workspace_dir);
- #[cfg(feature = "flows")]
- catalogue.extend(crate::flows::catalogue::flow_entries(config));
- catalogue
- })
+ .workflows(workflows::session_workflows(config, host_only))
.post_turn_hooks(post_turn_hooks)
.agent_definition_name(agent_id.to_string())
.omit_memory_context(effective_omit_memory_context)
diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory_workflows.rs b/crates/openhuman-core/src/agent/session_host/builder/factory_workflows.rs
new file mode 100644
index 0000000000..6fb763c992
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory_workflows.rs
@@ -0,0 +1,18 @@
+//! The skill and flow catalogue exposed to a newly constructed session.
+
+use crate::config::Config;
+use crate::skills::Workflow;
+
+pub(super) fn session_workflows(config: &Config, host_only: bool) -> Vec<Workflow> {
+ if host_only {
+ return Vec::new();
+ }
+ let catalogue = crate::skills::load_workflow_metadata(&config.workspace_dir);
+ #[cfg(feature = "flows")]
+ let catalogue = {
+ let mut catalogue = catalogue;
+ catalogue.extend(crate::flows::catalogue::flow_entries(config));
+ catalogue
+ };
+ catalogue
+}
diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
index da250aca38..efeb84fe1f 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
@@ -6,6 +6,7 @@
//! registry from a loaded [`Config`]. Per-turn behaviour lives in
//! [`super::turn`]; accessors and run-helpers live in [`super::runtime`].
+#[cfg(feature = "flows")]
pub(crate) use factory::provider_role_for_definition;
mod builder_build;
diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs
index 2c5da159bb..450f0021af 100644
--- a/crates/openhuman-core/src/agent/session_host/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@ -30,6 +30,7 @@
//! `crate::agent`, which re-exports them from this module.
//! The child files are an implementation detail.
+#[cfg(feature = "flows")]
pub(crate) use builder::provider_role_for_definition;
pub use builder::{HostOnlyToolPolicy, HostTools, HostTurnTools, TurnContext};
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index 3a647f284d..b6574f93b6 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -770,72 +770,9 @@ pub(super) fn reconcile_synthesized_visibility(
}
}
-/// Account only a receipt-backed turn, using the same direct-plus-completed
-/// child total the codec attached to the atomic transcript append.
-pub(super) async fn account_committed_turn_against_goal(
- workspace_dir: &std::path::Path,
- thread_id: Option<&str>,
- sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
-) {
- let child_input = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.input_tokens)
- .sum::<u64>();
- let child_output = sidecar
- .subagents
- .iter()
- .map(|entry| entry.usage.output_tokens)
- .sum::<u64>();
- crate::agent::goals::runtime::account_turn_against_goal(
- workspace_dir,
- thread_id,
- sidecar.input_tokens.saturating_add(child_input),
- sidecar.output_tokens.saturating_add(child_output),
- sidecar
- .duration
- .map(|duration| duration.as_secs())
- .unwrap_or_default(),
- )
- .await;
-}
-
-/// UI billing projection for a committed turn. It keeps child records for a
-/// detailed display while reporting the same all-in totals the codec persists.
-pub(super) fn holistic_last_turn_usage(
- sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
-) -> crate::agent::tinyagents::host::LastTurnUsage {
- // Each count is the turn's own plus every synchronous child's.
- let tokens = |own: u64, child: fn(&crate::agent::subagent_host::SubagentUsage) -> u64| {
- sidecar.subagents.iter().fold(own, |total, entry| {
- total.saturating_add(child(&entry.usage))
- })
- };
- let input_tokens = tokens(sidecar.input_tokens, |usage| usage.input_tokens);
- let output_tokens = tokens(sidecar.output_tokens, |usage| usage.output_tokens);
- let cached_input_tokens = tokens(sidecar.cached_input_tokens, |usage| {
- usage.cached_input_tokens
- });
- let mut cost = sidecar.cost;
- for entry in &sidecar.subagents {
- cost.merge(entry.usage.cost());
- }
- crate::agent::tinyagents::host::LastTurnUsage {
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cost_usd: cost.usd(),
- cost_source: cost.source,
- context_window: sidecar.context_window,
- context_tokens: sidecar
- .last_call_input_tokens
- .saturating_add(sidecar.last_call_output_tokens),
- subagents: sidecar.subagents.clone(),
- // The session does not count these; a library turn that asked for a
- // final-response report fills them in (`response_shape`).
- reasoning_tokens: 0,
- }
-}
+#[path = "runtime_session_usage.rs"]
+mod usage;
+pub(super) use usage::{account_committed_turn_against_goal, holistic_last_turn_usage};
impl OpenHumanSessionHost {
pub(super) fn update_runtime_prelude_progress(
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_usage.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_usage.rs
new file mode 100644
index 0000000000..92c1ed22d4
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_usage.rs
@@ -0,0 +1,68 @@
+//! Committed-turn goal accounting and billing projection.
+
+/// Account only a receipt-backed turn, using the same direct-plus-completed
+/// child total the codec attached to the atomic transcript append.
+pub(in crate::agent::session_host) async fn account_committed_turn_against_goal(
+ workspace_dir: &std::path::Path,
+ thread_id: Option<&str>,
+ sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
+) {
+ let child_input = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.input_tokens)
+ .sum::<u64>();
+ let child_output = sidecar
+ .subagents
+ .iter()
+ .map(|entry| entry.usage.output_tokens)
+ .sum::<u64>();
+ crate::agent::goals::runtime::account_turn_against_goal(
+ workspace_dir,
+ thread_id,
+ sidecar.input_tokens.saturating_add(child_input),
+ sidecar.output_tokens.saturating_add(child_output),
+ sidecar
+ .duration
+ .map(|duration| duration.as_secs())
+ .unwrap_or_default(),
+ )
+ .await;
+}
+
+/// UI billing projection for a committed turn. It keeps child records for a
+/// detailed display while reporting the same all-in totals the codec persists.
+pub(in crate::agent::session_host) fn holistic_last_turn_usage(
+ sidecar: &crate::agent::tinyagents::host::run_context::SessionTurnSidecar,
+) -> crate::agent::tinyagents::host::LastTurnUsage {
+ // Each count is the turn's own plus every synchronous child's.
+ let tokens = |own: u64, child: fn(&crate::agent::subagent_host::SubagentUsage) -> u64| {
+ sidecar.subagents.iter().fold(own, |total, entry| {
+ total.saturating_add(child(&entry.usage))
+ })
+ };
+ let input_tokens = tokens(sidecar.input_tokens, |usage| usage.input_tokens);
+ let output_tokens = tokens(sidecar.output_tokens, |usage| usage.output_tokens);
+ let cached_input_tokens = tokens(sidecar.cached_input_tokens, |usage| {
+ usage.cached_input_tokens
+ });
+ let mut cost = sidecar.cost;
+ for entry in &sidecar.subagents {
+ cost.merge(entry.usage.cost());
+ }
+ crate::agent::tinyagents::host::LastTurnUsage {
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cost_usd: cost.usd(),
+ cost_source: cost.source,
+ context_window: sidecar.context_window,
+ context_tokens: sidecar
+ .last_call_input_tokens
+ .saturating_add(sidecar.last_call_output_tokens),
+ subagents: sidecar.subagents.clone(),
+ // The session does not count these; a library turn that asked for a
+ // final-response report fills them in (`response_shape`).
+ reasoning_tokens: 0,
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 02dfb0f041..3006362fd8 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -1139,85 +1139,9 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
}
}
-fn host_outcome_to_neutral(
- outcome: SubagentRunOutcome,
- definition: &crate::agent::harness::definition::AgentDefinition,
- options: &SubagentRunOptions,
-) -> SubagentOutcome {
- let status = match outcome.status {
- SubagentRunStatus::Completed => SubagentOutcomeKind::Completed,
- SubagentRunStatus::AwaitingUser { question, .. } => {
- SubagentOutcomeKind::AwaitingInput(SubagentPause {
- reason: question,
- resume: SubagentResume {
- history: outcome
- .final_history
- .iter()
- .map(crate::agent::message_convert::chat_message_to_message)
- .collect(),
- metadata: std::collections::BTreeMap::from_iter([
- ("agent_id".into(), definition.id.clone()),
- (
- "worker_thread_id".into(),
- options.worker_thread_id.clone().unwrap_or_default(),
- ),
- (
- "skill_filter_override".into(),
- options.skill_filter_override.clone().unwrap_or_default(),
- ),
- (
- "model_override".into(),
- options.model_override.clone().unwrap_or_default(),
- ),
- ]),
- ..SubagentResume::default()
- },
- })
- }
- SubagentRunStatus::Incomplete { reason } => {
- SubagentOutcomeKind::Incomplete(SubagentIncomplete::new(reason))
- }
- SubagentRunStatus::Cancelled => SubagentOutcomeKind::Cancelled,
- };
- SubagentOutcome {
- task_id: outcome.task_id,
- output: outcome.output,
- history: outcome
- .final_history
- .iter()
- .map(crate::agent::message_convert::chat_message_to_message)
- .collect(),
- status,
- usage: UsageTotals {
- calls: outcome.iterations as u64,
- usage: Usage {
- input_tokens: outcome.usage.input_tokens,
- output_tokens: outcome.usage.output_tokens,
- total_tokens: outcome
- .usage
- .input_tokens
- .saturating_add(outcome.usage.output_tokens),
- cache_read_tokens: outcome.usage.cached_input_tokens,
- // An unknown cost crosses as no charge at all, never as $0.
- charged_amount: outcome
- .usage
- .cost()
- .usd()
- .map(|usd| ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)),
- ..Usage::default()
- },
- },
- artifacts: outcome
- .artifact_paths
- .into_iter()
- .map(|id| ArtifactReference {
- id,
- ..ArtifactReference::default()
- })
- .collect(),
- ..SubagentOutcome::cancelled(String::new())
- }
-}
+#[path = "lifecycle_outcome.rs"]
+mod outcome;
+use outcome::host_outcome_to_neutral;
fn outcome_to_host(
result: SubagentRunResult,
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs
new file mode 100644
index 0000000000..684f400c66
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_outcome.rs
@@ -0,0 +1,83 @@
+//! Translation from product subagent outcomes to neutral orchestration records.
+
+use super::*;
+
+pub(super) fn host_outcome_to_neutral(
+ outcome: SubagentRunOutcome,
+ definition: &crate::agent::harness::definition::AgentDefinition,
+ options: &SubagentRunOptions,
+) -> SubagentOutcome {
+ let status = match outcome.status {
+ SubagentRunStatus::Completed => SubagentOutcomeKind::Completed,
+ SubagentRunStatus::AwaitingUser { question, .. } => {
+ SubagentOutcomeKind::AwaitingInput(SubagentPause {
+ reason: question,
+ resume: SubagentResume {
+ history: outcome
+ .final_history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ metadata: std::collections::BTreeMap::from_iter([
+ ("agent_id".into(), definition.id.clone()),
+ (
+ "worker_thread_id".into(),
+ options.worker_thread_id.clone().unwrap_or_default(),
+ ),
+ (
+ "skill_filter_override".into(),
+ options.skill_filter_override.clone().unwrap_or_default(),
+ ),
+ (
+ "model_override".into(),
+ options.model_override.clone().unwrap_or_default(),
+ ),
+ ]),
+ ..SubagentResume::default()
+ },
+ })
+ }
+ SubagentRunStatus::Incomplete { reason } => {
+ SubagentOutcomeKind::Incomplete(SubagentIncomplete::new(reason))
+ }
+ SubagentRunStatus::Cancelled => SubagentOutcomeKind::Cancelled,
+ };
+ SubagentOutcome {
+ task_id: outcome.task_id,
+ output: outcome.output,
+ history: outcome
+ .final_history
+ .iter()
+ .map(crate::agent::message_convert::chat_message_to_message)
+ .collect(),
+ status,
+ usage: UsageTotals {
+ calls: outcome.iterations as u64,
+ usage: Usage {
+ input_tokens: outcome.usage.input_tokens,
+ output_tokens: outcome.usage.output_tokens,
+ total_tokens: outcome
+ .usage
+ .input_tokens
+ .saturating_add(outcome.usage.output_tokens),
+ cache_read_tokens: outcome.usage.cached_input_tokens,
+ // An unknown cost crosses as no charge at all, never as $0.
+ charged_amount: outcome
+ .usage
+ .cost()
+ .usd()
+ .map(|usd| ChargedAmount::usd_micros((usd * 1_000_000.0).round() as i64)),
+ ..Usage::default()
+ },
+ },
+ artifacts: outcome
+ .artifact_paths
+ .into_iter()
+ .map(|id| ArtifactReference {
+ id,
+ ..ArtifactReference::default()
+ })
+ .collect(),
+ ..SubagentOutcome::cancelled(String::new())
+ }
+}
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
index 1d482da102..9a70704885 100644
--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs
@@ -95,29 +95,9 @@ pub(super) fn tier_gate_decision(
Ok(())
}
-/// Truncate `output` in place to the definition's `max_result_chars` cap (when
-/// set), appending a `[...truncated]` marker. Char-count based (not byte-length)
-/// to avoid panicking on a multi-byte UTF-8 sequence at the boundary.
-fn apply_max_result_chars(output: &mut String, cap: Option<usize>, agent_id: &str) {
- let Some(cap) = cap else { return };
- let original_chars = output.chars().count();
- if original_chars <= cap {
- return;
- }
- tracing::debug!(
- agent_id = %agent_id,
- original_chars,
- cap,
- "[subagent_host] truncating oversized result to max_result_chars cap"
- );
- let byte_offset = output
- .char_indices()
- .nth(cap)
- .map(|(i, _)| i)
- .unwrap_or(output.len());
- output.truncate(byte_offset);
- output.push_str("\n[...truncated]");
-}
+#[path = "runner_result_cap.rs"]
+mod result_cap;
+use result_cap::apply_max_result_chars;
/// Run a sub-agent based on its definition and a task prompt.
///
diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner_result_cap.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner_result_cap.rs
new file mode 100644
index 0000000000..8bade1cfe9
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner_result_cap.rs
@@ -0,0 +1,25 @@
+//! Character-safe result caps for delegated agent output.
+
+/// Truncate `output` in place to the definition's `max_result_chars` cap (when
+/// set), appending a `[...truncated]` marker. Char-count based (not byte-length)
+/// to avoid panicking on a multi-byte UTF-8 sequence at the boundary.
+pub(super) fn apply_max_result_chars(output: &mut String, cap: Option<usize>, agent_id: &str) {
+ let Some(cap) = cap else { return };
+ let original_chars = output.chars().count();
+ if original_chars <= cap {
+ return;
+ }
+ tracing::debug!(
+ agent_id = %agent_id,
+ original_chars,
+ cap,
+ "[subagent_host] truncating oversized result to max_result_chars cap"
+ );
+ let byte_offset = output
+ .char_indices()
+ .nth(cap)
+ .map(|(i, _)| i)
+ .unwrap_or(output.len());
+ output.truncate(byte_offset);
+ output.push_str("\n[...truncated]");
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
index 68f370f5cf..4d2a8ecd60 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -11,8 +11,7 @@ use tinyagents_harness::middleware::{
RepeatProgressMiddleware, RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,
};
use tinyagents_harness::runtime::AgentHarness;
-use tinyagents_harness::steering::SteeringHandle;
-use tinyagents_registry::{CapabilityRegistry, RegistryDiagnostic, RegistrySnapshot};
+use tinyagents_registry::CapabilityRegistry;
use tinyinference_llm::model::CapabilitySet;
use tokio::sync::mpsc::Sender;
@@ -39,68 +38,9 @@ use tinyagents_harness::store::InMemoryStore as ToolResultArtifactIndexStore;
use super::ToolPolicyEnforcement;
-/// Everything [`assemble_turn_harness`] wires up for one turn: the configured
-/// harness plus the shared slots/handles the run loop reads after the drive
-/// future returns.
-pub(super) struct AssembledTurnHarness {
- /// The fully assembled harness: model, tools, and middleware registered in
- /// the intended order.
- pub(super) harness: AgentHarness<(), OpenHumanRunContext>,
- /// Shared 1-based model-call cursor (event bridge advances, model adapter
- /// reads for out-of-band thinking attribution).
- pub(super) cursor: IterationCursor,
- /// Shared `call_id → tool_name` map used by the event bridge to label
- /// tool-argument fragments projected off the crate stream.
- pub(super) tool_names: ToolNameMap,
- /// Shared `call_id → (success, failure, elapsed_ms, output_chars)` side-channel:
- /// middleware records each outcome for the event bridge's `ToolCallCompleted`.
- pub(super) failure_map: ToolFailureMap,
- /// Shared FIFO carry of per-call provider `BilledUsage`; the event bridge
- /// reads it when recording usage to preserve charged-USD precedence (#4467).
- pub(super) provider_usage_carry: ProviderUsageCarry,
- /// Recovers the original (downcastable) provider error on run failure.
- pub(super) error_slot: crate::agent::tinyagents::model::ModelErrorSlot,
- /// Root-cause summary recorded by the repeated-tool-failure breaker.
- pub(super) halt_summary: HaltSummarySlot,
- /// Per-call tool success/content capture for honest `ToolCallRecord`s.
- pub(super) tool_outcome_sink: ToolOutcomeSink,
- /// The shared steering handle (mid-flight steer, early-exit, cap, stop-hook
- /// pauses).
- pub(super) handle: Option<SteeringHandle>,
- /// Records the first early-exit tool round, when early-exit tools exist.
- pub(super) early_exit_hook: Option<EarlyExitHook>,
- /// Set by [`FinalCallWrapUpMiddleware`] when it turned the last permitted
- /// model call into the turn's conclusion (issue #6014). `None` when the
- /// middleware is not installed (a run that does not pause at its cap).
- ///
- /// A flag rather than an inference off the run, because this turn now ends
- /// the way a finished one does — the model returns text and requests no
- /// tools — so `final_response.is_none()` no longer tells the two apart.
- pub(super) wrap_up_fired:
- Option<Arc<tinyagents_harness::middleware::FinalCallWrapUpMiddleware>>,
- /// Number of callable tools registered.
- pub(super) tool_count: usize,
- /// TinyAgents named-capability projection for this turn. The live run still
- /// uses the harness registries above; this snapshot makes the projected
- /// model/tool/graph inventory inspectable without changing dispatch.
- pub(super) registry_snapshot: RegistrySnapshot,
- /// Health diagnostics from the projected registry.
- pub(super) registry_diagnostics: Vec<RegistryDiagnostic>,
- /// TinyAgents store index for OpenHuman action-dir tool-result artifacts.
- pub(super) tool_result_artifact_index: Option<Arc<ToolResultArtifactIndexStore>>,
- /// Concrete handle to the installed [`ContextCompressionMiddleware`], when
- /// summarization is active. Drained after the run to surface each compaction's
- /// [`CompressionProvenance`][tinyagents_harness::summarization::CompressionProvenance]
- /// via the observability path.
- pub(super) compression_mw: Option<Arc<ContextCompressionMiddleware>>,
- /// Crate prompt-cache guard (issue #4249, 03.2). Records a `CacheLayoutEvent`
- /// whenever the cacheable prompt prefix (system prompt + tool set) changes
- /// across model calls. Drained after the run and surfaced via
- /// [`observability::surface_cache_layout_events`](crate::agent::tinyagents::observability::surface_cache_layout_events) —
- /// the crate-native replacement for the deleted `CacheAlignMiddleware`
- /// warn-log (C3).
- pub(super) prompt_cache_guard: Arc<PromptCacheGuardMiddleware>,
-}
+#[path = "harness_assembly_state.rs"]
+mod state;
+pub(super) use state::AssembledTurnHarness;
/// Assemble the turn harness for [`run_turn_via_tinyagents_shared`](super::run_turn_via_tinyagents_shared):
/// register the provider model, every shared tool, and the full middleware
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly_state.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly_state.rs
new file mode 100644
index 0000000000..d61f7af48e
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly_state.rs
@@ -0,0 +1,69 @@
+//! Shared harness state and handles consumed after a turn.
+
+use super::*;
+use tinyagents_harness::steering::SteeringHandle;
+use tinyagents_registry::{RegistryDiagnostic, RegistrySnapshot};
+
+/// Everything [`assemble_turn_harness`] wires up for one turn: the configured
+/// harness plus the shared slots/handles the run loop reads after the drive
+/// future returns.
+pub(in crate::agent::tinyagents) struct AssembledTurnHarness {
+ /// The fully assembled harness: model, tools, and middleware registered in
+ /// the intended order.
+ pub(in crate::agent::tinyagents) harness: AgentHarness<(), OpenHumanRunContext>,
+ /// Shared 1-based model-call cursor (event bridge advances, model adapter
+ /// reads for out-of-band thinking attribution).
+ pub(in crate::agent::tinyagents) cursor: IterationCursor,
+ /// Shared `call_id → tool_name` map used by the event bridge to label
+ /// tool-argument fragments projected off the crate stream.
+ pub(in crate::agent::tinyagents) tool_names: ToolNameMap,
+ /// Shared `call_id → (success, failure, elapsed_ms, output_chars)` side-channel:
+ /// middleware records each outcome for the event bridge's `ToolCallCompleted`.
+ pub(in crate::agent::tinyagents) failure_map: ToolFailureMap,
+ /// Shared FIFO carry of per-call provider `BilledUsage`; the event bridge
+ /// reads it when recording usage to preserve charged-USD precedence (#4467).
+ pub(in crate::agent::tinyagents) provider_usage_carry: ProviderUsageCarry,
+ /// Recovers the original (downcastable) provider error on run failure.
+ pub(in crate::agent::tinyagents) error_slot: crate::agent::tinyagents::model::ModelErrorSlot,
+ /// Root-cause summary recorded by the repeated-tool-failure breaker.
+ pub(in crate::agent::tinyagents) halt_summary: HaltSummarySlot,
+ /// Per-call tool success/content capture for honest `ToolCallRecord`s.
+ pub(in crate::agent::tinyagents) tool_outcome_sink: ToolOutcomeSink,
+ /// The shared steering handle (mid-flight steer, early-exit, cap, stop-hook
+ /// pauses).
+ pub(in crate::agent::tinyagents) handle: Option<SteeringHandle>,
+ /// Records the first early-exit tool round, when early-exit tools exist.
+ pub(in crate::agent::tinyagents) early_exit_hook: Option<EarlyExitHook>,
+ /// Set by [`FinalCallWrapUpMiddleware`] when it turned the last permitted
+ /// model call into the turn's conclusion (issue #6014). `None` when the
+ /// middleware is not installed (a run that does not pause at its cap).
+ ///
+ /// A flag rather than an inference off the run, because this turn now ends
+ /// the way a finished one does — the model returns text and requests no
+ /// tools — so `final_response.is_none()` no longer tells the two apart.
+ pub(in crate::agent::tinyagents) wrap_up_fired:
+ Option<Arc<tinyagents_harness::middleware::FinalCallWrapUpMiddleware>>,
+ /// Number of callable tools registered.
+ pub(in crate::agent::tinyagents) tool_count: usize,
+ /// TinyAgents named-capability projection for this turn. The live run still
+ /// uses the harness registries above; this snapshot makes the projected
+ /// model/tool/graph inventory inspectable without changing dispatch.
+ pub(in crate::agent::tinyagents) registry_snapshot: RegistrySnapshot,
+ /// Health diagnostics from the projected registry.
+ pub(in crate::agent::tinyagents) registry_diagnostics: Vec<RegistryDiagnostic>,
+ /// TinyAgents store index for OpenHuman action-dir tool-result artifacts.
+ pub(in crate::agent::tinyagents) tool_result_artifact_index:
+ Option<Arc<ToolResultArtifactIndexStore>>,
+ /// Concrete handle to the installed [`ContextCompressionMiddleware`], when
+ /// summarization is active. Drained after the run to surface each compaction's
+ /// [`CompressionProvenance`][tinyagents_harness::summarization::CompressionProvenance]
+ /// via the observability path.
+ pub(in crate::agent::tinyagents) compression_mw: Option<Arc<ContextCompressionMiddleware>>,
+ /// Crate prompt-cache guard (issue #4249, 03.2). Records a `CacheLayoutEvent`
+ /// whenever the cacheable prompt prefix (system prompt + tool set) changes
+ /// across model calls. Drained after the run and surfaced via
+ /// [`observability::surface_cache_layout_events`](crate::agent::tinyagents::observability::surface_cache_layout_events) —
+ /// the crate-native replacement for the deleted `CacheAlignMiddleware`
+ /// warn-log (C3).
+ pub(in crate::agent::tinyagents) prompt_cache_guard: Arc<PromptCacheGuardMiddleware>,
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
index 353573ff02..fe2118c1c2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs
@@ -377,65 +377,9 @@ impl OpenHumanSecurityGate {
}
}
-/// What the model is told when the approval prompt for `tool_name` expired
-/// unanswered. Like the refusal text it carries no `[policy-denied]` marker
-/// (see [`decision_for_outcome`]), so the model keeps the turn to tell the
-/// user.
-pub(crate) fn unanswered_approval_text(tool_name: &str) -> String {
- format!(
- "The approval request for '{tool_name}' was not answered in time, so it was not run. \
- Tell the user the approval window expired and that they must ask again to retry. \
- Do not retry this call yourself this turn and do not achieve the same result another \
- way (shell, CLI, another tool)."
- )
-}
-
-/// Maps how the approval flow settled to what the runtime is told.
-///
-/// A refusal is a `Deny` whose text names no human and no timeout — every
-/// refusal reads the same — and rules out other routes explicitly, because
-/// `shell` never prompts while autonomy is disabled (`[autonomy] enabled =
-/// false`, the default) and was used to redo a refused call.
-///
-/// The text carries no `[policy-denied]` marker on purpose. The marker
-/// classifies as a policy failure with a zero recovery budget
-/// (`middleware::repeated_failure`), which pauses the turn before the model can
-/// answer. The model must get this turn to tell the user the action was not
-/// done, as it did with the harness's unmarked fallback text.
-fn decision_for_outcome(tool_name: &str, outcome: GateOutcome) -> GateDecision {
- match outcome {
- GateOutcome::Allow => GateDecision::Prompted { approved: true },
- // An expired prompt is not a refusal: nobody answered, and the gate has
- // now denied the request. Saying so lets the agent (and, for a
- // sub-agent, its parent) tell the user the approval window expired and
- // that they must ask again for a new request, rather than that it was
- // declined — the generic text below left a 600s `media_generate_image`
- // expiry reported as nothing at all.
- GateOutcome::Deny { reason }
- if crate::security::approval::is_unanswered_approval_reason(&reason) =>
- {
- tracing::warn!(
- target: "tinyagents",
- tool = %tool_name,
- "[tinyagents::host::security] approval prompt expired unanswered"
- );
- GateDecision::deny(unanswered_approval_text(tool_name))
- }
- GateOutcome::Deny { reason } => {
- tracing::warn!(
- target: "tinyagents",
- tool = %tool_name,
- reason = %reason,
- "[tinyagents::host::security] approval flow declined the tool call"
- );
- GateDecision::deny(
- "This action was refused and must not be performed this turn — do not retry this \
- call and do not achieve the same result another way (shell, CLI, another tool). \
- Tell the user it was not done.",
- )
- }
- }
-}
+#[path = "security_gate_approval.rs"]
+mod approval;
+use approval::decision_for_outcome;
#[async_trait]
impl SecurityGate for OpenHumanSecurityGate {
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs
new file mode 100644
index 0000000000..0fa11c2ab8
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/host/security_gate_approval.rs
@@ -0,0 +1,63 @@
+//! Approval outcomes projected into runtime gate decisions and model text.
+
+use super::{GateDecision, GateOutcome};
+
+/// What the model is told when the approval prompt for `tool_name` expired
+/// unanswered. Like the refusal text it carries no `[policy-denied]` marker
+/// (see [`decision_for_outcome`]), so the model keeps the turn to tell the
+/// user.
+fn unanswered_approval_text(tool_name: &str) -> String {
+ format!(
+ "The approval request for '{tool_name}' was not answered in time, so it was not run. \
+ Tell the user the approval window expired and that they must ask again to retry. \
+ Do not retry this call yourself this turn and do not achieve the same result another \
+ way (shell, CLI, another tool)."
+ )
+}
+
+/// Maps how the approval flow settled to what the runtime is told.
+///
+/// A refusal is a `Deny` whose text names no human and no timeout — every
+/// refusal reads the same — and rules out other routes explicitly, because
+/// `shell` never prompts while autonomy is disabled (`[autonomy] enabled =
+/// false`, the default) and was used to redo a refused call.
+///
+/// The text carries no `[policy-denied]` marker on purpose. The marker
+/// classifies as a policy failure with a zero recovery budget
+/// (`middleware::repeated_failure`), which pauses the turn before the model can
+/// answer. The model must get this turn to tell the user the action was not
+/// done, as it did with the harness's unmarked fallback text.
+pub(super) fn decision_for_outcome(tool_name: &str, outcome: GateOutcome) -> GateDecision {
+ match outcome {
+ GateOutcome::Allow => GateDecision::Prompted { approved: true },
+ // An expired prompt is not a refusal: nobody answered, and the gate has
+ // now denied the request. Saying so lets the agent (and, for a
+ // sub-agent, its parent) tell the user the approval window expired and
+ // that they must ask again for a new request, rather than that it was
+ // declined — the generic text below left a 600s `media_generate_image`
+ // expiry reported as nothing at all.
+ GateOutcome::Deny { reason }
+ if crate::security::approval::is_unanswered_approval_reason(&reason) =>
+ {
+ tracing::warn!(
+ target: "tinyagents",
+ tool = %tool_name,
+ "[tinyagents::host::security] approval prompt expired unanswered"
+ );
+ GateDecision::deny(unanswered_approval_text(tool_name))
+ }
+ GateOutcome::Deny { reason } => {
+ tracing::warn!(
+ target: "tinyagents",
+ tool = %tool_name,
+ reason = %reason,
+ "[tinyagents::host::security] approval flow declined the tool call"
+ );
+ GateDecision::deny(
+ "This action was refused and must not be performed this turn — do not retry this \
+ call and do not achieve the same result another way (shell, CLI, another tool). \
+ Tell the user it was not done.",
+ )
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs
index eb4ce9f34b..dfde197221 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_policy_class_tests.rs
@@ -183,6 +183,7 @@ async fn a_user_denial_still_stops_on_the_first_refusal() {
// ── the timeout floor, by production tool name ──────────────────────────────
+#[cfg(feature = "modules")]
fn search_spec(name: &str) -> tinysearch_bus::ToolSpec {
tinysearch_bus::ToolSpec {
name: name.to_string(),
@@ -196,7 +197,7 @@ fn search_spec(name: &str) -> tinysearch_bus::ToolSpec {
fn production_read_tools() -> Vec<Box<dyn tinytools::Tool>> {
use crate::security::SecurityPolicy;
let security = std::sync::Arc::new(SecurityPolicy::default());
- let mut tools: Vec<Box<dyn tinytools::Tool>> = vec![
+ let tools: Vec<Box<dyn tinytools::Tool>> = vec![
Box::new(crate::tools::implementations::network::web_fetch_tool(
security.clone(),
vec!["example.com".into()],
@@ -207,16 +208,21 @@ fn production_read_tools() -> Vec<Box<dyn tinytools::Tool>> {
security.clone(),
)),
Box::new(tinytools_std::filesystem::ListFilesTool::new(security)),
- Box::new(crate::desktop::control::tools::DesktopTool::new(
+ ];
+ #[cfg(feature = "modules")]
+ let tools = {
+ let mut tools = tools;
+ tools.push(Box::new(crate::desktop::control::tools::DesktopTool::new(
std::sync::Arc::new(crate::config::Config::default()),
crate::desktop::control::tools::DesktopToolKind::Windows,
- )),
- ];
- for name in ["web_search_tool", "web_answer_tool", "web_contents_tool"] {
- tools.push(Box::new(crate::search::tools::TinySearchTool::recorded(
- search_spec(name),
)));
- }
+ for name in ["web_search_tool", "web_answer_tool", "web_contents_tool"] {
+ tools.push(Box::new(crate::search::tools::TinySearchTool::recorded(
+ search_spec(name),
+ )));
+ }
+ tools
+ };
tools
}
@@ -224,9 +230,13 @@ const PRODUCTION_READ_TOOLS: &[&str] = &[
"web_fetch",
"file_read",
"list_files",
+ #[cfg(feature = "modules")]
"desktop_list_windows",
+ #[cfg(feature = "modules")]
"web_search_tool",
+ #[cfg(feature = "modules")]
"web_answer_tool",
+ #[cfg(feature = "modules")]
"web_contents_tool",
];
diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rs
index 17d494a03c..718bcb55d1 100644
--- a/crates/openhuman-core/src/inference/provider/factory.rs
+++ b/crates/openhuman-core/src/inference/provider/factory.rs
@@ -50,6 +50,7 @@ mod subprocess_providers;
mod tiers;
mod turn_model;
+#[cfg(feature = "flows")]
pub(crate) use access_gates::current_host_requires_session;
pub(crate) use chat_model::resolves_to_managed_backend;
pub use chat_model::{
diff --git a/crates/openhuman-core/src/integrations/composio/catalog.rs b/crates/openhuman-core/src/integrations/composio/catalog.rs
index b507d2aae5..e18f5de5b4 100644
--- a/crates/openhuman-core/src/integrations/composio/catalog.rs
+++ b/crates/openhuman-core/src/integrations/composio/catalog.rs
@@ -40,9 +40,11 @@ mod in_flight_tests;
mod tests;
pub(crate) use contract::fetch_live_toolkit_catalog;
-pub use contract::ToolContract;
#[cfg(test)]
-pub(crate) use contract::{seed_live_catalog_cache, seed_live_catalog_cache_expired};
+pub(crate) use contract::seed_live_catalog_cache;
+#[cfg(all(test, feature = "flows"))]
+pub(crate) use contract::seed_live_catalog_cache_expired;
+pub use contract::ToolContract;
pub(crate) use lookups::composio_required_args;
#[cfg(test)]
pub(crate) use probe::ProbedOutputSample;
diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs
index 115e3c733e..f65400db17 100644
--- a/crates/openhuman-core/src/sandbox/ops.rs
+++ b/crates/openhuman-core/src/sandbox/ops.rs
@@ -171,7 +171,7 @@ pub fn resolve_sandbox_policy(
// The jail denies whatever it is not told about, so a local policy carries
// the toolchain/git grants everyday commands need (see `sandbox::grants`).
let grants = if backend == SandboxBackendKind::Local {
- resolve_local_jail_grants(dirs::home_dir().as_deref(), &runtime_config.local_jail)
+ host_local_jail_grants(runtime_config)
} else {
JailGrants::default()
};
@@ -377,8 +377,7 @@ pub(crate) fn apply_requested_backend(
anyhow::bail!("Landlock sandbox was explicitly requested but is unavailable");
}
if policy.backend != SandboxBackendKind::Local {
- let grants =
- resolve_local_jail_grants(dirs::home_dir().as_deref(), &runtime.local_jail);
+ let grants = host_local_jail_grants(runtime);
policy.read_only_mounts = grants.read_only;
policy.read_write_mounts = grants.read_write;
}
@@ -635,6 +634,27 @@ pub fn is_elevated_op(tool_name: &str) -> bool {
ELEVATED_TOOLS.contains(&tool_name)
}
+fn host_local_jail_grants(runtime: &RuntimeConfig) -> JailGrants {
+ local_jail_grants_with_home(runtime, crate::core::runtime::is_saas(), || {
+ dirs::home_dir()
+ })
+}
+
+// Shared by initial selection and an explicit backend switch. SaaS callers
+// have no operator-home grants, even if the helper is reached directly.
+fn local_jail_grants_with_home(
+ runtime: &RuntimeConfig,
+ saas: bool,
+ home: impl FnOnce() -> Option<PathBuf>,
+) -> JailGrants {
+ let home = if saas { None } else { home() };
+ resolve_local_jail_grants(home.as_deref(), &runtime.local_jail)
+}
+
+#[cfg(test)]
+#[path = "ops_host_grants_tests.rs"]
+mod host_grants_tests;
+
/// Build an `ElevatedOp` for audit logging when a tool bypasses the sandbox.
pub fn build_elevated_op(tool_name: &str, command: &str, reason: &str) -> ElevatedOp {
tracing::info!(
diff --git a/crates/openhuman-core/src/sandbox/ops_host_grants_tests.rs b/crates/openhuman-core/src/sandbox/ops_host_grants_tests.rs
new file mode 100644
index 0000000000..3484e09daa
--- /dev/null
+++ b/crates/openhuman-core/src/sandbox/ops_host_grants_tests.rs
@@ -0,0 +1,25 @@
+use super::*;
+
+#[test]
+fn saas_local_grants_never_consult_the_operator_home() {
+ let runtime = RuntimeConfig::default();
+ let grants = local_jail_grants_with_home(&runtime, true, || {
+ panic!("a tenant must not read the operator's home")
+ });
+ assert!(grants.read_write.is_empty());
+ assert!(grants
+ .read_only
+ .iter()
+ .all(|path| path.starts_with("/usr/local") || path.starts_with("/opt")));
+}
+
+#[test]
+fn single_user_local_grants_keep_the_configured_toolchain_home() {
+ let home = tempfile::tempdir().unwrap();
+ std::fs::create_dir(home.path().join(".rustup")).unwrap();
+ let runtime = RuntimeConfig::default();
+ let grants = local_jail_grants_with_home(&runtime, false, || Some(home.path().to_path_buf()));
+ assert!(grants
+ .read_only
+ .contains(&home.path().join(".rustup").canonicalize().unwrap()));
+}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index 4aa2b2d1fd..9ef28343f0 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -1,5 +1,6 @@
use super::shell_platform::{
- command_param_description, python_utf8_env, shell_child_env, shell_description,
+ command_param_description, command_with_runtime_path, python_utf8_env, shell_child_env,
+ shell_description,
};
use crate::agent::host_runtime::RuntimeAdapter;
use crate::runtime::javascript::NodeBootstrap;
@@ -381,11 +382,19 @@ impl ShellTool {
.await;
}
- // Execute with timeout to prevent hanging commands.
// Clear the environment to prevent leaking API keys and other secrets
// (CWE-200), then re-add only safe, functional variables.
let action_dir = self.effective_action_dir_for_context(context);
- let mut cmd = match self.runtime.build_shell_command(command, &action_dir) {
+ let runtime_path = self.runtime_path_for_command(command).await;
+ let execution_command = command_with_runtime_path(
+ command,
+ runtime_path.as_deref(),
+ self.runtime.shell_flavor(),
+ );
+ let mut cmd = match self
+ .runtime
+ .build_shell_command(&execution_command, &action_dir)
+ {
Ok(cmd) => cmd,
Err(e) => {
return (
@@ -426,7 +435,7 @@ impl ShellTool {
);
}
- if let Some(path) = self.runtime_path_for_command(command).await {
+ if let Some(path) = runtime_path {
tracing::debug!(path = %path, "[shell] applying managed runtime PATH");
cmd.env("PATH", path);
}
@@ -550,7 +559,22 @@ impl ShellTool {
"[shell] starting sandboxed command"
);
- match sandbox::execute_in_sandbox(&policy, command, action_dir, extra_env, effective).await
+ let runtime_path = extra_env
+ .get(std::ffi::OsStr::new("PATH"))
+ .and_then(|path| path.to_str());
+ let execution_command = command_with_runtime_path(
+ command,
+ runtime_path,
+ crate::agent::platform_shell::ShellFlavor::current(),
+ );
+ match sandbox::execute_in_sandbox(
+ &policy,
+ &execution_command,
+ action_dir,
+ extra_env,
+ effective,
+ )
+ .await
{
Ok(result) => {
let tool_result = if result.timed_out {
diff --git a/crates/openhuman-core/src/tools/impl/system/shell_platform.rs b/crates/openhuman-core/src/tools/impl/system/shell_platform.rs
index b0e33a5aa6..8ab0282e80 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_platform.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_platform.rs
@@ -106,3 +106,19 @@ pub(super) fn command_param_description(flavor: ShellFlavor) -> &'static str {
ShellFlavor::Posix => "The shell command to execute",
}
}
+
+/// Restores a managed PATH after POSIX login profiles have run. Ordinary
+/// commands and cmd.exe retain their existing startup/environment behavior.
+pub(super) fn command_with_runtime_path<'a>(
+ command: &'a str,
+ path: Option<&str>,
+ flavor: ShellFlavor,
+) -> std::borrow::Cow<'a, str> {
+ match (path, flavor) {
+ (Some(path), ShellFlavor::Posix) => std::borrow::Cow::Owned(format!(
+ "export PATH='{}'\n{command}",
+ path.replace('\'', "'\\''")
+ )),
+ _ => std::borrow::Cow::Borrowed(command),
+ }
+}
diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs
index d609ca3406..ef4fc9bedc 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs
@@ -122,11 +122,51 @@ fn shell_runtime_failure_logging_accepts_enabled_and_disabled_runtime_states() {
}
#[cfg(unix)]
-fn shell_with_cached_python() -> (ShellTool, tempfile::TempDir) {
+#[derive(Default)]
+struct TrackingNativeRuntime {
+ native: NativeRuntime,
+ builds: std::sync::atomic::AtomicUsize,
+}
+
+#[cfg(unix)]
+impl RuntimeAdapter for TrackingNativeRuntime {
+ fn name(&self) -> &str {
+ self.native.name()
+ }
+ fn has_shell_access(&self) -> bool {
+ self.native.has_shell_access()
+ }
+ fn has_filesystem_access(&self) -> bool {
+ self.native.has_filesystem_access()
+ }
+ fn storage_path(&self) -> std::path::PathBuf {
+ self.native.storage_path()
+ }
+ fn supports_long_running(&self) -> bool {
+ self.native.supports_long_running()
+ }
+ fn build_shell_command(
+ &self,
+ command: &str,
+ workspace: &std::path::Path,
+ ) -> anyhow::Result<tokio::process::Command> {
+ self.builds
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ self.native.build_shell_command(command, workspace)
+ }
+}
+
+#[cfg(unix)]
+fn shell_with_cached_python_using(
+ runtime: Arc<dyn RuntimeAdapter>,
+) -> (ShellTool, tempfile::TempDir) {
use crate::runtime::python::{PythonSource, ResolvedPython};
use std::os::unix::fs::PermissionsExt;
- let bin_dir = tempfile::tempdir().unwrap();
+ let bin_dir = tempfile::Builder::new()
+ .prefix("managed-python's $(false) ")
+ .tempdir()
+ .unwrap();
let python_bin = bin_dir.path().join("python3");
std::fs::write(&python_bin, "#!/bin/sh\necho managed-python-path\n").unwrap();
std::fs::set_permissions(&python_bin, std::fs::Permissions::from_mode(0o755)).unwrap();
@@ -143,7 +183,7 @@ fn shell_with_cached_python() -> (ShellTool, tempfile::TempDir) {
(
ShellTool::with_language_bootstraps(
test_security(AutonomyLevel::Full),
- test_runtime(),
+ runtime,
test_audit(),
None,
Some(python),
@@ -158,7 +198,9 @@ async fn shell_uses_cached_python_path_in_native_mode() {
use crate::agent::harness::definition::SandboxMode;
use crate::agent::harness::with_current_sandbox_mode;
- let (tool, _bin_dir) = shell_with_cached_python();
+ let _env = EnvVarGuard::locked_set_async(crate::sandbox::ops::SANDBOX_OFF_ENV, "off").await;
+ let runtime = Arc::new(TrackingNativeRuntime::default());
+ let (tool, _bin_dir) = shell_with_cached_python_using(runtime.clone());
let result = with_current_sandbox_mode(SandboxMode::None, async {
tool.execute(json!({"command": "python3 -c 'print(1)'"}))
.await
@@ -171,6 +213,11 @@ async fn shell_uses_cached_python_path_in_native_mode() {
result.output()
);
assert!(result.output().contains("managed-python-path"));
+ assert_eq!(
+ runtime.builds.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "native execution must use the instrumented runtime adapter"
+ );
}
#[tokio::test]
@@ -194,7 +241,9 @@ async fn shell_sandboxed_mode_routes_through_sandbox_backend() {
use crate::agent::harness::definition::SandboxMode;
use crate::agent::harness::with_current_sandbox_mode;
- let (tool, _bin_dir) = shell_with_cached_python();
+ let _env = EnvVarGuard::locked_set_async(crate::sandbox::ops::SANDBOX_OFF_ENV, "on").await;
+ let runtime = Arc::new(TrackingNativeRuntime::default());
+ let (tool, _bin_dir) = shell_with_cached_python_using(runtime.clone());
let result = with_current_sandbox_mode(SandboxMode::Sandboxed, async {
tool.execute(json!({"command": "python3 -c 'print(1)'"}))
.await
@@ -211,20 +260,17 @@ async fn shell_sandboxed_mode_routes_through_sandbox_backend() {
"expected managed Python PATH in result, got: {:?}",
result.output()
);
+ assert_eq!(
+ runtime.builds.load(std::sync::atomic::Ordering::SeqCst),
+ 0,
+ "sandboxed execution must bypass the tool's native runtime adapter"
+ );
}
-/// Regression guard for #3235 (cwd_jail wiring for shell-family tools).
-///
-/// PR #3261 wired `ShellTool` to route through `sandbox::execute_in_sandbox`
-/// (which uses `cwd_jail` for the local-OS-jail backend) when the
-/// active agent's `SandboxMode::Sandboxed` is set. This PR extends the
-/// same wiring to `NodeExecTool` and `NpmExecTool`. The behavioural
-/// `shell_sandboxed_mode_routes_through_sandbox_backend` test above
-/// proves the contract end-to-end for `shell` (no managed-Node
-/// dependency); `node_exec` and `npm_exec` cannot run end-to-end in
-/// unit tests without a resolved `NodeBootstrap`, so this source-grep
-/// guard catches refactors that drop the sandbox check from either
-/// tool's `execute()` body.
+/// Shell-family callers must use the shared routing decision, which covers
+/// both an agent's sandbox mode and an explicit operator backend. The test
+/// above executes a command and proves it bypasses the native runtime adapter;
+/// this guard covers Node/npm call sites without downloading their runtimes.
#[test]
fn shell_family_tools_route_to_sandbox_when_sandboxed_mode_active() {
const SHELL_SRC: &str = include_str!("shell.rs");
@@ -237,14 +283,8 @@ fn shell_family_tools_route_to_sandbox_when_sandboxed_mode_active() {
("npm_exec.rs", NPM_EXEC_SRC),
] {
assert!(
- src.contains("current_sandbox_mode()"),
- "{name} must check `current_sandbox_mode()` to detect SandboxMode::Sandboxed \
- sessions and route through the sandbox backend (see #3235)"
- );
- assert!(
- src.contains("SandboxMode::Sandboxed"),
- "{name} must compare against `SandboxMode::Sandboxed` to opt in to the \
- sandbox routing path (see #3235)"
+ src.contains("command_requires_sandbox().await"),
+ "{name} must use the shared command sandbox routing policy, including agent mode and operator backend"
);
// Use the call-site pattern `.run_sandboxed(` so the assertion
// doesn't trivially pass on the helper definition itself
@@ -258,3 +298,18 @@ fn shell_family_tools_route_to_sandbox_when_sandboxed_mode_active() {
);
}
}
+
+#[test]
+fn managed_path_restoration_preserves_cmd_syntax_and_unmanaged_commands() {
+ use crate::agent::platform_shell::ShellFlavor;
+ let windows_command = "echo %USERPROFILE%";
+ assert_eq!(
+ command_with_runtime_path(windows_command, Some("C:\\managed\\bin"), ShellFlavor::Cmd),
+ windows_command
+ );
+ let unmanaged_command = "echo \"$PATH\"";
+ assert_eq!(
+ command_with_runtime_path(unmanaged_command, None, ShellFlavor::Posix),
+ unmanaged_command
+ );
+}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 2562dfe23c..51c8ab8a7b 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -969,240 +969,9 @@ pub fn all_tools_with_runtime(
tools
}
-/// Classify an agent tool into its [`DomainGroup`](crate::core::all::DomainGroup)
-/// by its `name()`, so [`all_tools_with_runtime`] can drop tools whose family is
-/// disabled under the ambient [`DomainSet`](crate::core::runtime::DomainSet).
-///
-/// Named-family tools are matched here; everything without a domain family
-/// defaults to `Platform`. Under `harness()`, the Agent/Memory/Threads/Config/
-/// Security tools remain while gate-family and generic Platform tools drop.
-/// (Names verified against each Tool impl's `fn name()` on 2026-07-13.)
-pub(crate) fn tool_group(name: &str) -> crate::core::all::DomainGroup {
- use crate::core::all::DomainGroup;
-
- // Gate families with a domain-exclusive name prefix are matched by prefix
- // (not an exact list) so a NEW tool in the family auto-gates instead of
- // silently defaulting to Platform and leaking under a custom DomainSet
- // (#4808 maintainer review). Web3 = wallet_/web3_/x402_, Media = media_,
- // Mcp = mcp_ (below). Families without a clean prefix (Skills/Flows) keep
- // their exact lists; `no_gate_family_tool_silently_defaults_to_platform`
- // guards the prefix families.
- const SKILLS: &[&str] = &[
- "run_workflow",
- "await_workflow",
- "list_workflows",
- "create_skill",
- "describe_workflow",
- "read_workflow_resource",
- "list_workflow_runs",
- "read_workflow_run_log",
- "install_workflow_from_url",
- "uninstall_workflow",
- "skill_registry_browse",
- "skill_registry_search",
- "skill_registry_install",
- "skill_registry_sources",
- "skill_registry_uninstall",
- "skill_runtime_resolve_runtimes",
- ];
- // Flows has no clean tool-name prefix, so it MUST list every flow-owned
- // tool explicitly — a missing name falls through to `Platform` below and
- // stays callable under a custom `DomainSet { platform: true, flows: false }`,
- // leaking the flows surface past the runtime gate (#4808 review; #4797
- // maintainer review). Keep this in lockstep with the `#[cfg(feature =
- // "flows")]` registrations in `all_tools_with_runtime` above — the same 28
- // names asserted by `default_tools_omits_flows_tools_when_feature_off`.
- const FLOWS: &[&str] = &[
- "propose_workflow",
- "revise_workflow",
- "edit_workflow",
- "validate_workflow",
- "get_flow_history",
- "dry_run_workflow",
- "save_workflow",
- "suggest_workflows",
- "run_flow",
- "list_flow_runs",
- "resume_flow_run",
- "cancel_flow_run",
- "create_workflow",
- "duplicate_flow",
- "list_flows",
- "get_flow",
- "get_flow_run",
- "list_flow_connections",
- "search_tool_catalog",
- "get_tool_contract",
- "get_tool_output_sample",
- "list_agent_definitions",
- "list_connectable_toolkits",
- "list_node_kinds",
- "get_node_kind_contract",
- // Per-flow sandboxed memory (issue #5173) — `flow_` prefixed, not
- // `memory_`, so it does NOT fall under the `memory_` prefix check
- // below and must be listed here explicitly like every other
- // flow-owned tool.
- "flow_memory_recall",
- "flow_memory_remember",
- ];
- // Voice family agent tools (audio_toolkit) — no `voice_`/`tts_`/`stt_`
- // prefix, so they must be listed explicitly or they fall through to
- // Platform and stay callable when Voice is gated off (#4808 review).
- const VOICE: &[&str] = &[
- "audio_generate_podcast",
- "audio_email_podcast",
- "audio_generate_and_email_podcast",
- ];
- // Threads: thread_* / todo_* handled by prefix below; these are the extras.
- // Monitor + proactive-notify tools (Automation family).
- const MONITORS: &[&str] = &[
- "monitor",
- "monitor_list",
- "monitor_read",
- "monitor_stop",
- "notify_user",
- ];
- const THREADS_EXTRA: &[&str] = &["goal_get", "goal_set", "goal_complete"];
-
- // MCP: every MCP tool name is `mcp_` prefixed (mcp_registry_*,
- // mcp_call_tool, mcp_list_servers, mcp_list_tools).
- if name.starts_with("mcp_") {
- return DomainGroup::Mcp;
- }
- // Web3: wallet_/web3_/x402_ are all Web3-exclusive prefixes.
- if name.starts_with("wallet_") || name.starts_with("web3_") || name.starts_with("x402_") {
- return DomainGroup::Web3;
- }
- if SKILLS.contains(&name) {
- return DomainGroup::Skills;
- }
- if FLOWS.contains(&name) {
- return DomainGroup::Flows;
- }
- // Media generation: `media_` prefix (media_generate_image/video, media_list_models).
- if name.starts_with("media_") {
- return DomainGroup::Media;
- }
- // Voice family: explicit audio_* podcast tools plus the defensive
- // voice_/tts_/stt_ prefixes for any future tool.
- if VOICE.contains(&name)
- || name.starts_with("voice_")
- || name.starts_with("tts_")
- || name.starts_with("stt_")
- {
- return DomainGroup::Voice;
- }
- // Memory family (harness-kept): the single `memory` tool.
- if name == crate::memory::MEMORY_TOOL_NAME {
- return DomainGroup::Memory;
- }
- // Threads family (harness-kept): thread_* + per-thread goal + search.
- // `thread_` is kept as a prefix even though the `thread_*` agent-tool
- // family was removed: `goal_*` and the THREADS_EXTRA entries still
- // classify here, and a future threads tool should land in Threads rather
- // than falling through to Platform.
- if name.starts_with("thread_") || THREADS_EXTRA.contains(&name) {
- return DomainGroup::Threads;
- }
- // Harness families realigned out of Platform.
- if name.starts_with("artifact_")
- || name.starts_with("learning_")
- || name.contains("subagent")
- || matches!(
- name,
- "ask_user_clarification"
- | "delegate"
- | "delegate_graph"
- | "delegate_to_personality"
- | "todo"
- | "wait"
- | "wait_loop"
- | "request_plan_review"
- | "plan_exit"
- | "spawn_parallel_agents"
- )
- {
- return DomainGroup::Agent;
- }
- if name.starts_with("config_") || name.starts_with("workspace_") {
- return DomainGroup::Config;
- }
- if name.starts_with("security_")
- || name.starts_with("credential_")
- || name.starts_with("session_")
- || name.starts_with("oauth_")
- {
- return DomainGroup::Security;
- }
- // ── Families carved out of Platform by the DomainGroup realignment ──────
- // Each of these previously fell through to Platform, which meant the tool
- // stayed callable when its family was gated off under a custom DomainSet —
- // leak the #4808 review flagged. Keep these in
- // lockstep with the `push(...)` tags in `core::all`.
- //
- // Automation: scheduled jobs (`cron_*`) plus the monitor +
- // proactive-notify surface.
- if name.starts_with("cron_") || name == "schedule" || MONITORS.contains(&name) {
- return DomainGroup::Automation;
- }
- // Integrations: every external connector reached on the user's behalf.
- if name.starts_with("composio")
- || name == "web_search_tool"
- || name == "web_answer_tool"
- || name == "web_contents_tool"
- || name == "search"
- || name.starts_with("tinyfish_")
- || name.starts_with("exa_")
- || name.starts_with("gemini_")
- || name.starts_with("parallel_")
- || name.starts_with("brave_")
- || name.starts_with("querit_")
- || name.starts_with("tavily_")
- || name.starts_with("seltz_")
- || name.starts_with("searxng_")
- || name.starts_with("google_places_")
- || name.starts_with("stock_")
- || name.starts_with("storage_")
- || name.starts_with("task_source_")
- || name == "twilio_call"
- // Hosting: `hosting_` is a domain-exclusive prefix, so a NEW hosting
- // tool auto-gates rather than falling through to Platform and staying
- // callable under a custom DomainSet. `hosting_launch_site` uploads a
- // workspace directory to a third party and can provision a paid
- // database, so it must not outlive its family's gate.
- || name.starts_with("hosting_")
- {
- return DomainGroup::Integrations;
- }
- // Hosted: clients of the TinyHumans backend. The `billing_` / `team_` /
- // `referral_` prefixes were removed with those agent-tool families; their
- // controllers stay registered for the dashboard, which does not route
- // through this classifier.
- if name.starts_with("orchestration_") {
- return DomainGroup::Hosted;
- }
- // Desktop: shell-facing surfaces.
- if name.starts_with("dashboard_") || name.starts_with("desktop_") {
- return DomainGroup::Desktop;
- }
- // Runtimes: the managed Node/Python execution tools. These live under
- // `tools/impl/system/` rather than `runtime/`, so they are matched by name.
- if name == "node_exec" || name == "npm_exec" || name == "python_exec" {
- return DomainGroup::Runtimes;
- }
- // Inference: the CCR retrieval surface. Matched against the crate's own
- // constant list rather than a name prefix — the live tool is
- // `juice_retrieve`, and `tokenjuice_retrieve` / `retrieve_tool_output`
- // are migration aliases, so a prefix rule silently missed the real one.
- if crate::inference::tokenjuice::RECOVERY_TOOL_NAMES.contains(&name)
- || crate::inference::tokenjuice::is_repl_tool(name)
- {
- return DomainGroup::Inference;
- }
- // Everything else — shell/file and other kernel utilities — is Platform:
- // present under full(), absent under harness()/none().
- DomainGroup::Platform
-}
+#[path = "ops_tool_groups.rs"]
+mod tool_groups;
+pub(crate) use tool_groups::tool_group;
#[cfg(test)]
#[path = "ops_tests.rs"]
diff --git a/crates/openhuman-core/src/tools/ops_tool_groups.rs b/crates/openhuman-core/src/tools/ops_tool_groups.rs
new file mode 100644
index 0000000000..bf00e0809e
--- /dev/null
+++ b/crates/openhuman-core/src/tools/ops_tool_groups.rs
@@ -0,0 +1,236 @@
+//! Domain-family classification used to filter the callable tool catalog.
+
+/// Classify an agent tool into its [`DomainGroup`](crate::core::all::DomainGroup)
+/// by its `name()`, so [`all_tools_with_runtime`](super::all_tools_with_runtime) can drop tools whose family is
+/// disabled under the ambient [`DomainSet`](crate::core::runtime::DomainSet).
+///
+/// Named-family tools are matched here; everything without a domain family
+/// defaults to `Platform`. Under `harness()`, the Agent/Memory/Threads/Config/
+/// Security tools remain while gate-family and generic Platform tools drop.
+/// (Names verified against each Tool impl's `fn name()` on 2026-07-13.)
+pub(crate) fn tool_group(name: &str) -> crate::core::all::DomainGroup {
+ use crate::core::all::DomainGroup;
+
+ // Gate families with a domain-exclusive name prefix are matched by prefix
+ // (not an exact list) so a NEW tool in the family auto-gates instead of
+ // silently defaulting to Platform and leaking under a custom DomainSet
+ // (#4808 maintainer review). Web3 = wallet_/web3_/x402_, Media = media_,
+ // Mcp = mcp_ (below). Families without a clean prefix (Skills/Flows) keep
+ // their exact lists; `no_gate_family_tool_silently_defaults_to_platform`
+ // guards the prefix families.
+ const SKILLS: &[&str] = &[
+ "run_workflow",
+ "await_workflow",
+ "list_workflows",
+ "create_skill",
+ "describe_workflow",
+ "read_workflow_resource",
+ "list_workflow_runs",
+ "read_workflow_run_log",
+ "install_workflow_from_url",
+ "uninstall_workflow",
+ "skill_registry_browse",
+ "skill_registry_search",
+ "skill_registry_install",
+ "skill_registry_sources",
+ "skill_registry_uninstall",
+ "skill_runtime_resolve_runtimes",
+ ];
+ // Flows has no clean tool-name prefix, so it MUST list every flow-owned
+ // tool explicitly — a missing name falls through to `Platform` below and
+ // stays callable under a custom `DomainSet { platform: true, flows: false }`,
+ // leaking the flows surface past the runtime gate (#4808 review; #4797
+ // maintainer review). Keep this in lockstep with the `#[cfg(feature =
+ // "flows")]` registrations in `all_tools_with_runtime` above — the same 28
+ // names asserted by `default_tools_omits_flows_tools_when_feature_off`.
+ const FLOWS: &[&str] = &[
+ "propose_workflow",
+ "revise_workflow",
+ "edit_workflow",
+ "validate_workflow",
+ "get_flow_history",
+ "dry_run_workflow",
+ "save_workflow",
+ "suggest_workflows",
+ "run_flow",
+ "list_flow_runs",
+ "resume_flow_run",
+ "cancel_flow_run",
+ "create_workflow",
+ "duplicate_flow",
+ "list_flows",
+ "get_flow",
+ "get_flow_run",
+ "list_flow_connections",
+ "search_tool_catalog",
+ "get_tool_contract",
+ "get_tool_output_sample",
+ "list_agent_definitions",
+ "list_connectable_toolkits",
+ "list_node_kinds",
+ "get_node_kind_contract",
+ // Per-flow sandboxed memory (issue #5173) — `flow_` prefixed, not
+ // `memory_`, so it does NOT fall under the `memory_` prefix check
+ // below and must be listed here explicitly like every other
+ // flow-owned tool.
+ "flow_memory_recall",
+ "flow_memory_remember",
+ ];
+ // Voice family agent tools (audio_toolkit) — no `voice_`/`tts_`/`stt_`
+ // prefix, so they must be listed explicitly or they fall through to
+ // Platform and stay callable when Voice is gated off (#4808 review).
+ const VOICE: &[&str] = &[
+ "audio_generate_podcast",
+ "audio_email_podcast",
+ "audio_generate_and_email_podcast",
+ ];
+ // Threads: thread_* / todo_* handled by prefix below; these are the extras.
+ // Monitor + proactive-notify tools (Automation family).
+ const MONITORS: &[&str] = &[
+ "monitor",
+ "monitor_list",
+ "monitor_read",
+ "monitor_stop",
+ "notify_user",
+ ];
+ const THREADS_EXTRA: &[&str] = &["goal_get", "goal_set", "goal_complete"];
+
+ // MCP: every MCP tool name is `mcp_` prefixed (mcp_registry_*,
+ // mcp_call_tool, mcp_list_servers, mcp_list_tools).
+ if name.starts_with("mcp_") {
+ return DomainGroup::Mcp;
+ }
+ // Web3: wallet_/web3_/x402_ are all Web3-exclusive prefixes.
+ if name.starts_with("wallet_") || name.starts_with("web3_") || name.starts_with("x402_") {
+ return DomainGroup::Web3;
+ }
+ if SKILLS.contains(&name) {
+ return DomainGroup::Skills;
+ }
+ if FLOWS.contains(&name) {
+ return DomainGroup::Flows;
+ }
+ // Media generation: `media_` prefix (media_generate_image/video, media_list_models).
+ if name.starts_with("media_") {
+ return DomainGroup::Media;
+ }
+ // Voice family: explicit audio_* podcast tools plus the defensive
+ // voice_/tts_/stt_ prefixes for any future tool.
+ if VOICE.contains(&name)
+ || name.starts_with("voice_")
+ || name.starts_with("tts_")
+ || name.starts_with("stt_")
+ {
+ return DomainGroup::Voice;
+ }
+ // Memory family (harness-kept): the single `memory` tool.
+ if name == crate::memory::MEMORY_TOOL_NAME {
+ return DomainGroup::Memory;
+ }
+ // Threads family (harness-kept): thread_* + per-thread goal + search.
+ // `thread_` is kept as a prefix even though the `thread_*` agent-tool
+ // family was removed: `goal_*` and the THREADS_EXTRA entries still
+ // classify here, and a future threads tool should land in Threads rather
+ // than falling through to Platform.
+ if name.starts_with("thread_") || THREADS_EXTRA.contains(&name) {
+ return DomainGroup::Threads;
+ }
+ // Harness families realigned out of Platform.
+ if name.starts_with("artifact_")
+ || name.starts_with("learning_")
+ || name.contains("subagent")
+ || matches!(
+ name,
+ "ask_user_clarification"
+ | "delegate"
+ | "delegate_graph"
+ | "delegate_to_personality"
+ | "todo"
+ | "wait"
+ | "wait_loop"
+ | "request_plan_review"
+ | "plan_exit"
+ | "spawn_parallel_agents"
+ )
+ {
+ return DomainGroup::Agent;
+ }
+ if name.starts_with("config_") || name.starts_with("workspace_") {
+ return DomainGroup::Config;
+ }
+ if name.starts_with("security_")
+ || name.starts_with("credential_")
+ || name.starts_with("session_")
+ || name.starts_with("oauth_")
+ {
+ return DomainGroup::Security;
+ }
+ // ── Families carved out of Platform by the DomainGroup realignment ──────
+ // Each of these previously fell through to Platform, which meant the tool
+ // stayed callable when its family was gated off under a custom DomainSet —
+ // leak the #4808 review flagged. Keep these in
+ // lockstep with the `push(...)` tags in `core::all`.
+ //
+ // Automation: scheduled jobs (`cron_*`) plus the monitor +
+ // proactive-notify surface.
+ if name.starts_with("cron_") || name == "schedule" || MONITORS.contains(&name) {
+ return DomainGroup::Automation;
+ }
+ // Integrations: every external connector reached on the user's behalf.
+ if name.starts_with("composio")
+ || name == "web_search_tool"
+ || name == "web_answer_tool"
+ || name == "web_contents_tool"
+ || name == "search"
+ || name.starts_with("tinyfish_")
+ || name.starts_with("exa_")
+ || name.starts_with("gemini_")
+ || name.starts_with("parallel_")
+ || name.starts_with("brave_")
+ || name.starts_with("querit_")
+ || name.starts_with("tavily_")
+ || name.starts_with("seltz_")
+ || name.starts_with("searxng_")
+ || name.starts_with("google_places_")
+ || name.starts_with("stock_")
+ || name.starts_with("storage_")
+ || name.starts_with("task_source_")
+ || name == "twilio_call"
+ // Hosting: `hosting_` is a domain-exclusive prefix, so a NEW hosting
+ // tool auto-gates rather than falling through to Platform and staying
+ // callable under a custom DomainSet. `hosting_launch_site` uploads a
+ // workspace directory to a third party and can provision a paid
+ // database, so it must not outlive its family's gate.
+ || name.starts_with("hosting_")
+ {
+ return DomainGroup::Integrations;
+ }
+ // Hosted: clients of the TinyHumans backend. The `billing_` / `team_` /
+ // `referral_` prefixes were removed with those agent-tool families; their
+ // controllers stay registered for the dashboard, which does not route
+ // through this classifier.
+ if name.starts_with("orchestration_") {
+ return DomainGroup::Hosted;
+ }
+ // Desktop: shell-facing surfaces.
+ if name.starts_with("dashboard_") || name.starts_with("desktop_") {
+ return DomainGroup::Desktop;
+ }
+ // Runtimes: the managed Node/Python execution tools. These live under
+ // `tools/impl/system/` rather than `runtime/`, so they are matched by name.
+ if name == "node_exec" || name == "npm_exec" || name == "python_exec" {
+ return DomainGroup::Runtimes;
+ }
+ // Inference: the CCR retrieval surface. Matched against the crate's own
+ // constant list rather than a name prefix — the live tool is
+ // `juice_retrieve`, and `tokenjuice_retrieve` / `retrieve_tool_output`
+ // are migration aliases, so a prefix rule silently missed the real one.
+ if crate::inference::tokenjuice::RECOVERY_TOOL_NAMES.contains(&name)
+ || crate::inference::tokenjuice::is_repl_tool(name)
+ {
+ return DomainGroup::Inference;
+ }
+ // Everything else — shell/file and other kernel utilities — is Platform:
+ // present under full(), absent under harness()/none().
+ DomainGroup::Platform
+}
diff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rs
index 3cbca07b5b..b2b3b92c40 100644
--- a/crates/openhuman-core/src/web_chat/mod.rs
+++ b/crates/openhuman-core/src/web_chat/mod.rs
@@ -98,6 +98,7 @@ pub(crate) use ops::sentry_suppression_reason;
pub(crate) use ops::{event_session_id_for, key_for};
#[cfg(test)]
pub(crate) use ops::{key_in, unscope_in};
+#[cfg(feature = "flows")]
pub(crate) use progress_bridge::spawn_progress_bridge;
// Schema field helpers + session/error helpers re-exported for the `web_tests`
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index bfd5dcb206..ffefc831e5 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -159,56 +159,11 @@ pub fn unix_epoch_ms() -> u64 {
.unwrap_or(0)
}
-/// Upper bound on the sub-agent tool output forwarded to the drawer over
-/// Socket.IO. The `SubagentToolCallCompleted` event carries the *pre-handoff*
-/// tool result (the result-handoff path that stashes large toolkit payloads
-/// behind a short placeholder runs later, in `SubagentToolSource`), so a raw
-/// multi-MB integration result would otherwise ship in full to the socket /
-/// Redux / DOM. Cap it here on a UTF-8 boundary with a truncation marker so the
-/// drawer payload stays bounded while still showing what the tool returned.
-const MAX_WIRE_SUBAGENT_OUTPUT: usize = 256 * 1024;
-
-/// Bytes reserved within the cap for the truncation marker so the *final*
-/// payload (content + marker) never exceeds [`MAX_WIRE_SUBAGENT_OUTPUT`].
-/// Generous upper bound for `…[truncated <N> bytes of tool output]` at any
-/// plausible `N` (the "…" is 3 UTF-8 bytes).
-const TRUNCATION_MARKER_BUDGET: usize = 80;
-
-/// Truncate `output` so the returned string stays within
-/// [`MAX_WIRE_SUBAGENT_OUTPUT`] bytes, slicing on a char boundary and
-/// appending a marker (which is itself counted against the cap) when content
-/// was dropped. Returns the input unchanged when it's already within the cap.
-fn cap_wire_output(output: String) -> String {
- if output.len() <= MAX_WIRE_SUBAGENT_OUTPUT {
- return output;
- }
- let mut end = MAX_WIRE_SUBAGENT_OUTPUT.saturating_sub(TRUNCATION_MARKER_BUDGET);
- while end > 0 && !output.is_char_boundary(end) {
- end -= 1;
- }
- let omitted = output.len() - end;
- format!(
- "{}\n…[truncated {omitted} bytes of tool output]",
- &output[..end]
- )
-}
-
-/// Cap a tool call's forwarded `args`/input payload the same way
-/// [`cap_wire_output`] caps tool output: a captured argument (e.g. a large
-/// inline file body) must never ship megabytes over the socket. Truncation
-/// only ever produces a marker string; it never re-nests as JSON, since the
-/// wire consumer only needs to know the payload was too big to show in full.
-fn cap_wire_args(args: Option<serde_json::Value>) -> Option<serde_json::Value> {
- let value = args?;
- if value.is_null() {
- return None;
- }
- let rendered = value.to_string();
- if rendered.len() <= MAX_WIRE_SUBAGENT_OUTPUT {
- return Some(value);
- }
- Some(serde_json::Value::String(cap_wire_output(rendered)))
-}
+#[path = "progress_bridge_wire_caps.rs"]
+mod wire_caps;
+#[cfg(test)]
+use wire_caps::MAX_WIRE_SUBAGENT_OUTPUT;
+use wire_caps::{cap_wire_args, cap_wire_output};
pub(super) fn ledger_upsert_agent_run(
config: &crate::config::Config,
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_wire_caps.rs b/crates/openhuman-core/src/web_chat/progress_bridge_wire_caps.rs
new file mode 100644
index 0000000000..4d1ec4bce9
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_wire_caps.rs
@@ -0,0 +1,52 @@
+//! Bounded socket payloads for delegated tool inputs and outputs.
+
+/// Upper bound on the sub-agent tool output forwarded to the drawer over
+/// Socket.IO. The `SubagentToolCallCompleted` event carries the *pre-handoff*
+/// tool result (the result-handoff path that stashes large toolkit payloads
+/// behind a short placeholder runs later, in `SubagentToolSource`), so a raw
+/// multi-MB integration result would otherwise ship in full to the socket /
+/// Redux / DOM. Cap it here on a UTF-8 boundary with a truncation marker so the
+/// drawer payload stays bounded while still showing what the tool returned.
+pub(super) const MAX_WIRE_SUBAGENT_OUTPUT: usize = 256 * 1024;
+
+/// Bytes reserved within the cap for the truncation marker so the *final*
+/// payload (content + marker) never exceeds [`MAX_WIRE_SUBAGENT_OUTPUT`].
+/// Generous upper bound for `…[truncated <N> bytes of tool output]` at any
+/// plausible `N` (the "…" is 3 UTF-8 bytes).
+const TRUNCATION_MARKER_BUDGET: usize = 80;
+
+/// Truncate `output` so the returned string stays within
+/// [`MAX_WIRE_SUBAGENT_OUTPUT`] bytes, slicing on a char boundary and
+/// appending a marker (which is itself counted against the cap) when content
+/// was dropped. Returns the input unchanged when it's already within the cap.
+pub(super) fn cap_wire_output(output: String) -> String {
+ if output.len() <= MAX_WIRE_SUBAGENT_OUTPUT {
+ return output;
+ }
+ let mut end = MAX_WIRE_SUBAGENT_OUTPUT.saturating_sub(TRUNCATION_MARKER_BUDGET);
+ while end > 0 && !output.is_char_boundary(end) {
+ end -= 1;
+ }
+ let omitted = output.len() - end;
+ format!(
+ "{}\n…[truncated {omitted} bytes of tool output]",
+ &output[..end]
+ )
+}
+
+/// Cap a tool call's forwarded `args`/input payload the same way
+/// [`cap_wire_output`] caps tool output: a captured argument (e.g. a large
+/// inline file body) must never ship megabytes over the socket. Truncation
+/// only ever produces a marker string; it never re-nests as JSON, since the
+/// wire consumer only needs to know the payload was too big to show in full.
+pub(super) fn cap_wire_args(args: Option<serde_json::Value>) -> Option<serde_json::Value> {
+ let value = args?;
+ if value.is_null() {
+ return None;
+ }
+ let rendered = value.to_string();
+ if rendered.len() <= MAX_WIRE_SUBAGENT_OUTPUT {
+ return Some(value);
+ }
+ Some(serde_json::Value::String(cap_wire_output(rendered)))
+}
diff --git a/crates/openhuman-embed/tests/isolation_autonomy.rs b/crates/openhuman-embed/tests/isolation_autonomy.rs
index 5f7b6b5345..941ef82dfc 100644
--- a/crates/openhuman-embed/tests/isolation_autonomy.rs
+++ b/crates/openhuman-embed/tests/isolation_autonomy.rs
@@ -8,8 +8,8 @@
mod common;
use common::{
- eventually, offline_config, route, runtime, scripted_provider, stub_backend,
- tool_call_completion,
+ chat_requests, eventually, offline_config, route, runtime, scripted_provider, stub_backend,
+ tool_call_completion, tool_results,
};
use openhuman_core::security::AutonomyLevel;
use openhuman_embed::{
@@ -73,10 +73,18 @@ fn every_agent_answers_policy_from_its_own_tier() {
assert_eq!(a.config().autonomy.level, AutonomyLevel::ReadOnly);
let a_out = a.run("write the marker").await.expect("a's turn returns");
assert!(!a_file.exists(), "a read-only agent must not write");
+ // A refused tool call is fed back to the model; the final reply
+ // comes from the provider and need not repeat the policy error.
+ let a_requests = chat_requests(&a_provider).await;
assert!(
- a_out.reply.contains("read-only mode"),
- "a's shell call is refused by its own tier: {}",
- a_out.reply
+ a_requests
+ .iter()
+ .any(|request| tool_results(request).contains("read-only mode")),
+ "a's tool result must report refusal by its own read-only tier"
+ );
+ assert_eq!(
+ a_out.reply, "a-done",
+ "the model continues after the refused write"
);
// ── B: supervised, shell on its own allowlist; runs without parking ──
diff --git a/scripts/__tests__/runtime-boundary-types.test.mjs b/scripts/__tests__/runtime-boundary-types.test.mjs
new file mode 100644
index 0000000000..1cda6c5fbd
--- /dev/null
+++ b/scripts/__tests__/runtime-boundary-types.test.mjs
@@ -0,0 +1,77 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { isClaudeCodeBridgeMessage } from "../lib/runtime-boundary-types.mjs";
+
+const root =
+ "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/";
+const neutral =
+ "pub(crate) struct ChatMessage { pub(crate) role: String, pub(crate) content: String, }";
+
+test("recognizes only the reviewed neutral provider message", () => {
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ `${root}input_builder.rs`,
+ "ChatMessage",
+ neutral,
+ ),
+ true,
+ );
+ assert.equal(
+ isClaudeCodeBridgeMessage(`${root}driver_tests.rs`, "ChatMessage", neutral),
+ true,
+ );
+});
+
+test("product record fields cannot inherit the provider exception", () => {
+ const product = neutral.replace(
+ "content: String,",
+ "content: String, pub(crate) thread_id: String,",
+ );
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ `${root}input_builder.rs`,
+ "ChatMessage",
+ product,
+ ),
+ false,
+ );
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ `${root}input_builder.rs`,
+ "AgentProgress",
+ neutral,
+ ),
+ false,
+ );
+});
+
+test("other crates and provider modules keep the domain-type rule", () => {
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ "vendor/tinyagents/crates/tinyagents-session/src/mod.rs",
+ "ChatMessage",
+ neutral,
+ ),
+ false,
+ );
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ root.replace("claude_code/", "claude_agent_sdk/") + "mod.rs",
+ "ChatMessage",
+ neutral,
+ ),
+ false,
+ );
+});
+
+test("qualified product imports are never treated as the neutral DTO", () => {
+ assert.equal(
+ isClaudeCodeBridgeMessage(
+ `${root}input_builder.rs`,
+ "ChatMessage",
+ neutral,
+ "use openhuman_core::ChatMessage;",
+ ),
+ false,
+ );
+});
diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json
index 82f0aa33ca..3319659205 100644
--- a/scripts/ci/agent-runtime-boundary-baseline.json
+++ b/scripts/ci/agent-runtime-boundary-baseline.json
@@ -23,28 +23,35 @@
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/subagent_host/ops/graph/dispatch.rs",
- "line": 198,
+ "line": 199,
"text": "let run_result = Box::pin(run_turn_via_tinyagents_shared(",
"occurrence": 1
},
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs",
- "line": 74,
+ "line": 77,
"text": "assemble_turn_harness(",
"occurrence": 1
},
+ {
+ "rule": "openhuman-runtime-bridge",
+ "path": "crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs",
+ "line": 195,
+ "text": "let assembled = assemble_turn_harness(",
+ "occurrence": 1
+ },
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs",
- "line": 110,
+ "line": 52,
"text": "pub(super) fn assemble_turn_harness(",
"occurrence": 1
},
{
"rule": "openhuman-runtime-bridge",
"path": "crates/openhuman-core/src/agent/tinyagents/mod.rs",
- "line": 95,
+ "line": 98,
"text": "pub(crate) use turn_runner::{run_root_turn_via_hosted_agent, run_turn_via_tinyagents_shared};",
"occurrence": 1
},
@@ -332,7 +339,7 @@
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",
"line": 424,
- "text": "let join = tokio::spawn(crate::agent::turn_origin::propagate(",
+ "text": "let join = crate::core::runtime::spawn_scoped(crate::agent::turn_origin::propagate(",
"occurrence": 1
},
{
@@ -429,7 +436,7 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/session_host/runtime_session.rs",
- "line": 665,
+ "line": 669,
"text": "workspace_descriptor: crate::agent::harness::current_parent()",
"occurrence": 1
},
@@ -471,24 +478,31 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/subagent_host/ops/runner.rs",
- "line": 255,
+ "line": 235,
"text": ".max(current_spawn_depth().saturating_add(1));",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/subagent_host/ops/runner.rs",
- "line": 360,
+ "line": 340,
"text": "let run_result = Box::pin(with_spawn_depth(attempted_depth, async {",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/subagent_host/ops/runner.rs",
- "line": 362,
+ "line": 342,
"text": "with_current_sandbox_mode(definition.sandbox_mode, async {",
"occurrence": 1
},
+ {
+ "rule": "openhuman-task-local",
+ "path": "crates/openhuman-core/src/agent/tinyagents/host/security_gate.rs",
+ "line": 526,
+ "text": "crate::agent::turn_origin::current(),",
+ "occurrence": 1
+ },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/tools/delegate.rs",
@@ -590,7 +604,7 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/channels/proactive.rs",
- "line": 305,
+ "line": 306,
"text": "let (outcome, request_id) = crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
@@ -772,7 +786,7 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/inference/provider/openhuman_backend_model_calls.rs",
- "line": 81,
+ "line": 78,
"text": "with_thread_id(apply_reasoning_hint(request), self.thread_id.as_deref()),",
"occurrence": 2
},
@@ -870,28 +884,35 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/memory/tools.rs",
- "line": 141,
+ "line": 145,
"text": ".or_else(crate::agent::turn_workspace::current)",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/memory/tools.rs",
- "line": 146,
+ "line": 150,
"text": "crate::agent::harness::fork_context::current_parent()",
"occurrence": 1
},
+ {
+ "rule": "openhuman-task-local",
+ "path": "crates/openhuman-core/src/sandbox/ops.rs",
+ "line": 68,
+ "text": "crate::agent::harness::current_sandbox_mode(),",
+ "occurrence": 1
+ },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/security/approval/gate_intercept.rs",
- "line": 58,
+ "line": 53,
"text": "let origin = turn_origin::current().unwrap_or(AgentTurnOrigin::Unknown);",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/security/approval/gate_intercept.rs",
- "line": 275,
+ "line": 298,
"text": "&& (detached || crate::agent::harness::spawn_depth_context::current_spawn_depth() > 0);",
"occurrence": 1
},
@@ -918,44 +939,44 @@
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/skills/webhooks/bus.rs",
- "line": 317,
- "text": "crate::agent::turn_origin::with_origin(",
+ "path": "crates/openhuman-core/src/skills/runtime/schemas.rs",
+ "line": 270,
+ "text": "let origin = crate::agent::turn_origin::current()",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/skills/webhooks/ops.rs",
- "line": 171,
- "text": "crate::agent::turn_origin::with_origin(",
+ "path": "crates/openhuman-core/src/skills/runtime/schemas.rs",
+ "line": 272,
+ "text": "let started = crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/tools/impl/system/node_exec.rs",
- "line": 259,
- "text": "crate::agent::harness::current_sandbox_mode(),",
+ "path": "crates/openhuman-core/src/skills/schemas/handlers.rs",
+ "line": 155,
+ "text": "let origin = crate::agent::turn_origin::current()",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/tools/impl/system/npm_exec.rs",
- "line": 261,
- "text": "crate::agent::harness::current_sandbox_mode(),",
+ "path": "crates/openhuman-core/src/skills/schemas/handlers.rs",
+ "line": 157,
+ "text": "let started = match crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/tools/impl/system/python_exec.rs",
- "line": 252,
- "text": "crate::agent::harness::current_sandbox_mode(),",
+ "path": "crates/openhuman-core/src/skills/webhooks/bus.rs",
+ "line": 317,
+ "text": "crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/tools/impl/system/shell.rs",
- "line": 371,
- "text": "crate::agent::harness::current_sandbox_mode(),",
+ "path": "crates/openhuman-core/src/skills/webhooks/ops.rs",
+ "line": 171,
+ "text": "crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
{
@@ -1003,7 +1024,7 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/web_chat/ops/turn_guards.rs",
- "line": 111,
+ "line": 135,
"text": "crate::agent::turn_origin::with_origin(",
"occurrence": 1
},
@@ -1150,35 +1171,35 @@
{
"rule": "openhuman-upstream-reexport",
"path": "crates/openhuman-embed/src/lib.rs",
- "line": 187,
+ "line": 195,
"text": "pub use tinyagents_session::port::{",
"occurrence": 1
},
{
"rule": "openhuman-upstream-reexport",
"path": "crates/openhuman-embed/src/lib.rs",
- "line": 191,
+ "line": 199,
"text": "pub use tinyagents_session::testkit::conformance::{",
"occurrence": 1
},
{
"rule": "openhuman-upstream-reexport",
"path": "crates/openhuman-embed/src/lib.rs",
- "line": 195,
+ "line": 203,
"text": "pub use tinyagents_session::transcript::{",
"occurrence": 1
},
{
"rule": "openhuman-upstream-reexport",
"path": "crates/openhuman-embed/src/lib.rs",
- "line": 200,
+ "line": 208,
"text": "pub use tinyagents_session::turn_state::{TurnLifecycle, TurnState};",
"occurrence": 1
},
{
"rule": "openhuman-upstream-reexport",
"path": "crates/openhuman-embed/src/lib.rs",
- "line": 202,
+ "line": 210,
"text": "pub use tinyagents_session::{Result as StoreResult, TinyAgentsError as StoreError};",
"occurrence": 1
},
@@ -1189,244 +1210,6 @@
"text": "pub struct ToolRegistry<State: Send + Sync, Ctx: Send + Sync> {",
"occurrence": 1
},
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/bridge.rs",
- "line": 10,
- "text": "pub(crate) struct ChatMessage {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/bridge.rs",
- "line": 15,
- "text": "impl ChatMessage {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/driver.rs",
- "line": 71,
- "text": "use super::bridge::{ChatMessage, ChatResponse, ProviderDelta};",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/driver.rs",
- "line": 237,
- "text": "pub messages: &'a [ChatMessage],",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 6,
- "text": "fn msg(role: &str, content: &str) -> ChatMessage {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 8,
- "text": "\"system\" => ChatMessage::system(content),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 9,
- "text": "\"user\" => ChatMessage::user(content),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 10,
- "text": "\"assistant\" => ChatMessage::assistant(content),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 11,
- "text": "_ => ChatMessage::tool(content),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 148,
- "text": "&[ChatMessage::user(",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 167,
- "text": "&[ChatMessage::user(",
- "occurrence": 2
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 184,
- "text": "&[ChatMessage::user(\"read [IMAGE:/etc/hostname]\")],",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 195,
- "text": "ChatMessage::user(\"earlier [OH_IMAGE:data:image/png;base64,QUJD]\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 196,
- "text": "ChatMessage::assistant(\"old answer\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 197,
- "text": "ChatMessage::user(\"latest\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 214,
- "text": "ChatMessage::user(\"first steering\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 215,
- "text": "ChatMessage::user(\"second steering\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 216,
- "text": "ChatMessage::assistant(\"answer\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 217,
- "text": "ChatMessage::user(\"latest\"),",
- "occurrence": 2
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 227,
- "text": "&[ChatMessage::user(",
- "occurrence": 3
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 242,
- "text": "&[ChatMessage::user(",
- "occurrence": 4
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 15,
- "text": "use super::bridge::ChatMessage;",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 25,
- "text": "pub fn build_stdin(messages: &[ChatMessage], is_new_session: bool) -> Vec<u8> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 35,
- "text": "let non_system: Vec<&ChatMessage> = messages.iter().filter(|m| m.role != \"system\").collect();",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 93,
- "text": "fn pending_user_content(non_system: &[&ChatMessage]) -> Option<String> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 116,
- "text": "fn prior_conversation_preamble(non_system: &[&ChatMessage], end: usize) -> Option<String> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 52,
- "text": "ChatMessage::system(\"base\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 53,
- "text": "ChatMessage::user(\"question\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 54,
- "text": "ChatMessage::system(\"middleware addition\"),",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 51,
- "text": "use bridge::{ChatMessage, ChatResponse, ProviderDelta};",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 221,
- "text": "messages: &[ChatMessage],",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 291,
- "text": "fn coalesce_system_prompt(messages: &[ChatMessage]) -> Option<String> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 340,
- "text": "fn request_messages(request: &ModelRequest) -> Vec<ChatMessage> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 374,
- "text": "ChatMessage::new(role, content)",
- "occurrence": 1
- },
{
"rule": "tinyagents-tool-calling-facade",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/dialect.rs",
diff --git a/scripts/ci/check-agent-runtime-boundary.mjs b/scripts/ci/check-agent-runtime-boundary.mjs
index 0a742f64cb..b9d71f171c 100644
--- a/scripts/ci/check-agent-runtime-boundary.mjs
+++ b/scripts/ci/check-agent-runtime-boundary.mjs
@@ -3,9 +3,13 @@
import { readFile, readdir, writeFile } from "node:fs/promises";
import { dirname, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { isClaudeCodeBridgeMessage } from "../lib/runtime-boundary-types.mjs";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
-const baselinePath = resolve(repoRoot, "scripts/ci/agent-runtime-boundary-baseline.json");
+const baselinePath = resolve(
+ repoRoot,
+ "scripts/ci/agent-runtime-boundary-baseline.json",
+);
const openhumanCratesRoot = resolve(repoRoot, "crates");
const tinyagentsRoot = resolve(repoRoot, "vendor/tinyagents/crates");
const writeBaseline = process.argv.includes("--write-baseline");
@@ -14,56 +18,115 @@ const noBaseline = process.argv.includes("--no-baseline");
// Product types need not start with `OpenHuman`, so this is an explicit,
// reviewed inventory rather than a naming convention.
const openhumanDomainTypes = new Set([
- "AgentDefinitionDisplay", "AgentDefinitionModel",
- "AgentProgress", "ApprovalDecision", "ChatMessage", "ConversationMessage",
- "ConversationMessagePatch", "ConversationMessageRecord", "DomainEvent",
- "IntegrationAccount", "OpenHumanConfig", "OpenHumanRunContext", "ToolExecutionResult",
- "ToolResultMessage", "TurnOrigin", "UserProfileHook", "WorkspacePolicy",
+ "AgentDefinitionDisplay",
+ "AgentDefinitionModel",
+ "AgentProgress",
+ "ApprovalDecision",
+ "ChatMessage",
+ "ConversationMessage",
+ "ConversationMessagePatch",
+ "ConversationMessageRecord",
+ "DomainEvent",
+ "IntegrationAccount",
+ "OpenHumanConfig",
+ "OpenHumanRunContext",
+ "ToolExecutionResult",
+ "ToolResultMessage",
+ "TurnOrigin",
+ "UserProfileHook",
+ "WorkspacePolicy",
]);
// Names moved out of compatibility layers. Values identify their sole owner;
// declarations in any other TinyAgents crate are facades even if private.
const movedSymbolOwners = new Map([
- ["Tool", "tinytools"], ["ToolResult", "tinytools"], ["ToolPolicy", "tinytools"],
- ["ToolSchema", "tinytools"], ["ToolCall", "tinytools"],
- ["ToolCallOptions", "tinytools"], ["ToolRunContext", "tinytools"],
- ["WorkspaceDescriptor", "tinytools"], ["ToolContent", "tinytools"],
+ ["Tool", "tinytools"],
+ ["ToolResult", "tinytools"],
+ ["ToolPolicy", "tinytools"],
+ ["ToolSchema", "tinytools"],
+ ["ToolCall", "tinytools"],
+ ["ToolCallOptions", "tinytools"],
+ ["ToolRunContext", "tinytools"],
+ ["WorkspaceDescriptor", "tinytools"],
+ ["ToolContent", "tinytools"],
["ToolRegistry", "tinytools"],
- ["ChatModel", "tinyinference-llm"], ["ModelRequest", "tinyinference-llm"],
- ["ModelResponse", "tinyinference-llm"], ["Message", "tinyinference-llm"],
- ["MessageDelta", "tinyinference-llm"], ["Usage", "tinyinference-llm"],
+ ["ChatModel", "tinyinference-llm"],
+ ["ModelRequest", "tinyinference-llm"],
+ ["ModelResponse", "tinyinference-llm"],
+ ["Message", "tinyinference-llm"],
+ ["MessageDelta", "tinyinference-llm"],
+ ["Usage", "tinyinference-llm"],
["UsageTotals", "tinyinference-llm"],
- ["AgentHarness", "tinyagents-harness"], ["AgentTurnRequest", "tinyagents-harness"],
- ["HostCapabilities", "tinyagents-harness"], ["RunConfig", "tinyagents-harness"],
- ["RunContext", "tinyagents-harness"], ["CancellationToken", "tinyagents-harness"],
- ["RetryPolicy", "tinyagents-harness"], ["FallbackPolicy", "tinyagents-harness"],
+ ["AgentHarness", "tinyagents-harness"],
+ ["AgentTurnRequest", "tinyagents-harness"],
+ ["HostCapabilities", "tinyagents-harness"],
+ ["RunConfig", "tinyagents-harness"],
+ ["RunContext", "tinyagents-harness"],
+ ["CancellationToken", "tinyagents-harness"],
+ ["RetryPolicy", "tinyagents-harness"],
+ ["FallbackPolicy", "tinyagents-harness"],
]);
const bridgeSymbols = [
- "SharedToolAdapter", "ToolAdapter", "spec_to_schema", "execute_openhuman_tool",
- "assemble_turn_harness", "run_turn_via_tinyagents_shared",
+ "SharedToolAdapter",
+ "ToolAdapter",
+ "spec_to_schema",
+ "execute_openhuman_tool",
+ "assemble_turn_harness",
+ "run_turn_via_tinyagents_shared",
];
const deletedTaskLocalModules = [
- "fork_context", "sandbox_context", "spawn_depth_context", "task_recency_context",
- "turn_attachments_context", "turn_dispatch_guard", "turn_subagent_usage",
- "resolved_route", "run_cancellation_context", "thread_context",
+ "fork_context",
+ "sandbox_context",
+ "spawn_depth_context",
+ "task_recency_context",
+ "turn_attachments_context",
+ "turn_dispatch_guard",
+ "turn_subagent_usage",
+ "resolved_route",
+ "run_cancellation_context",
+ "thread_context",
];
const taskLocalAccessors = [
- "current_parent", "with_parent_context",
- "current_sandbox_mode", "with_current_sandbox_mode",
- "current_spawn_depth", "with_spawn_depth", "current_task_recency_window",
- "with_task_recency_window", "current_turn_image_placeholders",
- "with_current_turn_image_placeholders", "with_dispatch_guard", "record_subagent_usage",
- "with_turn_collector", "current_progress_sink", "with_progress_sink",
- "with_resolved_provider_route_scope", "record_resolved_provider_route", "current_route_slot",
- "with_route_slot", "current_resolved_provider_route", "current_run_cancellation",
- "with_run_cancellation", "current_thread_id", "with_thread_id", "current_is_user_authored",
- "with_origin", "with_inherited_origin", "current_request_id",
+ "current_parent",
+ "with_parent_context",
+ "current_sandbox_mode",
+ "with_current_sandbox_mode",
+ "current_spawn_depth",
+ "with_spawn_depth",
+ "current_task_recency_window",
+ "with_task_recency_window",
+ "current_turn_image_placeholders",
+ "with_current_turn_image_placeholders",
+ "with_dispatch_guard",
+ "record_subagent_usage",
+ "with_turn_collector",
+ "current_progress_sink",
+ "with_progress_sink",
+ "with_resolved_provider_route_scope",
+ "record_resolved_provider_route",
+ "current_route_slot",
+ "with_route_slot",
+ "current_resolved_provider_route",
+ "current_run_cancellation",
+ "with_run_cancellation",
+ "current_thread_id",
+ "with_thread_id",
+ "current_is_user_authored",
+ "with_origin",
+ "with_inherited_origin",
+ "current_request_id",
];
const taskLocalStatics = [
- "PARENT_CONTEXT", "CURRENT_AGENT_SANDBOX_MODE",
- "TASK_RECENCY_WINDOW", "CURRENT_TURN_IMAGE_PLACEHOLDERS", "AGENT_PROGRESS_SINK",
- "RESOLVED_PROVIDER_ROUTE", "CURRENT_RUN_CANCELLATION", "THREAD_ID", "AGENT_TURN_ORIGIN",
+ "PARENT_CONTEXT",
+ "CURRENT_AGENT_SANDBOX_MODE",
+ "TASK_RECENCY_WINDOW",
+ "CURRENT_TURN_IMAGE_PLACEHOLDERS",
+ "AGENT_PROGRESS_SINK",
+ "RESOLVED_PROVIDER_ROUTE",
+ "CURRENT_RUN_CANCELLATION",
+ "THREAD_ID",
+ "AGENT_TURN_ORIGIN",
"AGENT_TURN_WORKSPACE",
];
@@ -108,12 +171,17 @@ function rustCode(source) {
}
if (state === "block") {
if (char === "/" && next === "*") {
- blockDepth += 1; result += " "; index += 2;
+ blockDepth += 1;
+ result += " ";
+ index += 2;
} else if (char === "*" && next === "/") {
- blockDepth -= 1; result += " "; index += 2;
+ blockDepth -= 1;
+ result += " ";
+ index += 2;
if (blockDepth === 0) state = "code";
} else {
- result += blank(char); index += 1;
+ result += blank(char);
+ index += 1;
}
continue;
}
@@ -121,39 +189,64 @@ function rustCode(source) {
result += blank(char);
if (char === "\\") {
if (next !== undefined) {
- result += blank(next); index += 2;
+ result += blank(next);
+ index += 2;
} else index += 1;
} else {
- if ((state === "quoted" && char === '"') || (state === "char" && char === "'")) state = "code";
+ if (
+ (state === "quoted" && char === '"') ||
+ (state === "char" && char === "'")
+ )
+ state = "code";
index += 1;
}
continue;
}
if (state === "raw") {
- if (char === '"' && source.slice(index + 1, index + 1 + rawHashes.length) === rawHashes) {
- result += " ".repeat(rawHashes.length + 1); index += rawHashes.length + 1; state = "code";
+ if (
+ char === '"' &&
+ source.slice(index + 1, index + 1 + rawHashes.length) === rawHashes
+ ) {
+ result += " ".repeat(rawHashes.length + 1);
+ index += rawHashes.length + 1;
+ state = "code";
} else {
- result += blank(char); index += 1;
+ result += blank(char);
+ index += 1;
}
continue;
}
if (char === "/" && next === "/") {
- result += " "; index += 2; state = "line";
+ result += " ";
+ index += 2;
+ state = "line";
} else if (char === "/" && next === "*") {
- result += " "; index += 2; blockDepth = 1; state = "block";
+ result += " ";
+ index += 2;
+ blockDepth = 1;
+ state = "block";
} else if (char === '"') {
- result += " "; index += 1; state = "quoted";
+ result += " ";
+ index += 1;
+ state = "quoted";
} else if (char === "'" && isRustCharLiteral(source, index)) {
- result += " "; index += 1; state = "char";
+ result += " ";
+ index += 1;
+ state = "char";
} else if (char === "r") {
const raw = source.slice(index).match(/^r(#{0,255})"/);
if (raw) {
- result += " ".repeat(raw[0].length); index += raw[0].length; rawHashes = raw[1]; state = "raw";
+ result += " ".repeat(raw[0].length);
+ index += raw[0].length;
+ rawHashes = raw[1];
+ state = "raw";
} else {
- result += char; index += 1;
+ result += char;
+ index += 1;
}
} else {
- result += char; index += 1;
+ result += char;
+ index += 1;
}
}
return result;
@@ -167,10 +260,15 @@ function isRustCharLiteral(source, start) {
const escape = source[escapeStart];
if (escape === undefined) return false;
if ("\\'\"nrt0".includes(escape)) return source[escapeStart + 1] === "'";
- if (escape === "x") return /^[0-9a-fA-F]{2}'/.test(source.slice(escapeStart + 1));
+ if (escape === "x")
+ return /^[0-9a-fA-F]{2}'/.test(source.slice(escapeStart + 1));
if (escape === "u") {
const close = source.indexOf("}", escapeStart + 1);
- return close >= 0 && /^\{[0-9a-fA-F_]+\}$/.test(source.slice(escapeStart + 1, close + 1)) && source[close + 1] === "'";
+ return (
+ close >= 0 &&
+ /^\{[0-9a-fA-F_]+\}$/.test(source.slice(escapeStart + 1, close + 1)) &&
+ source[close + 1] === "'"
+ );
}
return false;
}
@@ -181,7 +279,11 @@ function isRustCharLiteral(source, start) {
function codeLines(source) {
const code = rustCode(source).split(/\r?\n/);
const raw = source.split(/\r?\n/);
- return code.map((text, index) => ({ line: index + 1, text, raw: raw[index] ?? "" }));
+ return code.map((text, index) => ({
+ line: index + 1,
+ text,
+ raw: raw[index] ?? "",
+ }));
}
function compactRustPath(text) {
@@ -189,7 +291,9 @@ function compactRustPath(text) {
}
function isUpstreamPath(text) {
- return /\b(?:tinyagents(?:_[a-z0-9_]+)?|tinytools(?:_[a-z0-9_]+)?|tinyinference(?:_[a-z0-9_]+)?)\s*::/i.test(text);
+ return /\b(?:tinyagents(?:_[a-z0-9_]+)?|tinytools(?:_[a-z0-9_]+)?|tinyinference(?:_[a-z0-9_]+)?)\s*::/i.test(
+ text,
+ );
}
function isDependencyTable(header) {
@@ -197,7 +301,9 @@ function isDependencyTable(header) {
}
function nestedDependencyName(header) {
- const match = header.match(/(?:^|\.)(?:dev-|build-)?dependencies\s*\.\s*([A-Za-z0-9_-]+)\s*$/i);
+ const match = header.match(
+ /(?:^|\.)(?:dev-|build-)?dependencies\s*\.\s*([A-Za-z0-9_-]+)\s*$/i,
+ );
return match?.[1];
}
@@ -224,15 +330,18 @@ function cargoOpenhumanDependencyLines(source) {
if (tableMatch) {
table = tableMatch[1].replace(/\s+/g, "");
nestedDependency = nestedDependencyName(table) ?? "";
- if (/^openhuman(?:[-_][A-Za-z0-9_-]+)?$/i.test(nestedDependency)) findings.push({ line: offset + 1, text: raw });
+ if (/^openhuman(?:[-_][A-Za-z0-9_-]+)?$/i.test(nestedDependency))
+ findings.push({ line: offset + 1, text: raw });
continue;
}
if (!isDependencyTable(table) && !nestedDependency) continue;
const keyMatch = line.match(/^\s*([A-Za-z0-9_-]+)\s*=/);
const key = keyMatch?.[1] ?? "";
const namesOpenhuman = /^openhuman(?:[-_][A-Za-z0-9_-]+)?$/i.test(key);
- const aliasesOpenhuman = /\bpackage\s*=\s*["']openhuman(?:[-_][A-Za-z0-9_-]+)?["']/i.test(line);
- if (namesOpenhuman || aliasesOpenhuman) findings.push({ line: offset + 1, text: raw });
+ const aliasesOpenhuman =
+ /\bpackage\s*=\s*["']openhuman(?:[-_][A-Za-z0-9_-]+)?["']/i.test(line);
+ if (namesOpenhuman || aliasesOpenhuman)
+ findings.push({ line: offset + 1, text: raw });
}
return findings;
}
@@ -244,64 +353,184 @@ function tinyagentsCrateName(path) {
function isBehaviorFreeForwarder(source) {
let remaining = rustCode(source);
remaining = remaining.replace(/^\s*#\s*\[[^\n]*]\s*$/gm, "");
- remaining = remaining.replace(/(?:pub(?:\s*\([^)]*\))?\s+)?use\s+[\s\S]*?;/g, "");
+ remaining = remaining.replace(
+ /(?:pub(?:\s*\([^)]*\))?\s+)?use\s+[\s\S]*?;/g,
+ "",
+ );
return !/[A-Za-z0-9_]/.test(remaining);
}
function assertSelfTests() {
const fixture = [
- "[dependencies.openhuman]", "version = \"1\"",
- "[target.'cfg(unix)'.dev-dependencies]", "host = { package = \"openhuman-core\", version = \"1\" }",
- "[workspace.dependencies]", "openhuman_tools = \"1\"",
- "[build-dependencies]", "helper = { package = \"openhuman\" }",
- "[dev-dependencies.host]", "package = 'openhuman'",
+ "[dependencies.openhuman]",
+ 'version = "1"',
+ "[target.'cfg(unix)'.dev-dependencies]",
+ 'host = { package = "openhuman-core", version = "1" }',
+ "[workspace.dependencies]",
+ 'openhuman_tools = "1"',
+ "[build-dependencies]",
+ 'helper = { package = "openhuman" }',
+ "[dev-dependencies.host]",
+ "package = 'openhuman'",
].join("\n");
- if (cargoOpenhumanDependencyLines(fixture).length !== 5) throw new Error("agent-runtime boundary self-test: Cargo dependency form escaped detection");
- if (!["ChatMessage", "ConversationMessage", "ToolResultMessage"].every((name) => openhumanDomainTypes.has(name))) throw new Error("agent-runtime boundary self-test: durable transcript inventory regressed");
- const masked = rustCode('/* openhuman :: AgentProgress */ let x = openhuman :: AgentProgress; // tinytools::Tool');
- if (!compactRustPath(masked).includes("openhuman::AgentProgress") || masked.includes("tinytools::Tool")) throw new Error("agent-runtime boundary self-test: Rust masking/path normalization regressed");
- const lifetimeMasked = rustCode("fn borrow<'a>(message: &'a ChatMessage) { 'retry: loop { let _ = openhuman :: ChatMessage; break 'retry; } }");
- if (!compactRustPath(lifetimeMasked).includes("openhuman::ChatMessage") || !lifetimeMasked.includes("&'a ChatMessage")) throw new Error("agent-runtime boundary self-test: Rust lifetimes or labels hid code");
- const literalMasked = rustCode("let marker = 'x'; let text = \"openhuman :: ChatMessage\"; // openhuman :: ChatMessage");
- if (literalMasked.includes("openhuman") || literalMasked.includes("marker = 'x'")) throw new Error("agent-runtime boundary self-test: Rust literals or comments leaked into scan");
- if (!isBehaviorFreeForwarder("pub(crate) use tinytools::Tool;\n")) throw new Error("agent-runtime boundary self-test: private forwarding module escaped detection");
- const beforeMove = stable([{ rule: "fixture", path: "fixture.rs", line: 7, text: "use openhuman::ChatMessage;" }]);
- const afterMove = stable([{ rule: "fixture", path: "fixture.rs", line: 8, text: "use openhuman::ChatMessage;" }]);
- if (JSON.stringify(beforeMove) === JSON.stringify(afterMove)) throw new Error("agent-runtime boundary self-test: physical moves escaped the exact baseline");
+ if (cargoOpenhumanDependencyLines(fixture).length !== 5)
+ throw new Error(
+ "agent-runtime boundary self-test: Cargo dependency form escaped detection",
+ );
+ if (
+ !["ChatMessage", "ConversationMessage", "ToolResultMessage"].every((name) =>
+ openhumanDomainTypes.has(name),
+ )
+ )
+ throw new Error(
+ "agent-runtime boundary self-test: durable transcript inventory regressed",
+ );
+ const masked = rustCode(
+ "/* openhuman :: AgentProgress */ let x = openhuman :: AgentProgress; // tinytools::Tool",
+ );
+ if (
+ !compactRustPath(masked).includes("openhuman::AgentProgress") ||
+ masked.includes("tinytools::Tool")
+ )
+ throw new Error(
+ "agent-runtime boundary self-test: Rust masking/path normalization regressed",
+ );
+ const lifetimeMasked = rustCode(
+ "fn borrow<'a>(message: &'a ChatMessage) { 'retry: loop { let _ = openhuman :: ChatMessage; break 'retry; } }",
+ );
+ if (
+ !compactRustPath(lifetimeMasked).includes("openhuman::ChatMessage") ||
+ !lifetimeMasked.includes("&'a ChatMessage")
+ )
+ throw new Error(
+ "agent-runtime boundary self-test: Rust lifetimes or labels hid code",
+ );
+ const literalMasked = rustCode(
+ "let marker = 'x'; let text = \"openhuman :: ChatMessage\"; // openhuman :: ChatMessage",
+ );
+ if (
+ literalMasked.includes("openhuman") ||
+ literalMasked.includes("marker = 'x'")
+ )
+ throw new Error(
+ "agent-runtime boundary self-test: Rust literals or comments leaked into scan",
+ );
+ if (!isBehaviorFreeForwarder("pub(crate) use tinytools::Tool;\n"))
+ throw new Error(
+ "agent-runtime boundary self-test: private forwarding module escaped detection",
+ );
+ const beforeMove = stable([
+ {
+ rule: "fixture",
+ path: "fixture.rs",
+ line: 7,
+ text: "use openhuman::ChatMessage;",
+ },
+ ]);
+ const afterMove = stable([
+ {
+ rule: "fixture",
+ path: "fixture.rs",
+ line: 8,
+ text: "use openhuman::ChatMessage;",
+ },
+ ]);
+ if (JSON.stringify(beforeMove) === JSON.stringify(afterMove))
+ throw new Error(
+ "agent-runtime boundary self-test: physical moves escaped the exact baseline",
+ );
}
assertSelfTests();
const findings = [];
+const claudeCodeBridge = rustCode(
+ await readFile(
+ resolve(
+ tinyagentsRoot,
+ "tinyagents-harness/src/providers/claude_code/bridge.rs",
+ ),
+ "utf8",
+ ),
+);
function add(rule, path, line, text) {
- findings.push({ rule, path: relative(repoRoot, path), line, text: text.trim() });
+ findings.push({
+ rule,
+ path: relative(repoRoot, path),
+ line,
+ text: text.trim(),
+ });
}
// Scan every OpenHuman crate: facades are not restricted to agent/.
-for (const path of await filesUnder(openhumanCratesRoot, (path) => path.endsWith(".rs") && /\/src\//.test(path))) {
+for (const path of await filesUnder(
+ openhumanCratesRoot,
+ (path) => path.endsWith(".rs") && /\/src\//.test(path),
+)) {
const rel = relative(repoRoot, path);
for (const { line, text, raw } of codeLines(await readFile(path, "utf8"))) {
if (!text.trim()) continue;
const compact = compactRustPath(text);
- if (/\btinyagents_harness::tool_calling\b/.test(compact)) add("openhuman-tool-calling-facade", path, line, raw);
- if (/\bcrate::agent::(?:dispatcher|pformat|harness::(?:parse|instructions|tool_filter))\b/.test(compact)) add("openhuman-agent-facade", path, line, raw);
- for (const symbol of bridgeSymbols) if (new RegExp(`\\b${escapeRegex(symbol)}\\b`).test(text)) add("openhuman-runtime-bridge", path, line, raw);
+ if (/\btinyagents_harness::tool_calling\b/.test(compact))
+ add("openhuman-tool-calling-facade", path, line, raw);
+ if (
+ /\bcrate::agent::(?:dispatcher|pformat|harness::(?:parse|instructions|tool_filter))\b/.test(
+ compact,
+ )
+ )
+ add("openhuman-agent-facade", path, line, raw);
+ for (const symbol of bridgeSymbols)
+ if (new RegExp(`\\b${escapeRegex(symbol)}\\b`).test(text))
+ add("openhuman-runtime-bridge", path, line, raw);
if (!isTestPath(rel)) {
- const isListedTaskLocalFile = /\/(?:fork_context|sandbox_context|spawn_depth_context|task_recency_context|turn_attachments_context|turn_dispatch_guard|turn_subagent_usage|progress_sink|resolved_route|run_cancellation_context|thread_context|turn_origin|turn_workspace)\.rs$/.test(path);
- const namesTaskLocalAccessor = taskLocalAccessors.some((name) => new RegExp(`\\b${escapeRegex(name)}\\s*\\(`).test(text) || (/\b(?:pub(?:\([^)]*\))?\s+)?use\b/.test(text) && new RegExp(`\\b${escapeRegex(name)}\\b`).test(text)));
- const namesTaskLocalStatic = taskLocalStatics.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(text));
- const usesGenericAccessor = /\b(?:turn_origin|turn_workspace|turn_dispatch_guard)::(?:current|capture|propagate|spawn|spawn_unlabelled|check|record_subagent_elapsed|with_workspace)\b/.test(compact) || (/\/turn_workspace\.rs$/.test(path) && /\bwith_workspace\s*\(/.test(text));
- const declaresDeletedModule = deletedTaskLocalModules.some((name) => new RegExp(`\\bmod\\s+${escapeRegex(name)}\\s*;`).test(text));
- if ((isListedTaskLocalFile && /\btokio\s*::\s*task_local!/.test(text)) || namesTaskLocalAccessor || namesTaskLocalStatic || usesGenericAccessor || declaresDeletedModule) add("openhuman-task-local", path, line, raw);
+ const isListedTaskLocalFile =
+ /\/(?:fork_context|sandbox_context|spawn_depth_context|task_recency_context|turn_attachments_context|turn_dispatch_guard|turn_subagent_usage|progress_sink|resolved_route|run_cancellation_context|thread_context|turn_origin|turn_workspace)\.rs$/.test(
+ path,
+ );
+ const namesTaskLocalAccessor = taskLocalAccessors.some(
+ (name) =>
+ new RegExp(`\\b${escapeRegex(name)}\\s*\\(`).test(text) ||
+ (/\b(?:pub(?:\([^)]*\))?\s+)?use\b/.test(text) &&
+ new RegExp(`\\b${escapeRegex(name)}\\b`).test(text)),
+ );
+ const namesTaskLocalStatic = taskLocalStatics.some((name) =>
+ new RegExp(`\\b${escapeRegex(name)}\\b`).test(text),
+ );
+ const usesGenericAccessor =
+ /\b(?:turn_origin|turn_workspace|turn_dispatch_guard)::(?:current|capture|propagate|spawn|spawn_unlabelled|check|record_subagent_elapsed|with_workspace)\b/.test(
+ compact,
+ ) ||
+ (/\/turn_workspace\.rs$/.test(path) &&
+ /\bwith_workspace\s*\(/.test(text));
+ const declaresDeletedModule = deletedTaskLocalModules.some((name) =>
+ new RegExp(`\\bmod\\s+${escapeRegex(name)}\\s*;`).test(text),
+ );
+ if (
+ (isListedTaskLocalFile && /\btokio\s*::\s*task_local!/.test(text)) ||
+ namesTaskLocalAccessor ||
+ namesTaskLocalStatic ||
+ usesGenericAccessor ||
+ declaresDeletedModule
+ )
+ add("openhuman-task-local", path, line, raw);
}
- if (/\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text)) add("openhuman-upstream-reexport", path, line, raw);
+ if (
+ /\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(
+ text,
+ )
+ )
+ add("openhuman-upstream-reexport", path, line, raw);
}
}
-for (const path of await filesUnder(tinyagentsRoot, (path) => path.endsWith(".rs") || path.endsWith("Cargo.toml"))) {
+for (const path of await filesUnder(
+ tinyagentsRoot,
+ (path) => path.endsWith(".rs") || path.endsWith("Cargo.toml"),
+)) {
const source = await readFile(path, "utf8");
if (path.endsWith("Cargo.toml")) {
- for (const item of cargoOpenhumanDependencyLines(source)) add("tinyagents-openhuman-dependency", path, item.line, item.text);
+ for (const item of cargoOpenhumanDependencyLines(source))
+ add("tinyagents-openhuman-dependency", path, item.line, item.text);
continue;
}
const crateName = tinyagentsCrateName(path);
@@ -310,28 +539,73 @@ for (const path of await filesUnder(tinyagentsRoot, (path) => path.endsWith(".rs
for (const { line, text, raw } of lines) {
if (!text.trim()) continue;
const compact = compactRustPath(text);
- if (/\b(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+tool_calling\s*;/.test(text)) add("tinyagents-tool-calling-facade", path, line, raw);
- if (/\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text)) add("tinyagents-upstream-reexport", path, line, raw);
- if (/\b(?:pub(?:\s*\([^)]*\))?\s+)?use\s+tinytools_agent(?:\s*::|\s*;)/.test(text)) add("tinyagents-tool-calling-facade", path, line, raw);
- if (isUpstreamPath(text) && firstForwardingLine === undefined) firstForwardingLine = { line, raw };
- const declaration = text.match(/\b(?:pub(?:\s*\([^)]*\))?\s+)?(?:type|struct|enum|trait|fn)\s+([A-Za-z_][A-Za-z0-9_]*)\b/);
+ if (/\b(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+tool_calling\s*;/.test(text))
+ add("tinyagents-tool-calling-facade", path, line, raw);
+ if (
+ /\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(
+ text,
+ )
+ )
+ add("tinyagents-upstream-reexport", path, line, raw);
+ if (
+ /\b(?:pub(?:\s*\([^)]*\))?\s+)?use\s+tinytools_agent(?:\s*::|\s*;)/.test(
+ text,
+ )
+ )
+ add("tinyagents-tool-calling-facade", path, line, raw);
+ if (isUpstreamPath(text) && firstForwardingLine === undefined)
+ firstForwardingLine = { line, raw };
+ const declaration = text.match(
+ /\b(?:pub(?:\s*\([^)]*\))?\s+)?(?:type|struct|enum|trait|fn)\s+([A-Za-z_][A-Za-z0-9_]*)\b/,
+ );
if (declaration) {
const owner = movedSymbolOwners.get(declaration[1]);
- if (owner && !crateName.startsWith(owner)) add("tinyagents-moved-symbol-alias", path, line, raw);
+ if (owner && !crateName.startsWith(owner))
+ add("tinyagents-moved-symbol-alias", path, line, raw);
}
- if (/\b(?:pub(?:\s*\([^)]*\))?\s+)?type\s+[A-Za-z_][A-Za-z0-9_]*[^=]*=\s*(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text) || /\b(?:pub(?:\s*\([^)]*\))?\s+)?struct\s+[A-Za-z_][A-Za-z0-9_]*\s*\(\s*(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text)) add("tinyagents-moved-symbol-alias", path, line, raw);
- if (/\bopenhuman(?:\s*::|_[A-Za-z0-9_]*\s*::)/i.test(compact)) add("tinyagents-openhuman-domain-name", path, line, raw);
+ if (
+ /\b(?:pub(?:\s*\([^)]*\))?\s+)?type\s+[A-Za-z_][A-Za-z0-9_]*[^=]*=\s*(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(
+ text,
+ ) ||
+ /\b(?:pub(?:\s*\([^)]*\))?\s+)?struct\s+[A-Za-z_][A-Za-z0-9_]*\s*\(\s*(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(
+ text,
+ )
+ )
+ add("tinyagents-moved-symbol-alias", path, line, raw);
+ if (/\bopenhuman(?:\s*::|_[A-Za-z0-9_]*\s*::)/i.test(compact))
+ add("tinyagents-openhuman-domain-name", path, line, raw);
for (const name of openhumanDomainTypes) {
+ if (
+ isClaudeCodeBridgeMessage(
+ relative(repoRoot, path),
+ name,
+ claudeCodeBridge,
+ text,
+ )
+ )
+ continue;
if (new RegExp(`\\b${escapeRegex(name)}\\b`).test(text)) {
add("tinyagents-openhuman-domain-name", path, line, raw);
break;
}
}
}
- if (firstForwardingLine && isBehaviorFreeForwarder(source)) add("tinyagents-forwarding-module", path, firstForwardingLine.line, firstForwardingLine.raw);
+ if (firstForwardingLine && isBehaviorFreeForwarder(source))
+ add(
+ "tinyagents-forwarding-module",
+ path,
+ firstForwardingLine.line,
+ firstForwardingLine.raw,
+ );
}
-findings.sort((a, b) => a.rule.localeCompare(b.rule) || a.path.localeCompare(b.path) || a.line - b.line || a.text.localeCompare(b.text));
+findings.sort(
+ (a, b) =>
+ a.rule.localeCompare(b.rule) ||
+ a.path.localeCompare(b.path) ||
+ a.line - b.line ||
+ a.text.localeCompare(b.text),
+);
function stable(records) {
const occurrences = new Map();
@@ -354,8 +628,13 @@ function stable(records) {
}
if (writeBaseline) {
- await writeFile(baselinePath, `${JSON.stringify(stable(findings), null, 2)}\n`);
- console.log(`Wrote ${findings.length} exact agent-runtime boundary violations to ${relative(repoRoot, baselinePath)}.`);
+ await writeFile(
+ baselinePath,
+ `${JSON.stringify(stable(findings), null, 2)}\n`,
+ );
+ console.log(
+ `Wrote ${findings.length} exact agent-runtime boundary violations to ${relative(repoRoot, baselinePath)}.`,
+ );
process.exit(0);
}
@@ -364,7 +643,9 @@ if (!noBaseline) {
try {
expected = JSON.parse(await readFile(baselinePath, "utf8"));
} catch (error) {
- console.error(`Unable to read ${relative(repoRoot, baselinePath)}: ${error.message}`);
+ console.error(
+ `Unable to read ${relative(repoRoot, baselinePath)}: ${error.message}`,
+ );
process.exit(1);
}
}
@@ -378,18 +659,26 @@ const identity = ({ rule, path, text, occurrence }) =>
const actualStable = stable(findings);
const expectedKeys = new Set(expected.map(identity));
const actualKeys = new Set(actualStable.map(identity));
-const added = findings.filter((_, index) => !expectedKeys.has(identity(actualStable[index])));
+const added = findings.filter(
+ (_, index) => !expectedKeys.has(identity(actualStable[index])),
+);
const stale = expected.filter((record) => !actualKeys.has(identity(record)));
if (added.length || stale.length) {
console.error("Agent-runtime ownership boundary changed.");
if (added.length) {
console.error(`\nUnbaselined violations (${added.length}):`);
- for (const item of added) console.error(` ${item.rule}: ${item.path}:${item.line}: ${item.text}`);
+ for (const item of added)
+ console.error(` ${item.rule}: ${item.path}:${item.line}: ${item.text}`);
}
if (stale.length) {
console.error(`\nStale baseline entries (${stale.length}); remove them:`);
- for (const item of stale) console.error(` ${item.rule}: ${item.path}: ${item.text} [${item.occurrence}]`);
+ for (const item of stale)
+ console.error(
+ ` ${item.rule}: ${item.path}: ${item.text} [${item.occurrence}]`,
+ );
}
process.exit(1);
}
-console.log(`Agent-runtime boundary holds (${findings.length} temporary exact violations baselined).`);
+console.log(
+ `Agent-runtime boundary holds (${findings.length} temporary exact violations baselined).`,
+);
diff --git a/scripts/ci/check-gated-test-allowlist.sh b/scripts/ci/check-gated-test-allowlist.sh
index df0dfe1a1a..3718d59745 100755
--- a/scripts/ci/check-gated-test-allowlist.sh
+++ b/scripts/ci/check-gated-test-allowlist.sh
@@ -18,7 +18,6 @@ cd "$(dirname "$0")/../.."
EXPECTED=$(cat <<'EOF'
agent/harness/builtin_definitions_tests.rs
agent/harness/definition_tests.rs
-agent/session_host/builder/factory.rs
agent/session_host/prelude_integrations.rs
agent/session_host/runtime_session.rs
agent/session_host/runtime_session_tests.rs
@@ -35,6 +34,7 @@ core/invoke_tests.rs
core/legacy_aliases_tests.rs
core/runtime/services.rs
core/runtime/subscribers.rs
+inference/provider/factory.rs
memory/layout_migration/map_tests.rs
mcp/server/resources.rs
mcp/server/mod.rs
@@ -53,6 +53,7 @@ tools/ops_tests_default_registry_tests.rs
tools/ops_tests_domain_family_tests.rs
tools/registry/ops_tests.rs
tools/registry/schemas_tests.rs
+web_chat/mod.rs
web3/stub.rs
web3/wallet/stub.rs
web3/x402/stub.rs
diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjs
index 72c437f51c..5caeba4b71 100644
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@ -39,16 +39,16 @@ const LEGACY_LIMIT_ENTRIES = [
// under the general 750 limit, so it needs no exception at all.
// The session-todo integration added transcript metadata construction to
// this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1406],
+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1349],
// Session-host factory still assembles the product's deliberately coupled
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 977],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1306],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1145],
- ["crates/openhuman-core/src/tools/ops.rs", 1206],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1304],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 973],
+ ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1247],
+ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1132],
+ ["crates/openhuman-core/src/tools/ops.rs", 978],
+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1264],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its
@@ -168,7 +168,9 @@ for (const [directory, table] of [
const declared = declaredTargets(table);
for (const name of files) {
if (!declared.has(name))
- failures.push(`${directory}/${name}.rs: missing [[${table}]] entry in ${CLI_MANIFEST}`);
+ failures.push(
+ `${directory}/${name}.rs: missing [[${table}]] entry in ${CLI_MANIFEST}`,
+ );
}
for (const name of declared) {
if (!files.has(name))
diff --git a/scripts/ci/saas-ambient-baseline.json b/scripts/ci/saas-ambient-baseline.json
index c0f85b98d4..db56d34433 100644
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@ -790,13 +790,6 @@
"text": "let reader = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},
- {
- "rule": "bare-spawn",
- "path": "crates/openhuman-core/src/memory/lifecycle/hooks.rs",
- "line": 241,
- "text": "let task = tokio::spawn(async move {",
- "occurrence": 1
- },
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/modules/ops.rs",
@@ -849,8 +842,8 @@
{
"rule": "home-dir",
"path": "crates/openhuman-core/src/sandbox/ops.rs",
- "line": 116,
- "text": "resolve_local_jail_grants(dirs::home_dir().as_deref(), &runtime_config.local_jail)",
+ "line": 639,
+ "text": "dirs::home_dir()",
"occurrence": 1
},
{
diff --git a/scripts/lib/runtime-boundary-types.mjs b/scripts/lib/runtime-boundary-types.mjs
new file mode 100644
index 0000000000..765f7588af
--- /dev/null
+++ b/scripts/lib/runtime-boundary-types.mjs
@@ -0,0 +1,24 @@
+// A provider-local neutral message is not OpenHuman's durable chat record.
+export function isClaudeCodeBridgeMessage(
+ path,
+ name,
+ bridgeCode,
+ reference = "",
+) {
+ if (
+ name !== "ChatMessage" ||
+ !path
+ .replaceAll("\\", "/")
+ .startsWith(
+ "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/",
+ )
+ )
+ return false;
+ if (/\bopenhuman(?:_[A-Za-z0-9_]+)?\s*::/.test(reference)) return false;
+ const body = bridgeCode.match(/\bstruct\s+ChatMessage\s*\{([^}]*)\}/)?.[1];
+ // Fail closed if this reviewed wire DTO grows product identity/state fields.
+ return (
+ body?.replace(/\s+/g, "") ===
+ "pub(crate)role:String,pub(crate)content:String,"
+ );
+}