The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(embed): bound observed turn future stack usage
Steven Enamakelb713104145fb
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 5117d95c17..ac47a3c797 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -38,8 +38,6 @@use std::path::{Path, PathBuf};use std::sync::Arc;-use serde::{Deserialize, Serialize};-use super::call::call;use super::error::CoreError;use openhuman_core::agent::progress::AgentProgress;@@ -47,191 +45,12 @@ use openhuman_core::agent::turn_origin::AgentTurnOrigin;use openhuman_core::core::runtime::CoreRuntime;use openhuman_core::inference::INFERENCE_AGENT_CHAT as AGENT_CHAT;-/// 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,-}--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>")- .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(),- }- }-}--/// Wire params for [`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>,- /// 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,- 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>,-}+#[path = "turn_types.rs"]+mod types;+pub(crate) use types::{is_safe_endpoint_for_bearer, sanitize_url_for_display};+pub use types::{Route, TurnOutcome, TurnRequest};+#[path = "turn_control.rs"]+mod control;/// Where a [`Turn`] is dispatched.pub(crate) enum TurnTarget {@@ -500,343 +319,6 @@ impl Turn {pub fn request(&self) -> &TurnRequest {&self.request}-- /// Run the turn.- ///- /// Establishes the origin and progress scopes described in the module docs,- /// then dispatches through [`call`](super::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> {- // 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_controlled().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_controlled(),- )- .await- }-- async fn send_controlled(mut self) -> Result<TurnOutcome, CoreError> {- let timeout = self.timeout.take();- let cancellation = match self.cancellation.take() {- Some(cancellation) => cancellation,- None if timeout.is_some() => crate::TurnCancellation::default(),- None => return self.send_inner().await,- };- let _guard = cancellation.enter();- let outcome = cancellation- .cleanup()- .scope(async {- tokio::select! {- biased;- _ = cancellation.cancelled() => {- log::debug!("[embed][agent] turn cancelled");- Err(CoreError::TurnCancelled { method: AGENT_CHAT })- }- _ = async {- match timeout {- Some(duration) => tokio::time::sleep(duration).await,- None => std::future::pending().await,- }- } => Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),- outcome = Box::pin(self.send_inner()) => 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> {- // 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,- 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,- };- 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 = 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),- 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,- })- };- let host_only = match &self.target {- TurnTarget::Agent(agent) => agent.host_only,- TurnTarget::Runtime(_) => {- if self.response_format.is_some()- || self.max_tokens.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(())- }}/// Run `request` on `target`.diff --git a/crates/openhuman-embed/src/turn_control.rs b/crates/openhuman-embed/src/turn_control.rsnew file mode 100644index 0000000000..c754e757f5--- /dev/null+++ b/crates/openhuman-embed/src/turn_control.rs@@ -0,0 +1,348 @@+//! Whole-turn validation, observation, cancellation, deadlines and dispatch.+use super::*;++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> {+ // 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_controlled().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_controlled(),+ )+ .await+ }++ // 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 timeout = self.timeout.take();+ let cancellation = match self.cancellation.take() {+ Some(cancellation) => cancellation,+ None if timeout.is_some() => crate::TurnCancellation::default(),+ None => return Box::pin(self.send_inner()).await,+ };+ let _guard = cancellation.enter();+ let outcome = cancellation+ .cleanup()+ .scope(async {+ tokio::select! {+ biased;+ _ = cancellation.cancelled() => {+ log::debug!("[embed][agent] turn cancelled");+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })+ }+ _ = async {+ match timeout {+ Some(duration) => tokio::time::sleep(duration).await,+ None => std::future::pending().await,+ }+ } => Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),+ outcome = Box::pin(self.send_inner()) => 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> {+ // 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,+ 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,+ };+ 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 = 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),+ 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,+ })+ };+ let host_only = match &self.target {+ TurnTarget::Agent(agent) => agent.host_only,+ TurnTarget::Runtime(_) => {+ if self.response_format.is_some()+ || self.max_tokens.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 --git a/crates/openhuman-embed/src/turn_types.rs b/crates/openhuman-embed/src/turn_types.rsnew file mode 100644index 0000000000..208c23d299--- /dev/null+++ b/crates/openhuman-embed/src/turn_types.rs@@ -0,0 +1,188 @@+//! Credential-safe routes, wire turn requests and their typed outcomes.+use serde::{Deserialize, Serialize};++/// 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,+}++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>")+ .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(),+ }+ }+}++/// 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>,+ /// 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,+ 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 --git a/crates/openhuman-embed/tests/structured_turns.rs b/crates/openhuman-embed/tests/structured_turns.rsindex 371cdd42df..28958a4e38 100644--- a/crates/openhuman-embed/tests/structured_turns.rs+++ b/crates/openhuman-embed/tests/structured_turns.rs@@ -9,8 +9,8 @@mod common;-use std::sync::Arc;use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;use common::{chat_requests, offline_config, runtime, stub_backend};use openhuman_embed::complete::ResponseFormat;@@ -18,7 +18,7 @@ use openhuman_embed::{AgentDefinitionSpec, AgentSpec, CoreError, HostTurnTools, Provider, Runtime, Tool,ToolScopeSpec, Workspace,};-use serde_json::{Value, json};+use serde_json::{json, Value};use wiremock::matchers::{method, path};use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};diff --git a/crates/openhuman-embed/tests/structured_validation.rs b/crates/openhuman-embed/tests/structured_validation.rsindex 39f28bfb54..3f69b261d0 100644--- a/crates/openhuman-embed/tests/structured_validation.rs+++ b/crates/openhuman-embed/tests/structured_validation.rs@@ -2,9 +2,9 @@mod common;-use openhuman_embed::Route;use openhuman_embed::complete::{ChatMessage, Completer, CompletionRequest, ResponseFormat};-use serde_json::{Value, json};+use openhuman_embed::Route;+use serde_json::{json, Value};use wiremock::matchers::{method, path};use wiremock::{Mock, MockServer, ResponseTemplate};