Skip to content

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

feat(embed): tell the tool factory its occasion, and report what a turn spent

sanil-23aaf8497a8ebb
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index cad17b2004..981eceac2b 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -101,5 +101,6 @@ mod tests;
#[allow(unused_imports)]
pub use session_host::{
- HostTools, HostTurnTools, OpenHumanSessionHost, SessionHostBuilder, 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 4843b79e64..1b369b42d2 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
@@ -46,7 +46,7 @@ fn definition() -> crate::agent::harness::definition::AgentDefinition {
fn a_host_tool_is_on_the_belt_and_advertised() {
let tmp = tempfile::TempDir::new().unwrap();
let config = test_config(&tmp);
- let host: crate::agent::HostTools = Arc::new(|| {
+ let host: crate::agent::HostTools = Arc::new(|_| {
crate::agent::HostTurnTools::advertised(vec![Box::new(Marker("oc_marker_tool"))])
});
@@ -54,6 +54,7 @@ fn a_host_tool_is_on_the_belt_and_advertised() {
&config,
&definition(),
&host,
+ None,
)
.expect("build a session with a host belt");
@@ -78,7 +79,7 @@ fn the_factory_runs_once_per_session_build() {
let calls = Arc::new(AtomicUsize::new(0));
let host: crate::agent::HostTools = {
let calls = Arc::clone(&calls);
- Arc::new(move || {
+ Arc::new(move |_| {
calls.fetch_add(1, Ordering::SeqCst);
crate::agent::HostTurnTools::advertised(vec![Box::new(Marker("oc_marker_tool"))])
})
@@ -89,6 +90,7 @@ fn the_factory_runs_once_per_session_build() {
&config,
&definition(),
&host,
+ None,
)
.expect("build a session with a host belt");
}
@@ -118,3 +120,76 @@ fn no_host_belt_leaves_the_advertised_set_alone() {
"nothing should advertise a host tool that was never supplied"
);
}
+
+/// The factory is told which conversation it is building for.
+///
+/// Without this a host keying its belt on the chat has to read the occasion
+/// out of state it closed over, which is correct only while the agent serves
+/// one conversation at a time. Two at once and that state is a race, so the
+/// occasion has to arrive as an argument.
+#[test]
+fn the_factory_is_told_the_session_it_is_building_for() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let seen = Arc::new(std::sync::Mutex::new(Vec::<(String, Option<String>)>::new()));
+
+ let host: crate::agent::HostTools = {
+ let seen = Arc::clone(&seen);
+ Arc::new(move |turn: crate::agent::TurnContext<'_>| {
+ seen.lock().unwrap().push((
+ turn.agent_id().to_owned(),
+ turn.session_id().map(str::to_owned),
+ ));
+ // The belt itself varies with the occasion, which is the point.
+ let name = match turn.session_id() {
+ Some("desk:eng") => "oc_desk_tool",
+ _ => "oc_plain_tool",
+ };
+ crate::agent::HostTurnTools::advertised(vec![Box::new(Marker(name))])
+ })
+ };
+
+ let desked = crate::agent::OpenHumanSessionHost::from_config_with_host_tools(
+ &config,
+ &definition(),
+ &host,
+ Some("desk:eng"),
+ )
+ .expect("build a session for a named conversation");
+
+ assert!(
+ desked
+ .visible_tool_specs_arc()
+ .iter()
+ .any(|spec| spec.name == "oc_desk_tool"),
+ "the belt must be able to differ per conversation"
+ );
+
+ let unnamed = crate::agent::OpenHumanSessionHost::from_config_with_host_tools(
+ &config,
+ &definition(),
+ &host,
+ None,
+ )
+ .expect("build a session with no conversation named");
+
+ assert!(
+ unnamed
+ .visible_tool_specs_arc()
+ .iter()
+ .any(|spec| spec.name == "oc_plain_tool"),
+ "an unnamed turn is a case the host decides, not one it cannot observe"
+ );
+
+ let seen = seen.lock().unwrap();
+ assert_eq!(
+ seen.iter()
+ .map(|(agent, session)| (agent.as_str(), session.as_deref()))
+ .collect::<Vec<_>>(),
+ vec![
+ (definition().id.as_str(), Some("desk:eng")),
+ (definition().id.as_str(), None),
+ ],
+ "the factory is told the agent every time, and the session when one was named"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
index 837acb6b1b..d9ff6fd4f8 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs
@@ -25,6 +25,7 @@ async fn memory_write_instruction_is_present_with_learning_disabled() {
Some(&orchestrator),
false,
None,
+ None,
)
.expect("build session");
@@ -51,6 +52,7 @@ async fn memory_write_instruction_names_only_the_write_tool_a_scoped_agent_holds
Some(&archivist),
false,
None,
+ None,
)
.expect("build archivist session");
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 5e4c5bd3bd..e8c15d4bdc 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -113,7 +113,7 @@ impl OpenHumanSessionHost {
.unwrap_or(config.default_temperature)
);
- Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false, None)
+ Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false, None, None)
}
/// Build a session agent from a definition the caller already holds,
@@ -135,7 +135,7 @@ impl OpenHumanSessionHost {
definition.id,
definition.sandbox_mode,
);
- Self::build_session_agent_inner(config, &definition.id, Some(definition), false, None)
+ Self::build_session_agent_inner(config, &definition.id, Some(definition), false, None, None)
}
/// [`Self::from_config_with_definition`], plus a belt the host supplies
@@ -156,12 +156,18 @@ impl OpenHumanSessionHost {
/// # Errors
///
/// As [`Self::from_config_with_definition`].
+ ///
+ /// `session_id` is the conversation the turn will run in, when the caller
+ /// named one. It reaches the factory as [`TurnContext::session_id`] and is
+ /// the only thing that lets a belt differ per conversation rather than per
+ /// agent; pass `None` where no session is named yet.
pub fn from_config_with_host_tools(
config: &Config,
definition: &crate::agent::harness::definition::AgentDefinition,
host: &super::HostTools,
+ session_id: Option<&str>,
) -> Result<Self> {
- Self::build_session_agent_inner(config, &definition.id, Some(definition), false, Some(host))
+ Self::build_session_agent_inner(config, &definition.id, Some(definition), false, Some(host), session_id)
}
/// Internal constructor that consumes the optionally-resolved agent
@@ -180,6 +186,7 @@ impl OpenHumanSessionHost {
target_def: Option<&crate::agent::harness::definition::AgentDefinition>,
read_only_tools_only: bool,
host: Option<&super::HostTools>,
+ session_id: Option<&str>,
) -> Result<Self> {
let workspace_descriptor = derive_turn_workspace_descriptor();
@@ -1025,7 +1032,9 @@ impl OpenHumanSessionHost {
// 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()) {
+ 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}: {:?}",
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 05c96f77a2..694d8d9c08 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
@@ -90,6 +90,53 @@ impl std::fmt::Debug for HostTurnTools {
}
}
+/// What the turn being built is, as far as a host's tool factory needs to know.
+///
+/// A belt that varies has to vary on *something*. Without this the factory is
+/// called with no argument and has to infer its own occasion from state it
+/// closed over, which works only while the agent serves one conversation at a
+/// time -- the moment it serves two, a belt bound to "the current episode" is
+/// a race rather than a decision.
+///
+/// Non-exhaustive: this describes an occasion, and occasions gain detail.
+/// Construct it with [`TurnContext::new`] and read it through the accessors so
+/// a later field cannot break a host that matched on it.
+#[derive(Debug, Clone, Copy)]
+#[non_exhaustive]
+pub struct TurnContext<'a> {
+ agent_id: &'a str,
+ session_id: Option<&'a str>,
+}
+
+impl<'a> TurnContext<'a> {
+ /// The turn's occasion: which agent, and which conversation if one was named.
+ #[must_use]
+ pub fn new(agent_id: &'a str, session_id: Option<&'a str>) -> Self {
+ Self {
+ agent_id,
+ session_id,
+ }
+ }
+
+ /// The agent definition this turn runs as.
+ #[must_use]
+ pub fn agent_id(&self) -> &'a str {
+ self.agent_id
+ }
+
+ /// The conversation this turn runs in, as the caller named it.
+ ///
+ /// `None` when no session was named -- a one-shot turn, or a path that
+ /// mints an id only after the session is built. A host keying its belt on
+ /// this should decide what an unnamed turn gets rather than assume it
+ /// cannot happen.
+ #[must_use]
+ pub fn session_id(&self) -> Option<&'a str> {
+ self.session_id
+ }
+}
+
/// Builds one turn's host belt. Invoked once per session build, so a host may
-/// return a different belt each time.
-pub type HostTools = Arc<dyn Fn() -> HostTurnTools + Send + Sync>;
+/// return a different belt each time -- see [`TurnContext`] for what it is told
+/// about the turn it is building for.
+pub type HostTools = Arc<dyn for<'a> Fn(TurnContext<'a>) -> HostTurnTools + Send + Sync>;
diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
index 8c424d11b7..fa09861ce1 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs
@@ -15,7 +15,7 @@ mod helpers;
mod host_tools;
mod setters;
-pub use host_tools::{HostTools, HostTurnTools};
+pub use host_tools::{HostTools, HostTurnTools, TurnContext};
#[cfg(test)]
mod builder_tests;
diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rs
index 5bbc774696..49f0923162 100644
--- a/crates/openhuman-core/src/agent/session_host/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@ -31,7 +31,7 @@
//! The child files are an implementation detail.
pub(crate) use builder::provider_role_for_definition;
-pub use builder::{HostTools, HostTurnTools};
+pub use builder::{HostTools, HostTurnTools, TurnContext};
mod builder;
mod codec;
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 0e1624f72a..47727fd53b 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
@@ -102,6 +102,17 @@ pub enum AgentChatTarget<'a> {
///
/// `None` leaves resume untouched, which is every existing caller.
seed: Option<&'a [(String, String)]>,
+ /// Where to report what the turn spent.
+ ///
+ /// An out-parameter because this is the only target that can fill it:
+ /// the turn runs in-process here, so the session that counted the
+ /// tokens is still in hand when it ends. The other two answer over
+ /// `AGENT_CHAT`, whose reply is a string.
+ ///
+ /// Written whether the turn succeeded or failed -- a turn that ended
+ /// badly still spent what it spent, and a host that meters only
+ /// successes bills nothing for the ones that cost most.
+ usage: Option<&'a std::sync::Mutex<Option<crate::agent::tinyagents::host::LastTurnUsage>>>,
},
}
@@ -117,11 +128,13 @@ impl std::fmt::Debug for AgentChatTarget<'_> {
definition,
host,
seed,
+ usage,
} => f
.debug_struct("Definition")
.field("definition", &definition.id)
.field("host_tools", &host.is_some())
.field("seed_rows", &seed.map_or(0, <[(String, String)]>::len))
+ .field("meters", &usage.is_some())
.finish(),
}
}
@@ -130,6 +143,7 @@ impl std::fmt::Debug for AgentChatTarget<'_> {
fn build_turn_agent(
config: &Config,
target: &AgentChatTarget<'_>,
+ session_id: Option<&str>,
) -> Result<OpenHumanSessionHost, String> {
match target {
AgentChatTarget::Orchestrator => OpenHumanSessionHost::from_config(config),
@@ -140,9 +154,9 @@ fn build_turn_agent(
AgentChatTarget::Definition {
definition, host, ..
} => match host {
- Some(host) => {
- OpenHumanSessionHost::from_config_with_host_tools(config, definition, host)
- }
+ Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
+ config, definition, host, session_id,
+ ),
None => OpenHumanSessionHost::from_config_with_definition(config, definition),
},
}
@@ -188,6 +202,13 @@ pub async fn agent_chat_for(
if let Some(route) = route {
crate::config::schema::ephemeral_route::apply(config, route);
}
+ // The conversation this turn runs in, normalised once: the factory below is
+ // told the same id `set_thread_id` will bind, so a belt keyed on the
+ // session cannot disagree with the session it is built for.
+ let turn_session_id = thread_id
+ .as_deref()
+ .map(str::trim)
+ .filter(|id| !id.is_empty());
let turn_cwd = resolve_turn_cwd(cwd)?;
let mut agent = match turn_cwd.as_ref() {
// Per-turn root. Building from a config clone whose `action_dir` is the
@@ -206,14 +227,14 @@ pub async fn agent_chat_for(
"[inference] agent_chat rooting turn tools at cwd={}",
root.display()
);
- let mut agent = build_turn_agent(&scoped, &target)?;
+ let mut agent = build_turn_agent(&scoped, &target, turn_session_id)?;
// Also thread it as the turn's workspace descriptor so acting tools
// that read `ToolExecutionContext::workspace` (shell) resolve their
// default cwd here, and so spawned sub-agents inherit the same root.
agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(root.clone())));
agent
}
- None => build_turn_agent(config, &target)?,
+ None => build_turn_agent(config, &target, turn_session_id)?,
};
// Thread-correct resume. `OpenHumanSessionHost::turn` would otherwise auto-load the
// newest transcript for the agent *name*, which is another thread's
@@ -280,7 +301,16 @@ pub async fn agent_chat_for(
effective_agent_chat_origin(),
agent.run_single(message),
);
- let response = run.await.map_err(|e| e.to_string())?;
+ let outcome = run.await;
+ // Before the `?`. A turn that failed still spent what it spent, and the
+ // session that counted it is about to go out of scope with the error.
+ if let AgentChatTarget::Definition {
+ usage: Some(sink), ..
+ } = target
+ {
+ *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 29bc433ad3..c05dc2ac0b 100644
--- a/crates/openhuman-embed/src/agent/spec.rs
+++ b/crates/openhuman-embed/src/agent/spec.rs
@@ -227,16 +227,30 @@ impl AgentSpec {
/// thread will be described by the prompt that thread opened with. Vary a
/// belt only on turns that run on a session of their own.
///
+ /// # What the factory is told
+ ///
+ /// `f` receives a [`TurnContext`](openhuman_core::agent::TurnContext): the
+ /// agent, and the conversation the turn runs in when the caller named one
+ /// with [`Turn::session`](crate::Turn::session). A belt that varies has to
+ /// vary on something, and without this the factory would have to infer its
+ /// own occasion from state it closed over -- which holds only while the
+ /// agent serves one conversation at a time. The moment it serves two, a
+ /// belt bound to "the current episode" is a race rather than a decision.
+ ///
/// ```no_run
/// use openhuman_embed::{AgentSpec, HostTurnTools, Tool};
///
- /// # fn belt() -> Vec<Box<dyn Tool>> { Vec::new() }
- /// let spec = AgentSpec::new("reviewer").tools(|| HostTurnTools::advertised(belt()));
+ /// # fn belt_for(_chat: Option<&str>) -> Vec<Box<dyn Tool>> { Vec::new() }
+ /// let spec = AgentSpec::new("reviewer")
+ /// .tools(|turn| HostTurnTools::advertised(belt_for(turn.session_id())));
/// ```
#[must_use]
pub fn tools(
mut self,
- f: impl Fn() -> openhuman_core::agent::HostTurnTools + Send + Sync + 'static,
+ f: impl for<'a> Fn(openhuman_core::agent::TurnContext<'a>) -> openhuman_core::agent::HostTurnTools
+ + Send
+ + Sync
+ + 'static,
) -> Self {
self.host_tools = Some(std::sync::Arc::new(f));
self
diff --git a/crates/openhuman-embed/src/harness/builder.rs b/crates/openhuman-embed/src/harness/builder.rs
index ba4b019721..05398630a2 100644
--- a/crates/openhuman-embed/src/harness/builder.rs
+++ b/crates/openhuman-embed/src/harness/builder.rs
@@ -129,7 +129,10 @@ impl HarnessBuilder {
#[must_use]
pub fn tools(
mut self,
- f: impl Fn() -> openhuman_core::agent::HostTurnTools + Send + Sync + 'static,
+ f: impl for<'a> Fn(openhuman_core::agent::TurnContext<'a>) -> openhuman_core::agent::HostTurnTools
+ + Send
+ + Sync
+ + 'static,
) -> Self {
self.host_tools = Some(std::sync::Arc::new(f));
self
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 769ad0e25e..59ca4025fd 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -70,7 +70,8 @@ pub use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};
// The seam `AgentSpec::tools` needs: the belt types, and `Tool` itself from the
// vendored tinytools. An embedder that took `tinytools` as its own dependency
// would build tools of a different, incompatible type.
-pub use openhuman_core::agent::{HostTools, HostTurnTools};
+pub use openhuman_core::agent::tinyagents::host::LastTurnUsage;
+pub use openhuman_core::agent::{HostTools, HostTurnTools, TurnContext};
pub use openhuman_core::tools::Tool;
pub use openhuman_core::{
CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet, TokenSource,
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 776da572c9..63f8169a7f 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -196,7 +196,10 @@ impl TurnRequest {
}
/// What one turn produced.
-#[derive(Debug, Clone, PartialEq, Eq)]
+///
+/// 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,
@@ -204,6 +207,18 @@ pub struct TurnOutcome {
/// 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.
+ ///
+ /// 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.
+ ///
+ /// `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>,
}
/// Where a [`Turn`] is dispatched.
@@ -402,7 +417,11 @@ impl Turn {
}
}
- let dispatch = dispatch(self.target, self.request, self.seed.take());
+ // 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 dispatch = dispatch(self.target, self.request, self.seed.take(), &usage);
let reply = match (self.origin, self.progress) {
(Some(origin), Some(sink)) => {
@@ -444,7 +463,13 @@ impl Turn {
reply.len()
);
- Ok(TurnOutcome { reply, session_id })
+ Ok(TurnOutcome {
+ reply,
+ session_id,
+ usage: usage
+ .into_inner()
+ .unwrap_or_else(std::sync::PoisonError::into_inner),
+ })
}
}
@@ -456,10 +481,13 @@ 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>>;
+
async fn dispatch(
target: TurnTarget,
request: TurnRequest,
seed: Option<Vec<(String, String)>>,
+ usage: &UsageSink,
) -> Result<String, CoreError> {
match target {
TurnTarget::Runtime(rt) => {
@@ -498,6 +526,7 @@ async fn dispatch(
definition: &inner.definition,
host: inner.host_tools.as_ref(),
seed: seed.as_deref(),
+ usage: Some(usage),
};
agent_chat_for(
&mut config,
diff --git a/crates/openhuman-embed/src/turn_tests.rs b/crates/openhuman-embed/src/turn_tests.rs
index 623aae8bd4..cb8a08ece6 100644
--- a/crates/openhuman-embed/src/turn_tests.rs
+++ b/crates/openhuman-embed/src/turn_tests.rs
@@ -211,3 +211,37 @@ fn the_controller_declares_nowhere_for_a_seed_to_travel() {
schema.inputs.iter().map(|f| f.name).collect::<Vec<_>>()
);
}
+
+/// A turn outcome reports what it spent, and is not `Eq`.
+///
+/// The type-level half of the metering contract. `LastTurnUsage` carries a
+/// cost in dollars, so [`TurnOutcome`] cannot derive `Eq` -- this asserts the
+/// field is reachable and comparable the way a host meters it, and fails to
+/// compile if `usage` is dropped or retyped.
+#[test]
+fn a_turn_outcome_carries_what_the_turn_spent() {
+ let spent = openhuman_core::agent::tinyagents::host::LastTurnUsage {
+ input_tokens: 1_200,
+ output_tokens: 340,
+ cost_usd: 0.0042,
+ ..Default::default()
+ };
+ let outcome = TurnOutcome {
+ reply: "done".into(),
+ session_id: "s".into(),
+ usage: Some(spent.clone()),
+ };
+
+ let metered = outcome.usage.as_ref().expect("a metered turn");
+ assert_eq!(metered.input_tokens, 1_200);
+ assert_eq!(metered.output_tokens, 340);
+ assert!((metered.cost_usd - 0.0042).abs() < f64::EPSILON);
+
+ // Unmetered is representable and distinct, which is what the RPC path and
+ // a session that reported nothing both produce.
+ let unmetered = TurnOutcome {
+ usage: None,
+ ..outcome.clone()
+ };
+ assert_ne!(unmetered, outcome);
+}