Skip to content

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

Merge remote-tracking branch 'upstream/main' into medulla-12-scoped-hooks

Steven Enamakel4c6787dfecf0
diff --cc crates/openhuman-core/src/tools/timeout/mod.rs
index 16547ed574,a1629a1be5..c1378afc32
--- a/crates/openhuman-core/src/tools/timeout/mod.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod.rs
@@@ -239,63 -237,37 +239,63 @@@ pub async fn output_or_kill
/// caller cancels; a scoped [`ProcessCleanup`] can await that waiter.
pub async fn output_unbounded(
cmd: &mut tokio::process::Command,
+) -> std::io::Result<std::process::Output> {
+ output_with_input(cmd, None).await
+}
+
+/// Capture a command, optionally supplying stdin, in the current cleanup scope.
+pub async fn output_with_input(
+ cmd: &mut tokio::process::Command,
+ input: Option<Vec<u8>>,
) -> std::io::Result<std::process::Output> {
use std::process::Stdio;
- cmd.stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .kill_on_drop(true);
+ cmd.stdin(if input.is_some() {
+ Stdio::piped()
+ } else {
+ Stdio::null()
+ })
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ CommandEnvironment::apply(cmd);
own_process_group(cmd.as_std_mut());
- let child = cmd.spawn()?;
- let pid = child.id();
+ let mut child = cmd.spawn()?;
+ let stdin = child.stdin.take();
let reaped = process_cleanup::Reaped::register();
let (cancel, cancellation) = tokio::sync::watch::channel(false);
- let waiter = tokio::spawn(async move {
+ let waiter = crate::core::runtime::spawn_scoped(async move {
let _reaped = reaped;
- collect_command_output(child, cancellation).await
+ let write_input = async move {
+ if let (Some(mut stdin), Some(input)) = (stdin, input) {
+ use tokio::io::AsyncWriteExt;
+ // An early child exit closes stdin. Its exit status/output is
+ // authoritative; a broken pipe must not hide it.
+ let _ = stdin.write_all(&input).await;
+ }
+ };
+ let (_, output) = tokio::join!(write_input, collect_command_output(child, cancellation));
+ output
});
- let mut group = CommandGroup { pid, cancel };
- let result = waiter.await.map_err(std::io::Error::other)?;
- group.pid = None;
- result
+ let _cancel_on_drop = CancelOnDrop(cancel);
+ waiter.await.map_err(std::io::Error::other)?
}
-struct CommandGroup {
- pid: Option<u32>,
- cancel: tokio::sync::watch::Sender<bool>,
-}
+// The caller signals only the owned waiter. It never retains a PID after
+// that waiter reaps the child, so late future drops cannot kill a reused PID.
+struct CancelOnDrop(tokio::sync::watch::Sender<bool>);
-impl Drop for CommandGroup {
+impl Drop for CancelOnDrop {
fn drop(&mut self) {
- if let Some(pid) = self.pid {
+ self.0.send_replace(true);
+ }
+}
+
+struct CommandGroup(Option<u32>);
+
+impl CommandGroup {
+ fn kill(&self) {
+ if let Some(pid) = self.0 {
kill_process_group(pid);
- self.cancel.send_replace(true);
}
}
}
diff --cc crates/openhuman-embed/README.md
index ac6b18a1a6,c6603b764f..f7bb593777
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@@ -8,77 -8,6 +8,81 @@@ The [cookbook](https://github.com/tinyh
Hosts supply transport, credentials and application resources. Runtime settings establish shared defaults; agents narrow provider, access, prompt and tool behavior. Use ProfileRuntime when users require separate credentials and workspaces.
+## Cancelling one turn
+
+Acquire `Turn::cancellation_handle()` before sending a turn. The handle is
+cloneable and `cancel().await` waits for the turn to stop and for tracked
+commands to be reaped. The agent remains available for later turns:
+
+
+
+Cancellation is scoped to this turn, including while waiting for inference.
+Turns with a cancellation handle use owned interpreter subprocesses rather
+than the Node/Python pool, which has no acknowledged per-job abort API. This
+trades warm-worker reuse for awaited cleanup; ordinary turns retain pooling.
+The `meter` callback fires once on cancellation or a dropped send future,
+with `None` when dispatch has not supplied usage yet.
+
+Before send, cancellation prevents dispatch; after completion it is a no-op.
+On Unix, the built-in shell, Node, Python and npm commands kill their process
+group, including descendants. Other platforms stop the direct command. Host
+tools that spawn independent tasks or processes must provide their own cleanup;
+MCP server lifecycles remain owned by the agent. Keep polling `send()` while
+awaiting cancellation, for example in a spawned task.
+
+## Scoped worker hooks
+
+Hooks can be supplied at three levels: `RuntimeBuilder::tool_hook` /
+`post_turn_hook` for all agents, `AgentSpec::tool_hook` / `post_turn_hook`
+for one agent, and `Turn::tool_hook` / `post_turn_hook` for one dispatch.
+Tool callbacks run in that order. Named agent updates replace only that agent’s callback; per-turn callbacks are additional.
+`ToolHookContext` carries the agent/session identity when known, and `cwd`
+follows the execution workspace descriptor (including `Turn::cwd`), falling
+back to the embedding context's configured action root.
+The agent and turn hooks are never installed in the global registry, so
+concurrent workers and later turns do not pick up one another's callbacks.
+Post-turn callbacks run asynchronously with an owned session snapshot.
+Independently spawned tasks that build sessions must explicitly inherit
+`openhuman_core::agent::hooks::HookScope` to carry scoped hooks.
+
+Gateway attribution headers can be attached to `Route::header(name, value)`
+and used with `Turn::route`, or with `Provider::routed(route)` on an agent.
+They follow only that route's endpoint and are never saved to configuration,
+sent to background providers, or included as values in `Route`'s `Debug`.
+
+### Inline permission and usage policy
+
+`AgentSpec::can_use_tool` and `Turn::can_use_tool` await a host callback before
+executing each tool. The callback can wait for an approval UI and return
+`ToolHookDecision::Proceed`, `Deny`, or `ProceedWith`. It owns that wait;
+returning `Ask` denies execution. These callbacks add to existing tool policies,
+and a turn callback cannot override an agent denial.
+
+`AgentSpec::stop_hook` and `Turn::stop_hook` receive cumulative usage after each
+completed model call. Return `StopDecision::Continue` to observe usage, or
+`Stop` to prevent subsequent calls. Completed tool rounds may still execute;
+this is an after-call budget boundary, so hosts must refuse an already exhausted
+budget before sending a turn. Provider-reported charges remain authoritative,
+including known zero; missing charges remain unknown unless pricing is known.
+A policy stop uses a deterministic partial summary rather than spending on
+final-answer repair calls.
+
+### Per-turn tools and subprocess environment
+
+`Turn::tools` replaces this turn's host tool belt, including attached sources.
+An empty belt revokes host tools; the next turn returns to the agent's belt.
+Builtin tools still follow the agent definition. This supplies dynamic tools for
+in-process hosts; statically declared MCP servers retain their creation-time
+configuration.
+
+`Turn::tool_env` supplies the base environment of owned builtin subprocesses.
+Variables absent from it are not inherited from the daemon. The builtin command
+builders retain their own security/runtime additions, including Git restrictions,
+managed interpreter paths and scratch directories. Scoped turns bypass Node and
+Python pools, which cannot acknowledge per-job cancellation or swap a job's
+process environment. A host tool that spawns a separate Tokio task must explicitly
+carry the command environment and cleanup scopes into that task.
++
+ Standalone exact source pins and generated Cargo patches: [consumer setup](CONSUMERS.md).
+ Ordered fallbacks and required exploration: [routing](ROUTING.md).
+ Host telemetry and the existing exporter: [observers](OBSERVERS.md).
diff --cc crates/openhuman-embed/src/complete.rs
index f10008f6e6,5cbd6a7953..e73b1a5736
--- a/crates/openhuman-embed/src/complete.rs
+++ b/crates/openhuman-embed/src/complete.rs
@@@ -413,10 -439,12 +439,12 @@@ impl Completer
/// A completer for `route`, with no timeout and no observer.
pub fn new(route: Route) -> Self {
Self {
+ headers: route.headers.clone(),
route,
- headers: Vec::new(),
timeout: None,
observer: None,
+ cancellation: Default::default(),
+ budget: None,
}
}
diff --cc crates/openhuman-embed/src/lib.rs
index d4ebee3013,4e1e2d4b35..de781e73ab
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@@ -120,8 -122,7 +122,10 @@@ pub mod identity
pub mod memory;
#[cfg(feature = "modules")]
pub mod modules;
+mod permission;
+pub use permission::PermissionFuture;
+ pub mod observe;
++
pub mod process;
#[cfg(feature = "channels")]
pub mod profiles;
diff --cc crates/openhuman-embed/src/turn.rs
index fd3a2b5714,36c154afb5..1567f4736b
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@@ -270,14 -76,18 +76,21 @@@ pub struct Turn
seed: Option<Vec<(String, String)>>,
meter: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,
response_format: Option<crate::complete::ResponseFormat>,
+ structured_retries: u8,
max_tokens: Option<u32>,
top_p: Option<f64>,
- cancellation: Option<crate::CancellationToken>,
+ token_cancellation: Option<crate::CancellationToken>,
+ provider_options: serde_json::Value,
+ require_tool_call: bool,
untrusted_input: bool,
- cancel_handle: Option<crate::TurnCancellation>,
+ cancellation: Option<crate::TurnCancellation>,
+ timeout: Option<std::time::Duration>,
+ control_deadline: Option<tokio::time::Instant>,
+ observer: Option<Arc<dyn crate::observe::TurnObserver>>,
+ trace_content: crate::observe::TraceContent,
+ hooks: openhuman_core::agent::hooks::HookScope,
+ tools: Option<openhuman_core::agent::HostTools>,
+ tool_env: Option<openhuman_core::tools::timeout::CommandEnvironment>,
}
impl Turn {
@@@ -291,14 -102,18 +105,21 @@@
seed: None,
meter: None,
response_format: None,
+ structured_retries: 0,
max_tokens: None,
top_p: None,
- cancellation: None,
+ token_cancellation: None,
+ provider_options: serde_json::Value::Null,
+ require_tool_call: false,
untrusted_input: false,
- cancel_handle: None,
+ cancellation: None,
+ timeout: None,
+ control_deadline: None,
+ observer: None,
+ trace_content: crate::observe::TraceContent::MetadataOnly,
+ hooks: Default::default(),
+ tools: None,
+ tool_env: None,
}
}
diff --cc crates/openhuman-embed/src/turn_control.rs
index 0000000000,ba160fa2c0..caed7bb622
mode 000000,100644..100644
--- a/crates/openhuman-embed/src/turn_control.rs
+++ b/crates/openhuman-embed/src/turn_control.rs
@@@ -1,0 -1,499 +1,514 @@@
+ //! Whole-turn validation, observation, cancellation, deadlines and dispatch.
+ use super::*;
+
+ struct CancellationRelay(tokio::task::JoinHandle<()>);
+
+ impl Drop for CancellationRelay {
+ fn drop(&mut self) {
+ self.0.abort();
+ }
+ }
+
+ impl Turn {
+ /// Run the turn.
+ ///
+ /// Establishes the origin and progress scopes described in the module docs,
+ /// then dispatches through [`call`](crate::call::call) so the
+ /// `{result, logs}` envelope, [`DomainSet`](openhuman_core::core::runtime::DomainSet)
+ /// gating and error classification are handled the same way as every other
+ /// facade method.
+ ///
+ /// # Errors
+ ///
+ /// [`CoreError::Unavailable`] when the `inference` domain family is off —
+ /// that is a build/composition fact, not a failure, and a host should hide
+ /// the surface rather than report an error.
+ pub async fn send(mut self) -> Result<TurnOutcome, CoreError> {
++ let hooks = std::mem::take(&mut self.hooks);
++ let environment = self.tool_env.take();
++ let fresh_tools = self.tools.is_some();
++ let dispatch = hooks.scope(Box::pin(self.send_scoped()));
++ let dispatch = async move {
++ if fresh_tools {
++ openhuman_core::agent::tool_snapshot_scope::with_fresh_snapshot(dispatch).await
++ } else {
++ dispatch.await
++ }
++ };
++ match environment {
++ Some(environment) => environment.scope(dispatch).await,
++ None => dispatch.await,
++ }
++ }
++
++ async fn send_scoped(mut self) -> Result<TurnOutcome, CoreError> {
+ // External cancellation cascades inward; cancelling this turn through
+ // its acknowledgement handle/deadline must not cancel a shared parent.
+ let token = self
+ .token_cancellation
+ .clone()
+ .unwrap_or_default()
+ .child_token();
+ // A synchronously ready model stream can stay inside one dispatch poll.
+ // Relay control independently so its native cancellation checks also
+ // interrupt that poll; abort the relay when this turn ends or is dropped.
+ self.control_deadline = self
+ .timeout
+ .and_then(|duration| tokio::time::Instant::now().checked_add(duration));
+ let cancellation = self.cancellation.clone();
+ let deadline = self.control_deadline;
+ let _relay = (cancellation.is_some() || deadline.is_some()).then(|| {
+ let native = token.clone();
+ CancellationRelay(tokio::spawn(async move {
+ tokio::select! {
+ _ = async {
+ match cancellation {
+ Some(handle) => handle.cancelled().await,
+ None => std::future::pending().await,
+ }
+ } => {},
+ _ = async {
+ match deadline {
+ Some(deadline) => tokio::time::sleep_until(deadline).await,
+ None => std::future::pending().await,
+ }
+ } => {},
+ }
+ native.cancel();
+ }))
+ });
+ openhuman_core::agent::host_overrides::with_cancellation(token, self.send_traced()).await
+ }
+
+ async fn send_traced(mut self) -> Result<TurnOutcome, CoreError> {
+ // Keep cancellation acknowledgement behind the terminal callback too.
+ let _observer_guard = self.cancellation.as_ref().map(|handle| handle.enter());
+ let Some(observer) = self.observer.take() else {
+ return self.send_events().await;
+ };
+ let capture = self.trace_content;
+ let session_id = self
+ .session_id
+ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.session_id = Some(session_id.clone());
+ let message = self.request.message.clone();
+ crate::observe::observe_turn(observer, capture, &session_id, &message, self.send_events())
+ .await
+ }
+
+ // Runtime lifecycle events enclose control/cleanup, while progress delivery
+ // keeps polling that control future even when the caller stops draining.
+ async fn send_events(mut self) -> Result<TurnOutcome, CoreError> {
+ let (hub, agent_id) = match &self.target {
+ TurnTarget::Agent(agent) => (
+ Some(agent._runtime_guard.events.clone()),
+ Some(agent.id.clone()),
+ ),
+ TurnTarget::Runtime(_) => (None, None),
+ };
+ let Some(hub) = hub else {
+ return self.send_controlled().await;
+ };
+ let session_id = self
+ .session_id
+ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.session_id = Some(session_id.clone());
+ let thread_id = event_thread_id(self.origin.as_ref(), &session_id);
+ let turn_id = hub.begin_turn(agent_id.clone(), &thread_id);
+ let mut end = ObservedTurn {
+ hub: hub.clone(),
+ agent_id: agent_id.clone(),
+ thread_id,
+ turn_id: turn_id.clone(),
+ success: false,
+ };
+ let forward = self.progress.take();
+ let token = openhuman_core::agent::host_overrides::current_cancellation();
+ let acknowledgement = self.cancellation.clone();
+ let deadline = self.control_deadline;
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ self.progress = Some(tx);
+ let mut dispatch = self.send_controlled();
+ let mut pending_progress = None;
+ let mut outcome = loop {
+ tokio::select! {
+ biased;
+ result = &mut dispatch => break result,
+ item = rx.recv() => if let Some(item) = item {
+ observe_progress(&hub, &agent_id, &turn_id, &item);
+ if let Some(sink) = &forward {
+ let retained = item.clone();
+ tokio::select! {
+ _ = sink.send(item) => {},
+ _ = token.cancelled() => {},
+ result = &mut dispatch => { pending_progress = Some(retained); break result; },
+ }
+ }
+ } else { break (&mut dispatch).await; },
+ }
+ };
+ drop(dispatch);
+ while let Some((item, observed)) = pending_progress
+ .take()
+ .map(|item| (item, true))
+ .or_else(|| rx.try_recv().ok().map(|item| (item, false)))
+ {
+ if !observed {
+ observe_progress(&hub, &agent_id, &turn_id, &item);
+ }
+ if outcome.is_ok() {
+ if let Some(sink) = &forward {
+ tokio::select! {
+ _ = sink.send(item) => {},
+ _ = token.cancelled() => outcome = Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
+ _ = async {
+ match &acknowledgement {
+ Some(handle) => handle.cancelled().await,
+ None => std::future::pending().await,
+ }
+ } => outcome = Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
+ _ = async {
+ match deadline {
+ Some(deadline) => tokio::time::sleep_until(deadline).await,
+ None => std::future::pending().await,
+ }
+ } => outcome = Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),
+ }
+ }
+ }
+ }
+ end.success = outcome.is_ok();
+ outcome
+ }
+
+ // Erase this large dispatch future at the control boundary: composing
+ // several observed/cancellable turns must not multiply caller stack use.
+ fn send_controlled(
+ mut self,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TurnOutcome, CoreError>> + Send>>
+ {
+ Box::pin(async move {
+ let deadline = self.control_deadline;
+ let token = self.token_cancellation.clone();
+ let native = openhuman_core::agent::host_overrides::current_cancellation();
- let cancellation = match self.cancellation.take() {
- Some(cancellation) => cancellation,
- None if deadline.is_some() || token.is_some() => crate::TurnCancellation::default(),
- None => return Box::pin(self.send_inner()).await,
++ let cancellation = self.cancellation.take().or_else(|| {
++ (deadline.is_some() || token.is_some()).then(crate::TurnCancellation::default)
++ });
++ let _guard = cancellation.as_ref().map(crate::TurnCancellation::enter);
++ let meter = crate::turn_meter::TurnMeter::new(self.meter.take());
++ let Some(cancellation) = cancellation else {
++ return Box::pin(self.send_inner(&meter.usage)).await;
+ };
- let _guard = cancellation.enter();
+ let outcome = cancellation
+ .cleanup()
+ .scope(async {
+ tokio::select! {
+ biased;
+ _ = async {
+ match &token {
+ Some(token) => token.cancelled().await,
+ None => std::future::pending().await,
+ }
+ } => Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
+ _ = cancellation.cancelled() => {
+ native.cancel();
+ log::debug!("[embed][agent] turn cancelled");
+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })
+ }
+ _ = async {
+ match deadline {
+ Some(deadline) => tokio::time::sleep_until(deadline).await,
+ None => std::future::pending().await,
+ }
+ } => {
+ native.cancel();
+ Err(CoreError::DeadlineExceeded { method: AGENT_CHAT })
+ },
- outcome = Box::pin(self.send_inner()) => outcome,
++ outcome = Box::pin(self.send_inner(&meter.usage)) => outcome,
+ }
+ })
+ .await;
+ // The dispatch future is dropped before waiting for its command
+ // waiters. No new command can register after this point.
+ cancellation.cleanup().wait().await;
+ outcome
+ })
+ }
+
+ /// Observe completion and, on runtime-owned agents, model and tool events.
+ /// Caller-built core runtimes provide terminal metadata only. Payloads are
+ /// omitted unless [`Self::trace_content`] explicitly enables them.
+ pub fn observer(mut self, observer: Arc<dyn crate::observe::TurnObserver>) -> Self {
+ self.observer = Some(observer);
+ self
+ }
+
+ /// Explicitly consent to model messages and tool payloads in observations.
+ pub fn trace_content(mut self, content: crate::observe::TraceContent) -> Self {
+ self.trace_content = content;
+ self
+ }
+
+ /// Bound the entire turn, including tool calls and answer repair.
+ /// Deadline errors are returned only after registered subprocess cleanup.
+ pub fn timeout(mut self, duration: std::time::Duration) -> Self {
+ self.timeout = Some(duration);
+ self
+ }
+
+ /// Obtain a cloneable handle that cancels only this turn and awaits its
+ /// subprocess cleanup. Acquire it before moving the turn to `send()`.
+ pub fn cancellation_handle(&mut self) -> crate::TurnCancellation {
+ self.cancellation
+ .get_or_insert_with(Default::default)
+ .clone()
+ }
+
- async fn send_inner(mut self) -> Result<TurnOutcome, CoreError> {
++ async fn send_inner(mut self, usage: &UsageSink) -> Result<TurnOutcome, CoreError> {
+ // The core neither mints nor returns a session id, so continuing a
+ // conversation would otherwise be impossible without the caller
+ // inventing an id scheme — which every embedder has then done
+ // differently. Mint one here and hand it back.
+ let session_id = self
+ .session_id
+ .take()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.request.thread_id = Some(session_id.clone());
+
+ log::debug!(
+ "[embed][agent] turn session={session_id} model={:?} routed={} cwd_set={}",
+ self.request.model_override,
+ self.request.inference_url.is_some(),
+ self.request.cwd.is_some(),
+ );
+
+ validate_route(&self.request)?;
+ self.validate_turn_options()?;
+
+ // Never transmit the bearer over a non-TLS channel. The route accepts
+ // an arbitrary base URL, so guard here — before any request is built —
+ // rather than trusting every embedder to only name https endpoints. A
+ // `Route` is refused when it pairs a credential with a non-HTTPS
+ // endpoint; a route without a credential is allowed through (some
+ // embedders run a local, unauthenticated OpenAI-compatible server over
+ // plain http, and there is nothing sensitive on the wire for them).
+ if self
+ .request
+ .api_key
+ .as_deref()
+ .is_some_and(|k| !k.is_empty())
+ {
+ if let Some(endpoint) = self.request.inference_url.as_deref() {
+ if !is_safe_endpoint_for_bearer(endpoint) {
+ return Err(crate::error::CoreError::InsecureRoute {
+ method: AGENT_CHAT,
+ endpoint: sanitize_url_for_display(endpoint),
+ });
+ }
+ }
+ }
+
+ // Filled by the turn itself, before any error is raised, so a failed
+ // turn is still metered. Read back below whether the dispatch returned
+ // a reply or an error.
- let usage: UsageSink = std::sync::Mutex::new(None);
- let meter = self.meter.take();
+ let wants_json = self
+ .response_format
+ .as_ref()
+ .is_some_and(crate::complete::ResponseFormat::wants_json);
+ let validator =
+ crate::structured::Validator::new(self.response_format.as_ref()).map_err(|reason| {
+ CoreError::StructuredOutput {
+ method: AGENT_CHAT,
+ failure: crate::structured::StructuredOutputFailure {
+ attempts: 0,
+ reason,
+ finish_reason: None,
+ answered_model: None,
+ usage: None,
+ },
+ }
+ })?;
+ let options = AgentTurnOptions {
+ shape: openhuman_core::agent::tinyagents::response_shape::ResponseShapeScope::new(
+ openhuman_core::agent::tinyagents::response_shape::ResponseShape {
+ response_format: self
+ .response_format
+ .take()
+ .map(crate::complete::ResponseFormat::into_wire),
+ max_output_tokens: self.max_tokens,
+ top_p: self.top_p,
+ validator: wants_json.then(|| std::sync::Arc::new(validator) as std::sync::Arc<dyn openhuman_core::agent::tinyagents::response_shape::ResponseValidator>),
+ structured_retries: self.structured_retries,
+ provider_options: self.provider_options.clone(),
+ require_tool_call: self.require_tool_call,
+ observer: openhuman_core::agent::tinyagents::turn_observer::current_scope(),
+ },
+ ),
+ untrusted_input: self.untrusted_input,
++ tools: self.tools.take(),
+ };
+ let budget = self.budget.take().map(|budget| crate::budget::ModelBudget {
+ ledger: budget.ledger.child(crate::budget::SpendLimits::default()),
+ call: budget.call,
+ });
- let dispatch = dispatch(self.target, self.request, self.seed.take(), &usage, options);
++ let dispatch = dispatch(self.target, self.request, self.seed.take(), usage, options);
+ let dispatch = async {
+ match &budget {
+ Some(budget) => {
+ openhuman_core::agent::tinyagents::budget::with_budget(budget.clone(), dispatch)
+ .await
+ }
+ None => dispatch.await,
+ }
+ };
+
+ let reply = match (self.origin, self.progress) {
+ (Some(origin), Some(sink)) => {
+ openhuman_core::agent::progress_sink::with_progress_sink(
+ sink,
+ openhuman_core::agent::turn_origin::with_origin(origin, dispatch),
+ )
+ .await
+ }
+ (Some(origin), None) => {
+ openhuman_core::agent::turn_origin::with_origin(origin, dispatch).await
+ }
+ (None, Some(sink)) => {
+ openhuman_core::agent::progress_sink::with_progress_sink(sink, dispatch).await
+ }
+ (None, None) => dispatch.await,
+ }
+ .inspect_err(|err| {
+ // Log a redacted failure event so dispatch errors are visible in
+ // host logs without spilling the request, credentials, working
+ // directory, or the error's full payload (CoreError::Domain can
+ // carry arbitrary `data`). Only the session id and the coarse
+ // variant classification are logged; the error itself propagates
+ // to the caller untouched.
+ let tag = match err {
+ crate::error::CoreError::TurnCancelled { .. } => "turn_cancelled",
+ crate::error::CoreError::Cancelled { .. } => "cancelled",
+ crate::error::CoreError::DeadlineExceeded { .. } => "deadline",
+ crate::error::CoreError::StructuredOutput { .. } => "structured_output",
+ crate::error::CoreError::BudgetExceeded { .. } => "budget_exceeded",
+ crate::error::CoreError::Domain { .. } => "domain",
+ crate::error::CoreError::Unavailable { .. } => "unavailable",
+ crate::error::CoreError::Rpc { .. } => "rpc",
+ crate::error::CoreError::Encode { .. } => "encode",
+ crate::error::CoreError::Decode { .. } => "decode",
+ crate::error::CoreError::InsecureRoute { .. } => "insecure_route",
+ crate::error::CoreError::InvalidRoute { .. } => "invalid_route",
+ crate::error::CoreError::AgentRemoved { .. } => "agent_removed",
+ };
+ log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");
+ });
+
- // Before the `?`. A turn that errored still spent what it spent, and
- // this is the only place both the sink and a failing result are in
- // hand -- `TurnOutcome` below is never built on that path.
- if let Some(meter) = meter {
- meter(
- usage
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .clone(),
- );
- }
+ let reply = reply.map_err(|error| {
+ match budget.as_ref().and_then(|budget| budget.ledger.refusal()) {
+ Some(source) => CoreError::BudgetExceeded {
+ method: AGENT_CHAT,
+ source,
+ },
+ None => error,
+ }
+ });
+ let (reply, report) = reply?;
+ let structured = if wants_json {
+ serde_json::from_str(reply.trim()).ok()
+ } else {
+ None
+ };
+
+ log::debug!(
+ "[embed][agent] turn_completed session={session_id} reply_len={} structured={} \
+ finish_reason={:?}",
+ reply.len(),
+ structured.is_some(),
+ report.as_ref().and_then(|r| r.finish_reason.as_deref())
+ );
+
+ let report = report.unwrap_or_default();
+ Ok(TurnOutcome {
+ reply,
+ session_id,
+ usage: usage
- .into_inner()
- .unwrap_or_else(std::sync::PoisonError::into_inner),
++ .lock()
++ .unwrap_or_else(std::sync::PoisonError::into_inner)
++ .clone(),
+ structured,
+ finish_reason: report.finish_reason,
+ answered_model: report.answered_model,
+ })
+ }
+
+ /// Refuse the per-turn options the target cannot honour, before anything
+ /// is dispatched.
+ fn validate_turn_options(&self) -> Result<(), CoreError> {
+ if self.structured_retries > 3 {
+ return Err(CoreError::StructuredOutput {
+ method: AGENT_CHAT,
+ failure: crate::structured::StructuredOutputFailure {
+ attempts: 0,
+ reason: crate::structured::StructuredFailureReason::RetryLimit,
+ finish_reason: None,
+ answered_model: None,
+ usage: None,
+ },
+ });
+ }
+ let refuse = |message: &str, kind: &str| {
+ Err(CoreError::Domain {
+ method: AGENT_CHAT,
+ message: message.to_owned(),
+ kind: Some(kind.to_owned()),
+ data: None,
+ expected_user_state: true,
+ })
+ };
+ if self
+ .top_p
+ .is_some_and(|p| !p.is_finite() || !(0.0..=1.0).contains(&p))
+ {
+ return refuse(
+ "top_p must be finite and between zero and one",
+ "invalid_model_parameter",
+ );
+ }
+ let host_only = match &self.target {
+ TurnTarget::Agent(agent) => agent.host_only,
+ TurnTarget::Runtime(_) => {
++ if self.tools.is_some() {
++ return refuse(
++ "per-turn host tools need a runtime-owned Agent",
++ "turn_tools_unsupported",
++ );
++ }
+ if self.response_format.is_some()
+ || self.max_tokens.is_some()
+ || self.top_p.is_some()
+ || self.structured_retries != 0
+ || !self.provider_options.is_null()
+ || self.require_tool_call
+ {
+ return refuse(
+ "response_format and max_tokens need a runtime-owned Agent",
+ "turn_shape_unsupported",
+ );
+ }
+ false
+ }
+ };
+ if self.untrusted_input && !host_only {
+ return refuse(
+ "untrusted_input is only allowed on a HostOnly agent",
+ "untrusted_input_requires_host_only",
+ );
+ }
+ Ok(())
+ }
+ }
diff --cc crates/openhuman-embed/src/turn_types.rs
index 0000000000,524c08e618..6ffe8dbee5
mode 000000,100644..100644
--- a/crates/openhuman-embed/src/turn_types.rs
+++ b/crates/openhuman-embed/src/turn_types.rs
@@@ -1,0 -1,231 +1,244 @@@
+ //! Credential-safe routes, wire turn requests and their typed outcomes.
+ use serde::{Deserialize, Serialize};
+
+ #[cfg(test)]
+ #[path = "../tests/unit/turn_usage.rs"]
+ mod usage_tests;
+
+ /// Overlay root provider accounting while retaining session context and children.
+ pub(super) fn overlay_response_usage(
+ captured: &mut Option<openhuman_core::agent::tinyagents::host::LastTurnUsage>,
+ reported: &openhuman_core::agent::tinyagents::response_shape::ResponseUsage,
+ ) {
+ let usage = captured.get_or_insert_with(Default::default);
+ // A session may have a legitimate catalog estimate when every provider
+ // omitted billing. Invalid receipts must still replace it with unknown.
+ let preserve_host_cost = reported.cost_usd.is_none() && !reported.has_cost_receipt;
+ let host_cost = usage.cost_usd;
+ let host_source = usage.cost_source;
+ let root = reported.failure_usage();
+ usage.input_tokens = root.input_tokens;
+ usage.output_tokens = root.output_tokens;
+ usage.cached_input_tokens = root.cached_input_tokens;
+ usage.reasoning_tokens = root.reasoning_tokens;
+ let mut cost = root.cost_usd;
+ let mut source = root.cost_source;
+ for child in &usage.subagents {
+ usage.input_tokens = usage.input_tokens.saturating_add(child.usage.input_tokens);
+ usage.output_tokens = usage
+ .output_tokens
+ .saturating_add(child.usage.output_tokens);
+ usage.cached_input_tokens = usage
+ .cached_input_tokens
+ .saturating_add(child.usage.cached_input_tokens);
+ cost = cost
+ .zip(child.usage.cost().usd())
+ .map(|(root, child)| root + child);
+ source = source.max(child.usage.cost_source);
+ }
+ usage.cost_usd = if preserve_host_cost { host_cost } else { cost };
+ usage.cost_source = if preserve_host_cost {
+ host_source
+ } else {
+ source
+ };
+ }
+
+ /// The routed chat entry point.
+ ///
+ /// Deliberately not `openhuman.agent_chat`, which is the same op with the
+ /// per-call route parameters removed — it describes a turn on the account's own
+ /// configured inference. An embedder that cannot say where a turn runs is
+ /// strictly less capable, so the facade uses the wider surface and lets
+ /// [`Route`] be `None` when the account's own route is what is wanted.
+ ///
+ /// `INFERENCE_AGENT_CHAT` is owned by the inference domain; referencing it
+ /// keeps this facade's dispatch string in lockstep with the registered
+ /// controller rather than duplicating the wire name.
+ ///
+ /// Where one turn's inference should go.
+ ///
+ /// Both halves are required together: an endpoint with no credential and a
+ /// credential with no endpoint are each half a statement, and the core ignores
+ /// the pair unless both arrive non-blank. Constructing this type is what makes
+ /// that requirement visible at compile time rather than at runtime.
+ #[derive(Clone, PartialEq, Eq)]
+ pub struct Route {
+ /// OpenAI-compatible base URL; `/chat/completions` is appended to it.
+ pub base_url: String,
+ /// The bearer presented to `base_url`.
+ pub api_key: String,
++ /// Headers scoped to this route and never persisted or logged as values.
++ pub headers: Vec<(String, String)>,
+ }
+
+ impl std::fmt::Debug for Route {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ // The bearer is a credential, and the base URL can itself carry
+ // userinfo (`https://user:pass@host`) or query credentials; a derived
+ // Debug would spill both into `Provider`'s Debug and from there into
+ // host logs and error paths.
+ f.debug_struct("Route")
+ .field("base_url", &sanitize_url_for_display(&self.base_url))
+ .field("api_key", &"<redacted>")
++ .field("headers", &self.headers.len())
+ .finish()
+ }
+ }
+
+ /// A URL safe to surface in logs/diagnostics: userinfo and query/fragment are
+ /// stripped, so `https://user:pass@host/v1?key=secret` renders as
+ /// `https://host/v1`. A value that does not parse as an absolute URL (a bare
+ /// host, a protocol-relative `//user:pass@host`, a malformed string) carries
+ /// components this function cannot prove are non-credential, so it is rendered
+ /// as the fixed `<redacted>` marker rather than echoed verbatim.
+ pub(crate) fn sanitize_url_for_display(url: &str) -> String {
+ let Ok(parsed) = url::Url::parse(url) else {
+ return "<redacted>".to_string();
+ };
+ let mut out = parsed;
+ let _ = out.set_username("");
+ let _ = out.set_password(None);
+ out.set_query(None);
+ out.set_fragment(None);
+ out.to_string()
+ }
+
+ /// True when `endpoint` is safe to carry a bearer credential.
+ ///
+ /// A bearer must never cross a cleartext channel to a remote party, so an
+ /// `https:` endpoint is always accepted. `http:` is accepted only for a
+ /// loopback host (`127.0.0.1`, `::1`, `localhost`), where the traffic never
+ /// leaves the machine and the "credential in the clear" concern does not
+ /// apply — local, self-hosted OpenAI-compatible servers are a supported
+ /// embedder configuration. Falls back to `false` when the value does not
+ /// parse as an absolute URL, so an unparseable route is refused rather than
+ /// silently allowed.
+ pub(crate) fn is_safe_endpoint_for_bearer(endpoint: &str) -> bool {
+ let Ok(url) = url::Url::parse(endpoint) else {
+ return false;
+ };
+ if url.scheme() == "https" {
+ return true;
+ }
+ if url.scheme() != "http" {
+ return false;
+ }
+ let Some(host) = url.host_str() else {
+ return false;
+ };
+ matches!(
+ host,
+ "127.0.0.1" | "localhost" | "::1" | "[::1]" | "[0:0:0:0:0:0:0:1]" | "0:0:0:0:0:0:0:1"
+ ) || host.starts_with("127.")
+ }
+
+ impl Route {
+ /// An OpenAI-compatible endpoint and the bearer that authenticates it.
+ pub fn openai_compatible(base_url: impl Into<String>, api_key: impl Into<String>) -> Self {
+ Self {
+ base_url: base_url.into(),
+ api_key: api_key.into(),
++ headers: Vec::new(),
+ }
+ }
++ /// Add a header sent only to this route's endpoint.
++ pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
++ self.headers.push((name.into(), value.into()));
++ self
++ }
+ }
+
+ /// Wire params for [`super::AGENT_CHAT`].
+ ///
+ /// Field names are the wire contract — see the module docs. `snake_case`, no
+ /// rename attribute, matching the controller's own struct.
+ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+ pub struct TurnRequest {
+ /// The user message driving this turn.
+ pub message: String,
+ /// Model id for this turn only. Blank or absent keeps the configured
+ /// default. Note it is **advisory**: a model no configured provider serves
+ /// is not an error, the core falls back.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub model_override: Option<String>,
+ /// Sampling temperature for this turn only.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub temperature: Option<f64>,
+ /// Conversation this turn belongs to. The core does **not** mint one, so
+ /// [`Turn::send`] does; see [`TurnOutcome::session_id`].
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+ /// Per-turn working directory for the agent's filesystem and shell tools.
+ /// Absent keeps the configured `action_dir`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cwd: Option<String>,
+ /// Endpoint half of the per-call route. Paired with `api_key`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub inference_url: Option<String>,
++ /// Additional headers owned by this turn route.
++ #[serde(default, skip_serializing_if = "Vec::is_empty")]
++ pub inference_headers: Vec<(String, String)>,
+ /// Bearer half of the per-call route. Paired with `inference_url`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub api_key: Option<String>,
+ /// The agent definition the turn runs as. Set by
+ /// [`Agent::turn`](crate::Agent::turn); absent runs the orchestrator.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub agent_id: Option<String>,
+ }
+
+ impl TurnRequest {
+ /// A turn carrying nothing but its message.
+ pub fn new(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ model_override: None,
+ temperature: None,
+ thread_id: None,
+ cwd: None,
+ inference_url: None,
++ inference_headers: Vec::new(),
+ api_key: None,
+ agent_id: None,
+ }
+ }
+ }
+
+ /// What one turn produced.
+ ///
+ /// Not `Eq`: [`usage`](Self::usage) carries a cost in dollars, and a float has
+ /// no total equality. Compare the fields that matter to you.
+ #[derive(Debug, Clone, PartialEq)]
+ pub struct TurnOutcome {
+ /// The assistant's final text.
+ pub reply: String,
+ /// The conversation this turn ran in — the caller's `session_id` when one
+ /// was supplied, otherwise the one minted for it. Pass it to the next
+ /// [`Turn::session`] to continue the conversation.
+ pub session_id: String,
+ /// What the turn spent: tokens, cost, context window, and any synchronous
+ /// children it ran.
+ ///
+ /// Present only when the turn returned. A turn that **failed** also spent
+ /// what it spent, and there is no outcome to carry it on -- use
+ /// [`Turn::meter`] for that, which fires either way.
+ ///
+ /// `None` when the turn ran against a caller-built runtime's orchestrator
+ /// rather than a runtime-owned [`Agent`](crate::Agent): that path answers
+ /// over `AGENT_CHAT`, whose reply is a string, so there is nothing to
+ /// report from. `None` also when the session reported nothing at all.
+ pub usage: Option<openhuman_core::agent::tinyagents::host::LastTurnUsage>,
+ /// [`reply`](Self::reply) parsed as JSON, when the turn asked for a JSON
+ /// [`response_format`](Turn::response_format) and the reply parses.
+ /// `None` otherwise -- including a reply the model did not shape, which
+ /// the host should treat as a failed structured answer.
+ pub structured: Option<serde_json::Value>,
+ /// Why the turn's final model call stopped (`stop`, `length`, ...), as
+ /// the provider reported it. `None` on a caller-built runtime's
+ /// orchestrator, which answers over RPC.
+ pub finish_reason: Option<String>,
+ /// The model the provider says answered the final call. `None` when the
+ /// provider did not say, or on a caller-built runtime's orchestrator.
+ pub answered_model: Option<String>,
+ }
diff --cc crates/openhuman-embed/tests/turn_cancellation.rs
index 2512c8f96f,8181a6da4a..e0ca914b68
--- a/crates/openhuman-embed/tests/turn_cancellation.rs
+++ b/crates/openhuman-embed/tests/turn_cancellation.rs
@@@ -99,14 -97,28 +110,33 @@@ async fn scenario()
sent.await.unwrap(),
Err(CoreError::TurnCancelled { .. })
));
+ assert_eq!(metered.load(std::sync::atomic::Ordering::SeqCst), 2);
assert_eq!(agent.run("still usable").await.unwrap().reply, "finished");
+ let observed = Arc::new(Outcomes::default());
+ // A whole-turn deadline drops inference and leaves the same agent reusable.
+ assert!(matches!(
+ blocked
+ .turn("deadline")
+ .timeout(Duration::from_millis(100))
+ .observer(observed.clone())
+ .send()
+ .await,
+ Err(CoreError::DeadlineExceeded { .. })
+ ));
+ assert_eq!(agent.run("after deadline").await.unwrap().reply, "finished");
+ assert_eq!(
+ *observed.0.lock().unwrap(),
+ vec![openhuman_embed::observe::TurnFailure::Deadline]
+ );
+
// An externally dropped send future also acknowledges cancellation.
+ let prior_requests = common::chat_requests(&slow).await.len();
- let mut turn = blocked.turn("drop this inference request");
+ let observed = metered.clone();
+ let mut turn = blocked.turn("drop this inference request").meter(move |_| {
+ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ });
++
let cancel = turn.cancellation_handle();
let sent = tokio::spawn(turn.send());
tokio::time::timeout(Duration::from_secs(5), async {
diff --cc docs/TEST-COVERAGE-MATRIX.md
index 82b8e25a71,9f9bb7eb64..96872f4804
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@@ -661,15 -661,15 +661,23 @@@ The thread JSONL store moved to `tinyag
| 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |
| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused |
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
+ | 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. |
+ | 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/turn_usage.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON; successful charged usage reaches outcome/meter, invalid buyer charges stay unknown, root overlays retain child spend and session context. |
+ | 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/completion_cost.rs` | ✅ | Ordered fallbacks, per-rung option/cap overrides, bounded case-insensitive length/max_tokens truncation retries, unpinned terminal provider selection, image/options preservation, accumulated buyer-first reported costs with invalid-charge guards, actual answering model and refusal of schema-valid output before successful tool execution |
+ | 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
+ | 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
+ | 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |
| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |
- | 16.1.14 | Agent and turn hook isolation | RI | `crates/openhuman-embed/tests/scoped_hooks.rs` | ✅ | Additive same-named callbacks, overlapping worker turns, one-turn callback lifetime, resumed-session snapshots, core-scheduled turn callbacks and reuse of a removed agent id without registry leakage |
- | 16.1.15 | Agent-turn route attribution headers | RU+RI | `crates/openhuman-embed/tests/route_headers.rs`, `crates/openhuman-embed/src/turn_tests.rs` | ✅ | Per-route headers reach only the named endpoint and turn, remain absent on other agents and backend requests, and are redacted in Debug; wire fields pinned against the registered controller schema |
- | 16.1.16 | Tool-hook turn identity and cwd | RI | `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Before and after hooks report the worker/session and working root used by builtin shell; a later turn returns to its agent default |
- | 16.1.17 | Inline agent/turn permission callback | RI | `crates/openhuman-embed/tests/inline_permissions.rs` | ✅ | UI decisions precede execution; denials narrow authority, concurrent agents remain independent, cancellation closes a pending receiver and a closed UI refuses execution |
- | 16.1.18 | Per-turn host-tool replacement | RI | `crates/openhuman-embed/tests/turn_tools.rs` | ✅ | Replacement and empty-belt revocation apply to resumed HostOnly and mixed definitions, without restoring historical declarations or affecting other agents and later turns |
- | 16.1.19 | Scoped usage observation and budget stop | RI | `crates/openhuman-embed/tests/usage_hooks.rs` | ✅ | Cumulative charged cost and tokens, known-zero versus unpriced calls, per-agent policy and per-turn observer isolation; no summary-repair model calls after a stop |
- | 16.1.20 | Scoped builtin command environments | RI | `crates/openhuman-embed/tests/tool_environment.rs`, `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Overlapping subprocess maps exclude host inheritance on Unix; a real shell receives its turn's variables while excluding host HOME and preserving command-owned runtime/security additions |
++| 16.1.21 | Agent and turn hook isolation | RI | `crates/openhuman-embed/tests/scoped_hooks.rs` | ✅ | Additive same-named callbacks, overlapping worker turns, one-turn callback lifetime, resumed-session snapshots, core-scheduled turn callbacks and reuse of a removed agent id without registry leakage |
++| 16.1.22 | Agent-turn route attribution headers | RU+RI | `crates/openhuman-embed/tests/route_headers.rs`, `crates/openhuman-embed/src/turn_tests.rs` | ✅ | Per-route headers reach only the named endpoint and turn, remain absent on other agents and backend requests, and are redacted in Debug; wire fields pinned against the registered controller schema |
++| 16.1.23 | Tool-hook turn identity and cwd | RI | `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Before and after hooks report the worker/session and working root used by builtin shell; a later turn returns to its agent default |
++| 16.1.24 | Inline agent/turn permission callback | RI | `crates/openhuman-embed/tests/inline_permissions.rs` | ✅ | UI decisions precede execution; denials narrow authority, concurrent agents remain independent, cancellation closes a pending receiver and a closed UI refuses execution |
++| 16.1.25 | Per-turn host-tool replacement | RI | `crates/openhuman-embed/tests/turn_tools.rs` | ✅ | Replacement and empty-belt revocation apply to resumed HostOnly and mixed definitions, without restoring historical declarations or affecting other agents and later turns |
++| 16.1.26 | Scoped usage observation and budget stop | RI | `crates/openhuman-embed/tests/usage_hooks.rs` | ✅ | Cumulative charged cost and tokens, known-zero versus unpriced calls, per-agent policy and per-turn observer isolation; no summary-repair model calls after a stop |
++| 16.1.27 | Scoped builtin command environments | RI | `crates/openhuman-embed/tests/tool_environment.rs`, `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Overlapping subprocess maps exclude host inheritance on Unix; a real shell receives its turn's variables while excluding host HOME and preserving command-owned runtime/security additions |
+ | 16.1.20 | Host turn observer privacy and runtime propagation | RI | `crates/openhuman-embed/tests/turn_observers.rs`, `crates/openhuman-embed/tests/observed_turns.rs` | ✅ | Sanitized terminal failures, opt-in payloads, root runtime scope propagation, real model/tool callbacks and answering-model usage |
+
+
### 16.2 Dynamic runtime and agent configuration
| ID | Feature | Layer | Test path(s) | Status | Notes |
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 45d30d0c0d,745ad99fcf..f06cfcb5e2
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -159,11 -160,7 +160,8 @@@ for (const [directory, table] of
["tests", "test"],
["examples", "example"],
]) {
- const files = new Set(
- (fs.existsSync(directory) ? fs.readdirSync(directory) : [])
- .filter((name) => name.endsWith(".rs"))
- .map((name) => name.slice(0, -3)),
- );
+ const files = rootRustTargetNames(directory);
++
const declared = declaredTargets(table);
for (const name of files) {
if (!declared.has(name))