Skip to content

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

fix(embed): make the host-tools seam do what it says

sanil-23194f509c751a
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 981eceac2b..c3f2491a6a 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -101,6 +101,5 @@ mod tests;
#[allow(unused_imports)]
pub use session_host::{
- HostTools, HostTurnTools, OpenHumanSessionHost, SessionHostBuilder, TurnContext,
- TurnOverrides,
+ HostTools, HostTurnTools, OpenHumanSessionHost, SessionHostBuilder, TurnContext, TurnOverrides,
};
diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs
index 1b369b42d2..2c3e073732 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs
@@ -193,3 +193,59 @@ fn the_factory_is_told_the_session_it_is_building_for() {
"the factory is told the agent every time, and the session when one was named"
);
}
+
+/// A host tool wins a collision with a config-derived tool of the same name.
+///
+/// The rule only holds because the host belt is spliced in *first* and
+/// `dedup_visible_tool_specs` keeps the first occurrence. Append instead and
+/// the config spec is advertised while the host believes it replaced it --
+/// the model told about one tool and a different one answering, which is the
+/// version of this bug that is hardest to see from the outside.
+#[test]
+fn a_host_tool_overrides_a_config_tool_of_the_same_name() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ // A name the config-derived belt already carries, so the two collide.
+ let contested =
+ crate::agent::OpenHumanSessionHost::from_config_with_definition(&config, &definition())
+ .expect("build a session without a host belt")
+ .visible_tool_specs_arc()
+ .first()
+ .map(|spec| spec.name.clone())
+ .expect("the config-derived belt advertises at least one tool");
+
+ let host: crate::agent::HostTools = {
+ let contested = contested.clone();
+ Arc::new(move |_| {
+ crate::agent::HostTurnTools::advertised(vec![Box::new(Marker(Box::leak(
+ contested.clone().into_boxed_str(),
+ )))])
+ })
+ };
+
+ let agent = crate::agent::OpenHumanSessionHost::from_config_with_host_tools(
+ &config,
+ &definition(),
+ &host,
+ None,
+ )
+ .expect("build a session whose host belt collides");
+
+ let advertised: Vec<_> = agent
+ .visible_tool_specs_arc()
+ .iter()
+ .filter(|spec| spec.name == contested)
+ .map(|spec| spec.description.clone())
+ .collect();
+
+ assert_eq!(
+ advertised.len(),
+ 1,
+ "a collision must leave exactly one advertised spec for {contested}"
+ );
+ assert_eq!(
+ advertised[0], "a test marker",
+ "the surviving spec must be the host's, not the config-derived one"
+ );
+}
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 e8c15d4bdc..55a5238cf6 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -167,7 +167,14 @@ impl OpenHumanSessionHost {
host: &super::HostTools,
session_id: Option<&str>,
) -> Result<Self> {
- Self::build_session_agent_inner(config, &definition.id, Some(definition), false, Some(host), session_id)
+ Self::build_session_agent_inner(
+ config,
+ &definition.id,
+ Some(definition),
+ false,
+ Some(host),
+ session_id,
+ )
}
/// Internal constructor that consumes the optionally-resolved agent
@@ -1028,13 +1035,19 @@ impl OpenHumanSessionHost {
);
effective_agent_config.max_tool_iterations = def_cap;
}
- // The host's own belt, last, so a host tool wins a name collision with
- // a config-derived one: the host asked for this object specifically,
- // and `dedup_visible_tool_specs` keeps the first occurrence, so the
- // advertised spec must be the one that will actually run.
- let host_policy = match host.map(|build| {
- build(super::host_tools::TurnContext::new(agent_id, session_id))
- }) {
+ // The host's own belt goes FIRST, so a host tool wins a name collision
+ // with a config-derived one: the host named this object specifically,
+ // and a host that cannot override a tool it collides with has no way
+ // to correct one.
+ //
+ // First, not last, because `dedup_visible_tool_specs` keeps the first
+ // occurrence -- appending would advertise the config-derived spec
+ // while the host believed it had replaced it, which is the failure
+ // that is hardest to see: the model is told about one tool and a
+ // different one answers.
+ let host_policy = match host
+ .map(|build| build(super::host_tools::TurnContext::new(agent_id, session_id)))
+ {
Some(host_tools) if !host_tools.is_empty() => {
log::debug!(
"[agent::builder] host supplied {} tool(s) for agent_id={agent_id}: {:?}",
@@ -1045,8 +1058,8 @@ impl OpenHumanSessionHost {
.map(|tool| tool.name())
.collect::<Vec<_>>(),
);
- let mut host_tools = host_tools;
- tools.append(&mut host_tools.tools);
+ let host_tools = host_tools;
+ tools.splice(0..0, host_tools.tools);
visible.extend(host_tools.visible);
host_tools.policy
}
@@ -1087,10 +1100,15 @@ impl OpenHumanSessionHost {
if let Some(ps) = payload_summarizer {
builder = builder.payload_summarizer(ps);
}
- // The host's gate, when it sent one. Ahead of the session's own by
- // construction: a host that supplies both a belt and a gate is saying
- // what may run on that belt, and a config-derived policy knows nothing
- // about tools it did not produce.
+ // The host's gate, when it sent one. This REPLACES the session's own
+ // policy rather than sitting in front of it -- `tool_policy` assigns.
+ //
+ // That is deliberate: a host supplying a gate is saying what may run
+ // on this session, not only on its own belt, and the episode case
+ // needs exactly that (admit my tools, ask me about everything else).
+ // But it means a host that gates only its own names denies every
+ // config-derived tool, so the host composes, not this builder. See
+ // `HostTurnTools::with_policy`, which says so.
if let Some(policy) = host_policy {
builder = builder.tool_policy(policy);
}
diff --git a/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs b/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs
index 694d8d9c08..05e14aad74 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs
@@ -35,15 +35,17 @@ use crate::agent::tool_policy::ToolPolicy;
///
/// `visible` is the provider-visible allow-list to union into the session's
/// own; leaving it empty makes the tools reachable but unadvertised, which is
-/// rarely what a host wants. `policy` is consulted for these tools before the
-/// session's own gate.
+/// rarely what a host wants. `policy`, when set, becomes the session's gate --
+/// see [`with_policy`](Self::with_policy), which is not what "host tools"
+/// might suggest.
#[derive(Default)]
pub struct HostTurnTools {
- /// The tools themselves, appended to the belt config produced.
+ /// The tools themselves, placed **ahead of** the config-derived belt so a
+ /// host tool wins a collision on its name.
pub tools: Vec<Box<dyn Tool>>,
/// Names to add to the provider-visible allow-list.
pub visible: HashSet<String>,
- /// An admission gate consulted ahead of the session's own, if any.
+ /// The session's admission gate, if the host sets one.
pub policy: Option<Arc<dyn ToolPolicy>>,
}
@@ -59,7 +61,20 @@ impl HostTurnTools {
}
}
- /// Sets the admission gate consulted ahead of the session's own.
+ /// Sets the gate for the whole session.
+ ///
+ /// # This replaces; it does not wrap
+ ///
+ /// The policy set here becomes the session's tool policy outright -- it is
+ /// not consulted first and then deferred to a config-derived one, because
+ /// there is no composition step to defer through.
+ ///
+ /// That is what the episode case wants: a gate saying *admit my belt, and
+ /// ask me about everything else* is a statement about the whole session,
+ /// not only about the tools the host supplied. But it means **a host that
+ /// gates only its own names denies every other tool on the belt**. If the
+ /// session should keep an existing policy for calls the host does not own,
+ /// the host composes the two and passes the result here.
#[must_use]
pub fn with_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
self.policy = Some(policy);
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index 47727fd53b..2e930970e3 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@ -308,7 +308,9 @@ pub async fn agent_chat_for(
usage: Some(sink), ..
} = target
{
- *sink.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = agent.last_turn_usage();
+ *sink
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = agent.last_turn_usage();
}
let response = outcome.map_err(|e| e.to_string())?;
Ok(RpcOutcome::single_log(response, "agent chat completed"))
diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs
index c05dc2ac0b..cbba62ba2f 100644
--- a/crates/openhuman-embed/src/agent/spec.rs
+++ b/crates/openhuman-embed/src/agent/spec.rs
@@ -247,7 +247,9 @@ impl AgentSpec {
#[must_use]
pub fn tools(
mut self,
- f: impl for<'a> Fn(openhuman_core::agent::TurnContext<'a>) -> openhuman_core::agent::HostTurnTools
+ f: impl for<'a> Fn(
+ openhuman_core::agent::TurnContext<'a>,
+ ) -> openhuman_core::agent::HostTurnTools
+ Send
+ Sync
+ 'static,
diff --git a/crates/openhuman-embed/src/harness/builder.rs b/crates/openhuman-embed/src/harness/builder.rs
index 05398630a2..231c763447 100644
--- a/crates/openhuman-embed/src/harness/builder.rs
+++ b/crates/openhuman-embed/src/harness/builder.rs
@@ -129,7 +129,9 @@ impl HarnessBuilder {
#[must_use]
pub fn tools(
mut self,
- f: impl for<'a> Fn(openhuman_core::agent::TurnContext<'a>) -> openhuman_core::agent::HostTurnTools
+ f: impl for<'a> Fn(
+ openhuman_core::agent::TurnContext<'a>,
+ ) -> openhuman_core::agent::HostTurnTools
+ Send
+ Sync
+ 'static,
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 63f8169a7f..7c760ab7ca 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -210,9 +210,9 @@ pub struct TurnOutcome {
/// What the turn spent: tokens, cost, context window, and any synchronous
/// children it ran.
///
- /// A host that meters its agents needs this at the only moment it exists --
- /// when the turn ends -- and it is reported for a failed turn too, because
- /// a turn that ended badly still spent what it spent.
+ /// 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
@@ -242,6 +242,7 @@ pub struct Turn {
origin: Option<AgentTurnOrigin>,
progress: Option<tokio::sync::mpsc::Sender<AgentProgress>>,
seed: Option<Vec<(String, String)>>,
+ meter: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,
}
impl Turn {
@@ -253,6 +254,7 @@ impl Turn {
origin: None,
progress: None,
seed: None,
+ meter: None,
}
}
@@ -310,6 +312,39 @@ impl Turn {
self
}
+ /// Report what this turn spent, whether or not it succeeded.
+ ///
+ /// [`TurnOutcome::usage`] carries the same figures, but only when there is
+ /// an outcome to carry them on. A host that meters its agents cannot let a
+ /// failed turn go unbilled -- a turn that ran, called tools and then
+ /// errored spent real tokens, and an agent whose failures are free is an
+ /// agent whose costs are understated exactly where they run highest.
+ ///
+ /// `f` is called once, after the turn settles and before its error (if
+ /// any) is returned -- so a turn that ran and then failed is reported.
+ ///
+ /// It does **not** fire for a turn refused before dispatch, such as one
+ /// whose [`route`](Self::route) pairs a bearer with a plain-http endpoint:
+ /// nothing ran, so there is nothing to bill. `None` means the turn ran but
+ /// the session reported no usage, which is not the same as zero.
+ ///
+ /// ```no_run
+ /// # use openhuman_embed::Agent;
+ /// # async fn go(agent: &Agent) -> anyhow::Result<()> {
+ /// let (tx, rx) = std::sync::mpsc::channel();
+ /// let result = agent.turn("go")
+ /// .meter(move |spent| { let _ = tx.send(spent); })
+ /// .send()
+ /// .await;
+ /// let spent = rx.recv().ok().flatten(); // arrives even if `result` is an error
+ /// # let _ = (result, spent); Ok(()) }
+ /// ```
+ #[must_use]
+ pub fn meter(mut self, f: impl FnOnce(Option<LastTurnUsage>) + Send + 'static) -> Self {
+ self.meter = Some(Box::new(f));
+ self
+ }
+
/// Pin this turn to a model id.
pub fn model(mut self, model: impl Into<String>) -> Self {
self.request.model_override = Some(model.into());
@@ -421,6 +456,7 @@ impl Turn {
// 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 dispatch = dispatch(self.target, self.request, self.seed.take(), &usage);
let reply = match (self.origin, self.progress) {
@@ -456,7 +492,20 @@ impl Turn {
crate::error::CoreError::InvalidRoute { .. } => "invalid_route",
};
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?;
log::debug!(
"[embed][agent] turn_completed session={session_id} reply_len={}",
@@ -481,7 +530,9 @@ impl Turn {
/// target reaches `agent_chat_for` natively under the agent's own context —
/// the definition it carries cannot travel as JSON — so it applies the
/// DomainSet gate itself before touching the core.
-type UsageSink = std::sync::Mutex<Option<openhuman_core::agent::tinyagents::host::LastTurnUsage>>;
+use openhuman_core::agent::tinyagents::host::LastTurnUsage;
+
+type UsageSink = std::sync::Mutex<Option<LastTurnUsage>>;
async fn dispatch(
target: TurnTarget,