Skip to content

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

chore(tinyagents): drop unused host adapters

Steven Enamakel52749f82a6be
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 f0cd46dbd2..d536773b1e 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -823,7 +823,6 @@ impl OpenHumanSessionHost {
config: Arc::clone(&base_config),
definitions,
security_policy: security,
- post_turn_hooks: agent.post_turn_hooks.clone(),
session_definition: session_definition.clone().map(|definition| {
Arc::new(super::host_tools::add_permanent_tools(
definition,
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs b/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs
index 1193724aa5..cf125727aa 100644
--- a/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/budget_stop_turn_tests.rs
@@ -103,7 +103,6 @@ fn hosted_base() -> Arc<crate::agent::tinyagents::host::OpenHumanHostBase> {
crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only(),
),
security_policy: Arc::new(crate::security::policy::SecurityPolicy::default()),
- post_turn_hooks: Vec::new(),
session_definition: None,
})
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs b/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
deleted file mode 100644
index 07e381ad97..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/embeddings.rs
+++ /dev/null
@@ -1,79 +0,0 @@
-//! Cost-recording binding over the host's embedding model (issue #4249).
-//!
-//! The model contract, the signature format and the batch shape all live in
-//! `tinyinference-embeddings`; this file only adds OpenHuman's per-call
-//! embedding cost recording.
-
-use std::sync::Arc;
-
-use crate::core::runtime::DispatchCtx;
-use async_trait::async_trait;
-use tinyinference_embeddings::{EmbeddingModel, Result as EmbedResult};
-
-/// Wraps the host-bound [`EmbeddingModel`] (credentials, rate limit and
-/// fallback already applied by the factory) and records embedding cost per
-/// call. Everything else delegates to the model.
-pub(crate) struct ProviderEmbeddingModel {
- model: Arc<dyn EmbeddingModel>,
- dispatch: DispatchCtx,
-}
-
-impl ProviderEmbeddingModel {
- /// Builds the cost-recording binding over `model`.
- pub(crate) fn new(model: Arc<dyn EmbeddingModel>, dispatch: DispatchCtx) -> Self {
- tracing::debug!(
- provider = model.name(),
- model_id = model.model_id(),
- dimensions = model.dimensions(),
- signature = %model.signature(),
- "[embeddings] constructing cost-recording embedding binding"
- );
- Self { model, dispatch }
- }
-}
-
-#[async_trait]
-impl EmbeddingModel for ProviderEmbeddingModel {
- fn is_enabled(&self) -> bool {
- self.model.is_enabled()
- }
-
- fn name(&self) -> &str {
- self.model.name()
- }
-
- fn model_id(&self) -> &str {
- self.model.model_id()
- }
-
- fn dimensions(&self) -> usize {
- self.model.dimensions()
- }
-
- fn signature(&self) -> String {
- self.model.signature()
- }
-
- async fn embed(&self, texts: &[String]) -> EmbedResult<Vec<Vec<f32>>> {
- let result = self.model.embed(texts).await?;
- // Best-effort cost recording; never fails the embed. Skipped for an
- // empty batch so the request count is not inflated.
- if !result.is_empty() {
- let approx_input_tokens =
- tinyinference_embeddings::estimate_embedding_input_tokens(texts);
- crate::platform::cost::record_embedding_usage(
- &self.dispatch,
- self.model.name(),
- self.model.model_id(),
- approx_input_tokens,
- self.model.dimensions(),
- result.len() as u64,
- );
- }
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "embeddings_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/embeddings_tests.rs b/crates/openhuman-core/src/agent/tinyagents/embeddings_tests.rs
deleted file mode 100644
index a837ee129e..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/embeddings_tests.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-use super::*;
-
-/// Deterministic stub provider: emits one fixed-length vector per input,
-/// each component seeded from the input length so distinct texts map to
-/// distinct vectors and the round-trip / dimension assertions are stable.
-struct StubProvider {
- dims: usize,
-}
-
-#[async_trait]
-impl EmbeddingModel for StubProvider {
- fn name(&self) -> &str {
- "stub"
- }
-
- fn model_id(&self) -> &str {
- "stub-model"
- }
-
- fn dimensions(&self) -> usize {
- self.dims
- }
-
- async fn embed(&self, texts: &[String]) -> EmbedResult<Vec<Vec<f32>>> {
- Ok(texts
- .iter()
- .map(|t| vec![t.len() as f32; self.dims])
- .collect())
- }
-}
-
-#[tokio::test]
-async fn embeddings_adapter_round_trips_and_reports_dimensions() {
- let provider: Arc<dyn EmbeddingModel> = Arc::new(StubProvider { dims: 4 });
- let adapter = ProviderEmbeddingModel::new(provider, DispatchCtx::ambient());
-
- // dimensions() is forwarded from the underlying provider.
- assert_eq!(EmbeddingModel::name(&adapter), "stub");
- assert_eq!(EmbeddingModel::model_id(&adapter), "stub-model");
- assert_eq!(EmbeddingModel::dimensions(&adapter), 4);
-
- // embed() returns one vector per
- // input, in order, each of the reported dimensionality.
- let inputs = vec!["ab".to_string(), "abcd".to_string()];
- let vectors = adapter.embed(&inputs).await.expect("embed should succeed");
- assert_eq!(vectors.len(), 2);
- assert!(vectors.iter().all(|v| v.len() == 4));
- // Distinct inputs -> distinct vectors (seeded from text length).
- assert_eq!(vectors[0], vec![2.0; 4]);
- assert_eq!(vectors[1], vec![4.0; 4]);
-}
-
-#[tokio::test]
-async fn embeddings_adapter_preserves_signature() {
- let provider: Arc<dyn EmbeddingModel> = Arc::new(StubProvider { dims: 8 });
- let expected = provider.signature();
- let adapter = ProviderEmbeddingModel::new(provider, DispatchCtx::ambient());
- assert_eq!(adapter.signature(), expected);
- assert_eq!(adapter.signature(), "provider=stub;model=stub-model;dims=8");
-}
-
-#[tokio::test]
-async fn embeddings_adapter_empty_batch_is_empty() {
- let provider: Arc<dyn EmbeddingModel> = Arc::new(StubProvider { dims: 3 });
- let adapter = ProviderEmbeddingModel::new(provider, DispatchCtx::ambient());
- let vectors = adapter.embed(&[]).await.expect("empty embed ok");
- assert!(vectors.is_empty());
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
index 5d6450070a..68b333b9c5 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle.rs
@@ -8,21 +8,19 @@
use std::sync::Arc;
use tinyagents_harness::host::{
- BudgetGate, ContextComposer, HostCapabilities, LearningSink, ModelResolver, ProgressSink,
- SecurityGate, ToolOutcomeClassifier,
+ BudgetGate, ContextComposer, HostCapabilities, ModelResolver, NoopProgressSink, ProgressSink,
+ SecurityGate, StaticContextComposer, ToolOutcomeClassifier,
};
use crate::agent::harness::host_definition::AgentDefinitionRegistry;
-use crate::agent::hooks::PostTurnHook;
use crate::config::Config;
use crate::security::policy::SecurityPolicy;
use tinytools::Tool;
use tinytools::ToolPolicySession;
use super::{
- OpenHumanBudgetGate, OpenHumanContextComposer, OpenHumanDefinitionRegistry,
- OpenHumanLearningSink, OpenHumanModelResolver, OpenHumanProgressSink, OpenHumanRunContext,
- OpenHumanSecurityGate, OpenHumanToolOutcomeClassifier,
+ OpenHumanBudgetGate, OpenHumanDefinitionRegistry, OpenHumanRunContext, OpenHumanSecurityGate,
+ OpenHumanToolOutcomeClassifier,
};
/// Runtime-owned inputs required to build every OpenHuman host capability.
@@ -36,7 +34,8 @@ pub struct OpenHumanHostBundleInputs {
pub security_policy: Arc<SecurityPolicy>,
pub tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
pub tool_policy: Option<Arc<ToolPolicySession>>,
- pub post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
+ /// The current turn's already-selected model route set.
+ pub model_resolver: Arc<dyn ModelResolver<()>>,
/// See [`OpenHumanHostBase::session_definition`].
pub session_definition: Option<Arc<crate::agent::harness::host_definition::AgentDefinition>>,
}
@@ -51,7 +50,6 @@ pub struct OpenHumanHostBase {
pub config: Arc<Config>,
pub definitions: Arc<AgentDefinitionRegistry>,
pub security_policy: Arc<SecurityPolicy>,
- pub post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
/// The session's own caller-supplied definition, when it was built from one
/// rather than from a registry id — see
/// [`OpenHumanDefinitionRegistry::with_session_definition`]. Lives here, beside
@@ -67,7 +65,7 @@ pub struct OpenHumanHostInvocationInputs {
pub tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
pub tool_policy: Option<Arc<ToolPolicySession>>,
/// The current turn's already-selected model route set.
- pub model_resolver: Option<Arc<dyn ModelResolver<()>>>,
+ pub model_resolver: Arc<dyn ModelResolver<()>>,
}
/// OpenHuman's concrete capability adapters plus their erased crate bundle.
@@ -79,13 +77,12 @@ pub struct OpenHumanHostInvocationInputs {
/// solely to preserve the host boundary and to support focused wiring tests.
pub struct OpenHumanHostBundle {
pub capabilities: HostCapabilities<()>,
- pub context: Arc<OpenHumanContextComposer>,
+ pub context: Arc<StaticContextComposer>,
pub definitions: Arc<OpenHumanDefinitionRegistry>,
pub security: Arc<OpenHumanSecurityGate>,
- pub models: Arc<OpenHumanModelResolver>,
+ pub models: Arc<dyn ModelResolver<()>>,
pub budget: Arc<OpenHumanBudgetGate>,
- pub progress: Arc<OpenHumanProgressSink>,
- pub learning: Arc<OpenHumanLearningSink>,
+ pub progress: Arc<NoopProgressSink>,
pub tool_outcomes: Arc<OpenHumanToolOutcomeClassifier>,
}
@@ -99,38 +96,31 @@ impl OpenHumanHostBundleFactory {
inputs: OpenHumanHostInvocationInputs,
turn: &OpenHumanRunContext,
) -> OpenHumanHostBundle {
- let mut bundle = Self::build(
+ Self::build(
OpenHumanHostBundleInputs {
config: inputs.base.config.clone(),
definitions: inputs.base.definitions.clone(),
security_policy: inputs.base.security_policy.clone(),
tool_sets: inputs.tool_sets,
tool_policy: inputs.tool_policy,
- post_turn_hooks: inputs.base.post_turn_hooks.clone(),
+ model_resolver: inputs.model_resolver,
session_definition: inputs.base.session_definition.clone(),
},
turn,
- );
- if let Some(model_resolver) = inputs.model_resolver {
- bundle.capabilities.models = model_resolver;
- }
- bundle
+ )
}
/// Constructs every concrete adapter from a single session input set.
///
/// The run context supplies per-turn state, while `inputs` supplies durable
- /// session/runtime dependencies. No adapter is optional for OpenHuman. The
- /// progress seam is registered but unconsumed: the turn's live channel is
- /// owned by `OpenhumanEventBridge` (see below).
+ /// session/runtime dependencies. The session has already composed its
+ /// prompt and selected its models; session finalization owns learning hooks.
+ /// Live progress is owned by `OpenhumanEventBridge`.
pub fn build(
inputs: OpenHumanHostBundleInputs,
turn: &OpenHumanRunContext,
) -> OpenHumanHostBundle {
- let context = Arc::new(
- OpenHumanContextComposer::new(Arc::clone(&inputs.config))
- .with_dispatch(turn.dispatch_ctx()),
- );
+ let context = Arc::new(StaticContextComposer::empty());
let registered_tools = Arc::new(
inputs
.tool_sets
@@ -176,28 +166,13 @@ impl OpenHumanHostBundleFactory {
security = security.with_tool_policy(policy);
}
let security = Arc::new(security);
- let models = Arc::new(
- OpenHumanModelResolver::new(Arc::clone(&inputs.config))
- .with_dispatch(turn.dispatch_ctx()),
- );
+ let models = inputs.model_resolver;
let budget = Arc::new(
OpenHumanBudgetGate::new(Arc::clone(&inputs.config)).with_dispatch(turn.dispatch_ctx()),
);
- // The turn's live `AgentProgress` channel is fed by exactly one
- // producer: `OpenhumanEventBridge`, which `turn_exec` subscribes to
- // the run's `EventSink` on every turn and which carries what the UI
- // needs (iteration attribution, thinking, tool-argument fragments,
- // sub-agent scoping, cost). The harness also mirrors the loop onto the
- // coarse host `ProgressSink` (`emit_host_progress`: `Token` per model
- // delta, `ToolCall`/`ToolCallFinished`, `Finished`), so wiring this
- // sink to the same channel delivered every delta and every tool row
- // twice and interleaved the copies in the interim bubble. The sink
- // stays registered as the host capability with an unconsumed channel;
- // nothing OpenHuman renders depends on it.
- let progress = Arc::new(OpenHumanProgressSink::new(tokio::sync::mpsc::channel(1).0));
- let learning = Arc::new(
- OpenHumanLearningSink::new(inputs.post_turn_hooks).with_dispatch(turn.dispatch_ctx()),
- );
+ // Product progress is emitted by OpenhumanEventBridge. The coarse
+ // host sink contributes no second stream of token/tool events.
+ let progress = Arc::new(NoopProgressSink);
let tool_outcomes = Arc::new(OpenHumanToolOutcomeClassifier::new());
let capabilities = HostCapabilities::new(
@@ -208,7 +183,6 @@ impl OpenHumanHostBundleFactory {
)
.with_budget(budget.clone() as Arc<dyn BudgetGate>)
.with_progress(progress.clone() as Arc<dyn ProgressSink>)
- .with_learning(learning.clone() as Arc<dyn LearningSink>)
.with_tool_outcomes(tool_outcomes.clone() as Arc<dyn ToolOutcomeClassifier>);
OpenHumanHostBundle {
@@ -219,7 +193,6 @@ impl OpenHumanHostBundleFactory {
models,
budget,
progress,
- learning,
tool_outcomes,
}
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs
index e6af7206a0..544b1096dd 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/bundle_tests.rs
@@ -4,7 +4,7 @@ use std::sync::Arc;
use tinyagents_definition::DefinitionRegistry;
use tinyagents_harness::host::{
- BudgetGate, ContextComposer, LearningSink, ModelResolver, ProgressSink, SecurityGate,
+ BudgetGate, ContextComposer, FixedModelResolver, ModelResolver, ProgressSink, SecurityGate,
ToolOutcomeClassifier,
};
@@ -20,7 +20,9 @@ fn inputs() -> (OpenHumanHostBundleInputs, OpenHumanRunContext) {
security_policy: Arc::new(SecurityPolicy::default()),
tool_sets: Vec::new(),
tool_policy: None,
- post_turn_hooks: Vec::new(),
+ model_resolver: Arc::new(FixedModelResolver::new(Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::new(Vec::new()),
+ ))),
session_definition: None,
},
turn,
@@ -38,7 +40,6 @@ fn factory_records_every_concrete_adapter_in_one_bundle() {
let models: Arc<dyn ModelResolver<()>> = host.models.clone();
let budget: Arc<dyn BudgetGate> = host.budget.clone();
let progress: Arc<dyn ProgressSink> = host.progress.clone();
- let learning: Arc<dyn LearningSink> = host.learning.clone();
let outcomes: Arc<dyn ToolOutcomeClassifier> = host.tool_outcomes.clone();
assert!(Arc::ptr_eq(&context, &host.capabilities.context));
@@ -55,10 +56,7 @@ fn factory_records_every_concrete_adapter_in_one_bundle() {
&progress,
host.capabilities.progress.as_ref().expect("progress")
));
- assert!(Arc::ptr_eq(
- &learning,
- host.capabilities.learning.as_ref().expect("learning")
- ));
+ assert!(host.capabilities.learning.is_none());
assert!(Arc::ptr_eq(
&outcomes,
host.capabilities
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs b/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
deleted file mode 100644
index 98c3143b82..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/context_composer.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-//! Host adapter: [`tinyagents_harness::host::ContextComposer`] backed by
-//! OpenHuman's prompt pipeline.
-//!
-//! # Which OpenHuman domains this adapts
-//!
-//! * [`crate::agent::prompts`] (re-exported as
-//! `crate::agent::prompts`) — `SystemPromptBuilder`,
-//! `PromptContext`, `ConnectedIntegration`,
-//! `ToolCallFormat`, `load_agents_md_layers`, `render_connected_identities`.
-//! The `SOUL.md` / `IDENTITY.md` / `ROLE.md` bootstrap files under
-//! `crates/openhuman-core/src/agent/prompts/` are loaded (and synced to the workspace)
-//! by `IdentitySection` inside `SystemPromptBuilder::build`, so this adapter
-//! never reads them itself.
-//! * [`crate::config::Config`] — supplies `workspace_dir`,
-//! `action_dir`, the default model, and the `agents_md_enabled` gate.
-//! * [`crate::security::credentials::identity::peek_credential_user_identity`] — the
-//! non-secret `id`/`name`/`email` triple. Deliberately read through the
-//! *identity peek*, which is the accessor that strips credential material;
-//! this adapter must not reach for a richer user record to fill the prompt.
-//!
-//! Prompt assembly is **not** reimplemented here. Everything this file does is
-//! translate a [`TurnContextRequest`] into a `PromptContext` and hand it to the
-//! existing `SystemPromptBuilder::with_defaults()` chain — the same chain
-//! `agent::session_host::turn::context::build_system_prompt` uses. That
-//! keeps one source of truth for section ordering, the grounding contract, and
-//! the global style suffix.
-//!
-//! # Contract mismatches resolved here
-//!
-//! 1. **Per-turn call vs. frozen prefix.** The crate consults a composer on
-//! *every* turn (`context_composer.rs`: "a host whose learned context …
-//! changes mid-session needs the later turns to see it"). OpenHuman's
-//! pipeline goes the other way: `SystemPromptBuilder::build`'s rustdoc
-//! states the rendered bytes are "intended to be **frozen for the whole
-//! session**" so the inference backend's prefix cache hits. Both are
-//! honoured by construction — every input this adapter feeds the builder is
-//! a snapshot captured at *construction* time (config, connected
-//! integrations), so recomposing per turn yields byte-identical
-//! output unless the host deliberately builds a new composer. The two
-//! genuinely time-varying sections in the default chain
-//! (`DateTimeSection`, and the on-disk files `IdentitySection` reads) are
-//! OpenHuman's pre-existing behaviour on the main-agent path, not something
-//! this seam introduces.
-//! 2. **`thread_id` and `user_text` are unused inputs.** `PromptContext` has no
-//! thread field and no turn-text field; this adapter only logs the thread
-//! id for correlation.
-//! 3. **`preamble` returns an empty `Vec`, always.** OpenHuman has no separate
-//! preamble concept here: everything the system prompt needs is rendered
-//! *into* it as `PromptSection`s. Per the trait's
-//! "Empty is not failure" note this is the normal, correct answer, not a
-//! gap — synthesising extra messages here would duplicate content the
-//! system prompt already carries.
-//!
-//! # Policy
-//!
-//! The `agents_md_enabled` config gate is honoured: when it is off, both
-//! AGENTS.md layers are handed to the builder as `None` rather than being
-//! loaded. `load_agents_md_layers` performs the `O_NOFOLLOW` path hardening
-//! that keeps a symlinked project-layer `AGENTS.md` from leaking arbitrary
-//! host files into the prompt (and thence to the inference provider); this
-//! adapter goes through it rather than reading the files itself.
-
-use std::collections::HashSet;
-use std::sync::Arc;
-use tinytools_agent::dialect::ToolCallFormat;
-
-use async_trait::async_trait;
-use tinyagents_harness::error::{Result as TinyAgentsResult, TinyAgentsError};
-use tinyagents_harness::host::{ContextComposer, TurnContextRequest};
-use tinyinference_llm::message::Message;
-
-use crate::agent::prompts::{
- load_agents_md_layers, render_connected_identities, AgentsMdContent, ConnectedIntegration,
- PromptContext, PromptTool, SystemPromptBuilder,
-};
-use crate::config::{Config, DEFAULT_MODEL};
-use crate::core::runtime::DispatchCtx;
-use tinyskills::Skill as Workflow;
-
-/// Composes OpenHuman's system prompt for a TinyAgents turn.
-///
-/// Holds a snapshot of everything the prompt pipeline needs that is *not*
-/// carried on [`TurnContextRequest`]. Snapshot rather than live handles is
-/// deliberate: it is what makes repeated `compose_system_prompt` calls
-/// byte-stable, which is the KV-cache contract described in the module doc.
-///
-/// The struct is cheap to clone-construct and holds no locks, so a caller that
-/// genuinely needs mid-session refresh (new integration connected) rebuilds the composer rather than
-/// mutating it.
-pub struct OpenHumanContextComposer {
- /// Host config — source of the two path roots, the fallback model name,
- /// and the `agents_md_enabled` gate.
- config: Arc<Config>,
- /// Model name rendered into the prompt's runtime section. Defaults to
- /// `config.default_model` (then [`DEFAULT_MODEL`]) because the crate's
- /// `TurnContextRequest` carries no model — model resolution is a separate
- /// host capability (`ModelResolver`) and this seam must not second-guess
- /// it.
- model_name: String,
- /// How the tool catalogue renders. Left at the OpenHuman default
- /// ([`ToolCallFormat::Json`]) unless the caller pins it, since the
- /// authoritative value lives on the agent's tool dispatcher, which is not
- /// reachable from a `TurnContextRequest`.
- tool_call_format: ToolCallFormat,
- /// Connected Composio integrations, pre-fetched. Empty is a valid state
- /// (nothing connected, or the caller has not fetched yet) and renders as
- /// an absent section rather than an error.
- connected_integrations: Vec<ConnectedIntegration>,
- /// The turn's dispatch context for config reads; `None` falls back to the
- /// calling task's.
- dispatch: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
- /// The section chain. Built once so per-turn composition is just a render.
- builder: SystemPromptBuilder,
-}
-
-impl OpenHumanContextComposer {
- /// A composer over `config` with no integrations.
- ///
- /// This is the honest zero state, not a degraded one: a fresh install with
- /// nothing connected composes exactly this prompt.
- pub fn new(config: Arc<Config>) -> Self {
- let model_name = config
- .default_model
- .clone()
- .unwrap_or_else(|| DEFAULT_MODEL.to_string());
- Self {
- config,
- model_name,
- tool_call_format: ToolCallFormat::Json,
- connected_integrations: Vec::new(),
- dispatch: None,
- builder: SystemPromptBuilder::with_defaults(),
- }
- }
-
- /// Binds the turn's dispatch context, which the composer reads config under.
- pub fn with_dispatch(mut self, dispatch: DispatchCtx) -> Self {
- self.dispatch = dispatch.downgrade();
- self
- }
-
- /// Pins the model name rendered into the runtime section.
- pub fn with_model_name(mut self, model_name: impl Into<String>) -> Self {
- self.model_name = model_name.into();
- self
- }
-
- /// Loads the two AGENTS.md layers, honouring the `agents_md_enabled` gate.
- ///
- /// Split out so the gate has exactly one enforcement point and the tests
- /// can pin the disabled branch without rendering a whole prompt.
- fn agents_md(&self) -> AgentsMdContent {
- if self.config.agent.agents_md_enabled {
- load_agents_md_layers(&self.config.workspace_dir, &self.config.action_dir)
- } else {
- tracing::debug!(
- target: "tinyagents",
- "[tinyagents][context_composer] agents_md_enabled is off; skipping AGENTS.md injection"
- );
- AgentsMdContent::default()
- }
- }
-}
-
-#[async_trait]
-impl ContextComposer for OpenHumanContextComposer {
- /// Renders the full OpenHuman system prompt for this turn.
- ///
- /// Returns `Err(TinyAgentsError::Validation)` only when a
- /// [`crate::agent::prompts::PromptSection`] itself fails — a
- /// genuine fault, per the trait's "reserve it for genuine faults" rule.
- /// An empty section is skipped by the builder, never surfaced as an error.
- async fn compose_system_prompt(&self, req: &TurnContextRequest) -> TinyAgentsResult<String> {
- tracing::debug!(
- target: "tinyagents",
- agent_id = %req.agent_id,
- thread_id = %req.thread_id.as_str(),
- has_user_text = req.has_user_text(),
- "[tinyagents][context_composer] composing system prompt"
- );
-
- // Every borrowed field of `PromptContext` needs an owner that outlives
- // the context, so the empties are bound here rather than inline.
- //
- // `tools` and `visible_tool_names` are empty on purpose: the crate's
- // `TurnContextRequest` carries no tool set, and the tool catalogue is
- // owned by the runtime's own tool registry rather than by this seam.
- // An empty `visible_tool_names` is also the *non-orchestrator* signal
- // that `IdentitySection` keys off, which is the correct default for a
- // composer that does not know it is driving a delegator.
- //
- // TODO(phase4): once the runtime exposes its resolved tool set to the
- // host (a `ToolCatalog`-shaped capability would be the natural seam),
- // feed it through `PromptTool::from_tools` / `PromptTool::with_schema`
- // so `ToolsSection` renders a real catalogue instead of nothing.
- let prompt_tools: Vec<PromptTool<'_>> = Vec::new();
- let visible_tool_names: HashSet<String> = HashSet::new();
- // TODO(phase4): installed workflows live in
- // `crate::skill_registry` / `skills`, behind the `skills`
- // compile-time gate. Wiring them needs a gated fetch plus a decision
- // about the disabled build, so they are left empty here rather than
- // guessed at.
- let workflows: Vec<Workflow> = Vec::new();
- let agents_md = self.agents_md();
-
- let ctx = PromptContext {
- workspace_dir: &self.config.workspace_dir,
- model_name: &self.model_name,
- agent_id: &req.agent_id,
- tools: &prompt_tools,
- workflows: &workflows,
- // The dispatcher's tool-protocol preamble belongs to the runtime's
- // dispatcher, which this seam cannot see. Empty renders nothing.
- dispatcher_instructions: "",
- visible_tool_names: &visible_tool_names,
- tool_call_format: self.tool_call_format,
- connected_integrations: &self.connected_integrations,
- connected_identities_md: render_connected_identities(&DispatchCtx::from_weak(
- self.dispatch.as_ref(),
- )),
- user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
- // TODO(phase4): the master agent's personality roster is built
- // from the profiles domain (`crate::profiles`); the
- // existing main-agent path leaves this empty too (see the
- // `personality_roster: vec![]` TODO in
- // `agent/session_host/turn/context.rs`), so this matches
- // current behaviour rather than regressing it.
- personality_roster: Vec::new(),
- agents_md_global: agents_md.global,
- agents_md_local: agents_md.local,
- };
-
- self.builder.build(&ctx).map_err(|e| {
- TinyAgentsError::Validation(format!("system prompt composition failed: {e:#}"))
- })
- }
-
- /// Always empty — see mismatch (3) in the module doc.
- ///
- /// OpenHuman renders everything as prompt *sections*, so there is nothing left over to prepend as messages.
- /// Returning `Ok(vec![])` is the trait's documented normal case.
- async fn preamble(&self, _req: &TurnContextRequest) -> TinyAgentsResult<Vec<Message>> {
- Ok(Vec::new())
- }
-}
-
-#[cfg(test)]
-#[path = "context_composer_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs
deleted file mode 100644
index d46bc04321..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/context_composer_tests.rs
+++ /dev/null
@@ -1,122 +0,0 @@
-use super::*;
-
-/// A config rooted in a throwaway directory.
-///
-/// Non-negotiable for these tests: `IdentitySection` calls
-/// `sync_workspace_file`, which **writes** `SOUL.md` / `IDENTITY.md` /
-/// `ROLE.md` into `workspace_dir`. Composing against
-/// `Config::default()` would scribble into the developer's real
-/// `~/.openhuman` workspace.
-fn config_in(dir: &std::path::Path) -> Arc<Config> {
- let mut config = Config::default();
- config.workspace_dir = dir.to_path_buf();
- config.action_dir = dir.join("projects");
- std::fs::create_dir_all(&config.action_dir).expect("create action dir");
- Arc::new(config)
-}
-
-fn request() -> TurnContextRequest {
- TurnContextRequest::new("orchestrator", "thread-1", "what changed today?")
-}
-
-#[tokio::test]
-async fn composes_a_non_empty_prompt_carrying_the_agent_id() {
- let dir = tempfile::tempdir().expect("tempdir");
- let composer = OpenHumanContextComposer::new(config_in(dir.path()));
- let prompt = composer
- .compose_system_prompt(&request())
- .await
- .expect("prompt composes");
-
- assert!(!prompt.trim().is_empty(), "prompt must not be blank");
- // The default chain always appends the grounding contract and the
- // global style suffix; asserting on the suffix pins that we went
- // through `SystemPromptBuilder::build` rather than hand-assembling.
- assert!(
- prompt.contains("# Writing style"),
- "prompt must come from SystemPromptBuilder::build"
- );
-}
-
-#[tokio::test]
-async fn preamble_is_empty_and_not_an_error() {
- let dir = tempfile::tempdir().expect("tempdir");
- let composer = OpenHumanContextComposer::new(config_in(dir.path()));
- assert!(composer
- .preamble(&request())
- .await
- .expect("preamble succeeds")
- .is_empty());
-}
-
-#[tokio::test]
-async fn the_prompt_is_byte_stable_across_repeated_turns() {
- // The KV-cache contract from mismatch (1): the crate calls this every
- // turn, and OpenHuman needs the bytes frozen. `DateTimeSection` has
- // minute granularity, so two back-to-back calls agreeing is the
- // strongest cheap check that nothing *else* varies per call.
- let dir = tempfile::tempdir().expect("tempdir");
- let composer = OpenHumanContextComposer::new(config_in(dir.path()));
- let a = composer
- .compose_system_prompt(&request())
- .await
- .expect("first");
- let b = composer
- .compose_system_prompt(&request())
- .await
- .expect("second");
- assert_eq!(a, b);
-}
-
-#[tokio::test]
-async fn a_different_agent_id_still_composes() {
- // The crate treats `agent_id` as opaque, so an id the host has never
- // heard of must not fail composition — it is a prompt input, not a
- // registry lookup.
- let dir = tempfile::tempdir().expect("tempdir");
- let composer = OpenHumanContextComposer::new(config_in(dir.path()));
- let req = TurnContextRequest::new("no-such-agent", "thread-9", "");
- assert!(composer.compose_system_prompt(&req).await.is_ok());
-}
-
-#[test]
-fn agents_md_layers_are_loaded_when_the_gate_is_on() {
- let dir = tempfile::tempdir().expect("tempdir");
- let config = config_in(dir.path());
- std::fs::write(dir.path().join("AGENTS.md"), "global rule").expect("write global");
-
- let composer = OpenHumanContextComposer::new(config);
- let loaded = composer.agents_md();
- assert_eq!(loaded.global.as_deref(), Some("global rule"));
-}
-
-#[test]
-fn the_agents_md_gate_is_honoured_when_off() {
- let dir = tempfile::tempdir().expect("tempdir");
- let mut config = Config::default();
- config.workspace_dir = dir.path().to_path_buf();
- config.action_dir = dir.path().join("projects");
- config.agent.agents_md_enabled = false;
- std::fs::create_dir_all(&config.action_dir).expect("create action dir");
- std::fs::write(dir.path().join("AGENTS.md"), "global rule").expect("write global");
-
- let composer = OpenHumanContextComposer::new(Arc::new(config));
- let loaded = composer.agents_md();
- assert!(
- loaded.is_empty(),
- "a disabled gate must not read AGENTS.md at all"
- );
-}
-
-#[test]
-fn the_model_name_falls_back_to_the_crate_default() {
- let dir = tempfile::tempdir().expect("tempdir");
- let mut config = Config::default();
- config.workspace_dir = dir.path().to_path_buf();
- config.default_model = None;
- let composer = OpenHumanContextComposer::new(Arc::new(config));
- assert_eq!(composer.model_name, DEFAULT_MODEL);
-
- let pinned = OpenHumanContextComposer::new(config_in(dir.path())).with_model_name("haiku");
- assert_eq!(pinned.model_name, "haiku");
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs b/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs
deleted file mode 100644
index fde436bf4d..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-//! Host adapter for [`tinyagents_harness::host::LearningSink`] — the seam the
-//! generic agent runtime uses to hand a finished turn to the host's post-turn
-//! hooks ([`crate::agent::hooks::PostTurnHook`], e.g. the ones an embedder
-//! registers through `hooks::register_embedder_post_turn_hook`).
-//!
-//! The adapter is thin: it translates a [`TurnSummary`] into a
-//! [`TurnContext`] and enqueues it through [`crate::agent::hooks::fire_hooks`],
-//! which spawns every hook and returns at once.
-//!
-//! `TurnSummary::tools_invoked` is names-only, while `TurnContext.tool_calls`
-//! carries outcomes (`success`, `duration_ms`). There is no honest projection
-//! from one to the other, so `tool_calls` is left empty rather than filled
-//! with invented outcomes; the names are logged only. `TurnSummary` carries a
-//! thread id but no session id, so the thread id is mapped through as the
-//! nearest correlation key. Errors are advisory: the turn is already
-//! committed, so [`OpenHumanLearningSink::on_turn_complete`] always returns
-//! `Ok(())`.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use tinyagents_harness::error::Result;
-use tinyagents_harness::host::{LearningSink, TurnSummary};
-
-use crate::agent::hooks::{self, PostTurnHook, TurnContext};
-
-/// Adapts OpenHuman's [`PostTurnHook`] fan-out to the crate's
-/// [`LearningSink`] capability.
-///
-/// Holds the hook list rather than building it, because *which* hooks are
-/// installed is a composition decision the session builder already makes (see
-/// `agent/session_host/builder/factory.rs`); duplicating that policy here
-/// would give the generic runtime a second, silently divergent hook set.
-pub struct OpenHumanLearningSink {
- /// Hooks fired, in parallel, for every completed turn.
- hooks: Vec<Arc<dyn PostTurnHook>>,
- /// The owning turn's dispatch context; unbound falls back to the task's.
- dispatch: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,
-}
-
-impl OpenHumanLearningSink {
- /// Wraps an already-composed hook list.
- ///
- /// An empty list is legal and turns the sink into a no-op. It is *not* the
- /// way to express "this host has no learning pipeline" — the crate doc asks
- /// hosts to pass `None` for the capability in that case, so absence stays
- /// distinguishable from a sink that ran and did nothing.
- pub fn new(hooks: Vec<Arc<dyn PostTurnHook>>) -> Self {
- Self {
- hooks,
- dispatch: None,
- }
- }
-
- /// Binds the owning turn's dispatch context.
- pub fn with_dispatch(mut self, dispatch: crate::core::runtime::DispatchCtx) -> Self {
- self.dispatch = dispatch.downgrade();
- self
- }
-
- /// Appends one more hook.
- pub fn with_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self {
- self.hooks.push(hook);
- self
- }
-
- /// Number of installed hooks. Exposed for assertions and for a caller
- /// deciding whether to supply the capability at all.
- pub fn hook_count(&self) -> usize {
- self.hooks.len()
- }
-
- /// Projects a crate [`TurnSummary`] onto OpenHuman's [`TurnContext`].
- ///
- /// See the module doc for why `tool_calls` comes out empty. Kept associated
- /// and pure so the projection is testable without a runtime.
- fn turn_context_from(summary: &TurnSummary) -> TurnContext {
- TurnContext {
- user_message: summary.input.clone(),
- assistant_response: summary.output.clone(),
- // Intentionally empty — a names-only summary cannot supply the
- // `success` / `duration_ms` / `output_summary` fields that give a
- // `ToolCallRecord` its meaning. See the module doc.
- tool_calls: Vec::new(),
- // Not carried by `TurnSummary`; reporting-only fields, read by no
- // gate in any installed hook.
- turn_duration_ms: 0,
- iteration_count: 1,
- // `TurnSummary` has no session id; the thread id is the nearest
- // correlation key. Blank ids are normalized to `None` so hooks that
- // key on the session (reflection throttling) fall back to their
- // global bucket rather than keying on "".
- session_id: Some(summary.thread_id.as_str().to_string())
- .filter(|id| !id.trim().is_empty()),
- agent_id: Some(summary.agent_id.clone()).filter(|id| !id.trim().is_empty()),
- // No channel/entrypoint concept exists on the crate side.
- entrypoint: None,
- }
- }
-}
-
-#[async_trait]
-impl LearningSink for OpenHumanLearningSink {
- /// Enqueues the turn onto OpenHuman's post-turn hook fan-out and returns.
- ///
- /// Always `Ok(())`. `fire_hooks` spawns each hook on the tokio runtime and
- /// logs its failure, so there is nothing fallible left to report — and the
- /// trait doc forbids using an `Err` as a veto in any case, since the turn is
- /// already committed by the time this runs.
- async fn on_turn_complete(&self, summary: &TurnSummary) -> Result<()> {
- if self.hooks.is_empty() {
- return Ok(());
- }
-
- // Names only. This log line is the sole place the summary's tool list
- // is surfaced, precisely because it must not reach a persistence path
- // as a fabricated outcome.
- log::debug!(
- "[tinyagents][learning] turn complete thread={} agent={} tools=[{}] hooks={}",
- summary.thread_id.as_str(),
- summary.agent_id,
- summary.tools_invoked.join(","),
- self.hooks.len()
- );
-
- hooks::fire_hooks(
- &self.hooks,
- &crate::core::runtime::DispatchCtx::from_weak(self.dispatch.as_ref()),
- Self::turn_context_from(summary),
- );
- Ok(())
- }
-}
-
-#[cfg(test)]
-#[path = "learning_sink_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/learning_sink_tests.rs
deleted file mode 100644
index 4bd93b710b..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/learning_sink_tests.rs
+++ /dev/null
@@ -1,137 +0,0 @@
-use super::*;
-use std::sync::Mutex;
-use tokio::sync::mpsc;
-
-/// A hook that forwards each `TurnContext` it receives, so tests can await
-/// the spawned fan-out deterministically instead of sleeping.
-struct RecordingHook {
- tx: mpsc::UnboundedSender<TurnContext>,
-}
-
-#[async_trait]
-impl PostTurnHook for RecordingHook {
- fn name(&self) -> &str {
- "recording"
- }
-
- async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {
- let _ = self.tx.send(ctx.clone());
- Ok(())
- }
-}
-
-/// A hook that always fails, to pin that a hook error never reaches the
-/// sink's caller.
-struct FailingHook {
- called: Arc<Mutex<bool>>,
-}
-
-#[async_trait]
-impl PostTurnHook for FailingHook {
- fn name(&self) -> &str {
- "failing"
- }
-
- async fn on_turn_complete(&self, _ctx: &TurnContext) -> anyhow::Result<()> {
- *self.called.lock().unwrap() = true;
- Err(anyhow::anyhow!("hook blew up"))
- }
-}
-
-fn sample() -> TurnSummary {
- TurnSummary::new("thread-7", "orchestrator")
- .with_text("I prefer terse answers.", "Understood.")
- .with_tool("shell")
- .with_tool("read_file")
-}
-
-#[test]
-fn projection_carries_identity_and_text() {
- let ctx = OpenHumanLearningSink::turn_context_from(&sample());
- assert_eq!(ctx.user_message, "I prefer terse answers.");
- assert_eq!(ctx.assistant_response, "Understood.");
- assert_eq!(ctx.session_id.as_deref(), Some("thread-7"));
- assert_eq!(ctx.agent_id.as_deref(), Some("orchestrator"));
- assert!(ctx.entrypoint.is_none());
- assert_eq!(ctx.iteration_count, 1);
- assert_eq!(ctx.turn_duration_ms, 0);
-}
-
-#[test]
-fn tool_names_are_never_projected_into_tool_call_records() {
- // The regression this whole adapter is shaped around: a names-only
- // summary must not become fabricated `ToolCallRecord` outcomes, or the
- // tool_effectiveness tallies start recording invented successes.
- let summary = sample();
- assert!(summary.used_tools(), "fixture must carry tool names");
- let ctx = OpenHumanLearningSink::turn_context_from(&summary);
- assert!(
- ctx.tool_calls.is_empty(),
- "no outcome data exists to build a ToolCallRecord from"
- );
-}
-
-#[test]
-fn blank_identifiers_normalize_to_none() {
- // A blank agent id must not become `Some("")`, which would key hook
- // state on an empty string rather than falling back to a global bucket.
- let summary = TurnSummary::new(" ", " ").with_text("hi", "hello");
- let ctx = OpenHumanLearningSink::turn_context_from(&summary);
- assert!(ctx.session_id.is_none());
- assert!(ctx.agent_id.is_none());
-}
-
-#[tokio::test]
-async fn on_turn_complete_dispatches_the_projected_context() {
- let (tx, mut rx) = mpsc::unbounded_channel();
- let sink = OpenHumanLearningSink::new(vec![Arc::new(RecordingHook { tx })]);
- assert_eq!(sink.hook_count(), 1);
-
- sink.on_turn_complete(&sample()).await.expect("advisory Ok");
-
- let ctx = rx.recv().await.expect("hook received the turn");
- assert_eq!(ctx.user_message, "I prefer terse answers.");
- assert_eq!(ctx.session_id.as_deref(), Some("thread-7"));
- assert!(ctx.tool_calls.is_empty());
-}
-
-#[tokio::test]
-async fn a_failing_hook_does_not_fail_the_sink() {
- // The turn is already committed when this runs, so the crate contract
- // forbids surfacing a hook failure to the caller.
- let called = Arc::new(Mutex::new(false));
- let (tx, mut rx) = mpsc::unbounded_channel();
- let sink = OpenHumanLearningSink::new(vec![
- Arc::new(FailingHook {
- called: Arc::clone(&called),
- }),
- Arc::new(RecordingHook { tx }),
- ]);
-
- assert!(sink.on_turn_complete(&sample()).await.is_ok());
-
- // Awaiting the surviving hook proves the fan-out ran past the failure.
- rx.recv().await.expect("the second hook still fires");
- assert!(*called.lock().unwrap(), "the failing hook was invoked");
-}
-
-#[tokio::test]
-async fn an_empty_hook_list_is_a_successful_no_op() {
- let sink = OpenHumanLearningSink::new(Vec::new());
- assert_eq!(sink.hook_count(), 0);
- assert!(sink.on_turn_complete(&sample()).await.is_ok());
-}
-
-#[tokio::test]
-async fn with_hook_appends_and_is_usable_as_a_trait_object() {
- // The runtime stores this capability as `Option<Arc<dyn LearningSink>>`;
- // pin that the adapter is object-safe in that position.
- let (tx, mut rx) = mpsc::unbounded_channel();
- let sink = OpenHumanLearningSink::new(Vec::new())
- .with_hook(Arc::new(RecordingHook { tx }) as Arc<dyn PostTurnHook>);
- assert_eq!(sink.hook_count(), 1);
-
- let sink: Arc<dyn LearningSink> = Arc::new(sink);
- sink.on_turn_complete(&sample()).await.expect("advisory Ok");
- rx.recv().await.expect("appended hook fires");
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs b/crates/openhuman-core/src/agent/tinyagents/host/mod.rs
index 11b11d6f89..f46cd1dd4e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/mod.rs
@@ -29,13 +29,9 @@
pub mod budget_gate;
mod bundle;
-pub mod context_composer;
pub mod definition_registry;
pub mod delegation;
-pub mod learning_sink;
-pub mod model_resolver;
mod operation_context;
-pub mod progress_sink;
pub mod run_context;
pub mod security_gate;
pub(crate) mod steering;
@@ -46,11 +42,7 @@ pub use bundle::{
OpenHumanHostBase, OpenHumanHostBundle, OpenHumanHostBundleFactory, OpenHumanHostBundleInputs,
OpenHumanHostInvocationInputs,
};
-pub use context_composer::OpenHumanContextComposer;
pub use definition_registry::OpenHumanDefinitionRegistry;
-pub use learning_sink::OpenHumanLearningSink;
-pub use model_resolver::OpenHumanModelResolver;
-pub use progress_sink::OpenHumanProgressSink;
pub use run_context::{
decide_dispatch, DispatchDecision, DispatchInputs, LastTurnUsage, OpenHumanRunContext,
OpenHumanRunExt, SubagentUsageEntry, TurnDispatchState,
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs b/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs
deleted file mode 100644
index 306ef8e149..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver.rs
+++ /dev/null
@@ -1,367 +0,0 @@
-//! Host capability: **which** model answers a turn.
-//!
-//! Adapts [`tinyagents_harness::host::ModelResolver`] onto OpenHuman's
-//! inference domain — `crate::inference::provider` (the per-role
-//! provider factory: [`create_chat_model_with_model_id`], `provider_for_role`,
-//! [`role_for_model_tier`]) driven by a [`Config`] snapshot.
-//!
-//! This is `docs/specs/plan-agents.md` Phase 4. The crate deliberately refuses
-//! to know about tiers, lead/subagent economics, or BYOK-vs-managed routing —
-//! all of that is OpenHuman product policy, and this module is where it lives.
-//! The mapping performed here is exactly the one the rest of the core already
-//! performs: *workload role* → provider string → concrete `ChatModel`. Nothing
-//! about provider selection, BYOK inheritance, or egress disclosure is
-//! re-implemented; it is all reached through `create_chat_model_with_model_id`,
-//! which is the single chokepoint that emits the `ExternalTransfer` egress
-//! disclosure. Building a client by any other route would bypass that guard.
-//!
-//! # Contract mismatches resolved here
-//!
-//! 1. **`State` erasure.** The trait is generic over the harness state
-//! (`ModelResolver<State>` must return `Arc<dyn ChatModel<State>>`), but
-//! every model OpenHuman builds is a `ChatModel<()>` — the core carries
-//! per-turn values explicitly in `OpenHumanRunContext` and `RunContext`, not in a
-//! typed state value. [`StatelessModel`] bridges the two: it implements
-//! `ChatModel<State>` for *any* `State` by discarding the state reference and
-//! invoking the inner model with `&()`. That is lossless today precisely
-//! because no OpenHuman model reads state; if one ever does, it must stop
-//! going through this wrapper rather than silently observing `()`.
-//!
-//! 2. **"resolve is cheap, and must not be memoized by the caller."** The trait
-//! tells the *runtime* not to cache, which leaves the host free to. A fresh
-//! `create_chat_model_with_model_id` per turn would hand back a new provider
-//! client and throw away its connection pool — the exact waste the trait's
-//! `Arc` return is trying to avoid. Since this resolver holds an immutable
-//! `Arc<Config>` snapshot, the answer for a given workload role cannot change
-//! over its lifetime, so [`OpenHumanModelResolver`] memoizes per role. A
-//! caller that needs re-resolution after a config edit constructs a new
-//! resolver, which is how every other `Arc<Config>` holder in the core works.
-//!
-//! 3. **Tiered routing is not represented.** OpenHuman's richer per-turn model
-//! bundle (primary + workload-tier fallback routes + summarizer) is
-//! `TurnModelSource` / `TurnModels` in `super::super` — a *bundle*, not one
-//! `Arc<dyn ChatModel>`, so it does not fit this signature. See the
-//! `TODO(phase4)` on [`OpenHumanModelResolver::base_model_for_role`].
-//!
-//! 4. **`ModelResolveRequest::model_pin` is not honoured yet.** The field
-//! exists on the crate (this resolver's `-v1` suffix test was written
-//! against it while the pin had nowhere to go), so a definition's exact
-//! model id finally has a route here rather than being smuggled through
-//! `role`. It is deliberately still unread, for two reasons:
-//!
-//! * **Nothing constructs a `ModelResolveRequest` yet.** The crate does not
-//! emit one and this resolver is not repointed, so honouring the pin today
-//! would be code with no producer and no test that could fail honestly.
-//! * **There is no build-by-exact-id seam to honour it with.**
-//! `create_chat_model_with_model_id` takes a *role*, not a model id, so
-//! honouring a pin means adding that path in
-//! `inference::provider::factory` and deciding what happens when the
-//! pinned id is not configured — a real design question, not plumbing.
-//!
-//! When it is wired: the pin is **advisory**. The host decides whether it
-//! can be honoured, because the runtime has no view of credentials or
-//! provider health. Validate the id against configured providers and fall
-//! back to role routing with a warning; never pass it through blind.
-
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
-
-use async_trait::async_trait;
-use tinyagents_harness::error::TinyAgentsError;
-use tinyagents_harness::host::{ModelResolveRequest, ModelResolver};
-use tinyagents_harness::Result as TaResult;
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream};
-
-use crate::config::Config;
-use crate::inference::provider::{create_chat_model_with_model_id_in, role_for_model_tier};
-
-/// The workload roles `provider_for_role` understands **and** that name a
-/// chat-shaped model.
-///
-/// `embeddings` is deliberately absent even though the factory routes it: it
-/// names an embedding model, and handing one back as the turn's `ChatModel`
-/// would fail at dispatch rather than at resolution. An unrecognised role falls
-/// back to the structural default instead (see [`workload_role_for`]).
-const CHAT_WORKLOAD_ROLES: &[&str] = &[
- "chat",
- "reasoning",
- "agentic",
- "coding",
- "burst",
- "vision",
- "memory",
- "summarization",
-];
-
-/// The role a team lead takes when the caller supplied none.
-///
-/// `chat`, matching the live session path rather than the tempting `agentic`.
-///
-/// A lead does drive the tool-heavy orchestration turn, so `agentic` looks
-/// right — but `session/builder/factory.rs::provider_role_for` deliberately
-/// sends the orchestrator and every non-`hint:*` model to `chat`, and pins it
-/// with `orchestrator_defaults_to_chat`. That is what makes the user's
-/// Connections → API keys → LLM **chat** provider drive the user-facing turn.
-/// Defaulting a lead to `agentic` here would silently reroute it onto the
-/// separately-configured agentic provider the moment this seam went live — a
-/// behaviour change smuggled in as a default. `agentic` is reachable, but only
-/// through an explicit `hint:agentic`.
-const LEAD_DEFAULT_ROLE: &str = "chat";
-
-/// The role a non-lead agent takes when the caller supplied none.
-///
-/// `chat` is the core's own default workload, so
-/// an unannotated delegate lands exactly where an unconfigured OpenHuman turn
-/// already lands.
-const SUBAGENT_DEFAULT_ROLE: &str = "chat";
-
-/// Whether `lowered` is a retired tier slug (`hint:reasoning`, …) that
-/// `role_for_model_tier` still recognises as its role, rather than merely
-/// something that ends in `-v1`. Delegates to the config's own legacy table so
-/// this adapter never restates it.
-fn is_known_model_tier(lowered: &str) -> bool {
- crate::config::is_legacy_tier_model(lowered)
-}
-
-/// Maps one [`ModelResolveRequest`] onto an OpenHuman workload role.
-///
-/// This function *is* the product policy the seam exists to hold:
-///
-/// * an explicit role wins, after normalisation — a caller may spell it as a
-/// plain workload role (`"reasoning"`), as a model tier (`"hint:reasoning"`), or
-/// as an agent-definition hint (`"hint:agentic"`), and all three are in live
-/// use across `agent.toml` files and the channel routes;
-/// * otherwise the structural lead/subagent split decides, which is the one
-/// routing fact the runtime can assert honestly.
-///
-/// An unrecognised role is **not** an error: roles reach us as free-form data
-/// that already passed config validation, and refusing to route would turn a
-/// cosmetic typo into an agent that cannot run at all. It falls back to the
-/// structural default with a warning — the same posture
-/// `super::super::config::dispatcher_from` takes.
-fn workload_role_for(req: &ModelResolveRequest) -> &'static str {
- let structural_default = if req.is_team_lead {
- LEAD_DEFAULT_ROLE
- } else {
- SUBAGENT_DEFAULT_ROLE
- };
-
- let Some(raw) = req.role() else {
- tracing::debug!(
- target: "tinyagents",
- agent_id = %req.agent_id,
- is_team_lead = req.is_team_lead,
- role = structural_default,
- "[tinyagents][model_resolver] no role supplied; using the structural default"
- );
- return structural_default;
- };
-
- let lowered = raw.to_ascii_lowercase();
-
- // Tier and hint spellings normalise through the factory's own table so this
- // adapter never re-derives the tier→role mapping (and cannot drift from it).
- //
- // `hint:` is an unambiguous prefix, so it routes unconditionally. `-v1` is
- // not: it is a *suffix heuristic*, and an exact model id can end in `-v1`
- // too. `role_for_model_tier` answers `"chat"` for anything it does not
- // recognise, and it cannot distinguish "this is the chat tier" from "I have
- // never heard of this" — so passing an arbitrary `-v1` id through it would
- // silently reroute to chat with no diagnostic at all. Only hand it values
- // whose stem is a workload role it will actually recognise; anything else
- // falls through to the unknown-role path below, which at least warns.
- if lowered.starts_with("hint:") || is_known_model_tier(&lowered) {
- return role_for_model_tier(&lowered);
- }
-
- if let Some(known) = CHAT_WORKLOAD_ROLES
- .iter()
- .find(|candidate| **candidate == lowered)
- {
- return known;
- }
-
- tracing::warn!(
- target: "tinyagents",
- agent_id = %req.agent_id,
- role = %raw,
- fallback = structural_default,
- "[tinyagents][model_resolver] unknown workload role; falling back to the structural default"
- );
- structural_default
-}
-
-/// Presents a state-agnostic OpenHuman `ChatModel<()>` as a `ChatModel<State>`
-/// for any harness state.
-///
-/// Not a general-purpose adapter: it is sound only because OpenHuman's models
-/// genuinely ignore the harness state (they carry per-turn context in
-/// `OpenHumanRunContext` and `RunContext`). Both `invoke` and `stream` are forwarded so a
-/// streaming provider keeps streaming — falling through to the trait's default
-/// `stream` would silently downgrade every resolved model to replayed unary.
-struct StatelessModel {
- inner: Arc<dyn ChatModel<()>>,
-}
-
-#[async_trait]
-impl<State: Send + Sync> ChatModel<State> for StatelessModel {
- fn profile(&self) -> Option<&ModelProfile> {
- self.inner.profile()
- }
-
- // Forwarded so the harness response cache scopes on the *real* model. The
- // trait default declines identity, and `scoped_cache_key` then folds a fixed
- // "anonymous-model" marker — every wrapped model would share one key space.
- fn cache_identity(&self) -> Option<String> {
- self.inner.cache_identity()
- }
-
- async fn invoke(
- &self,
- _state: &State,
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.inner.invoke(&(), request).await
- }
-
- async fn stream(
- &self,
- _state: &State,
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelStream> {
- self.inner.stream(&(), request).await
- }
-}
-
-/// OpenHuman's [`ModelResolver`]: routes a turn to a workload role, then to that
-/// role's configured provider.
-///
-/// Holds an immutable [`Config`] snapshot — the same shape `TurnModelSource`'s
-/// crate-native source uses — plus a per-role cache of already-built clients.
-pub struct OpenHumanModelResolver {
- config: Arc<Config>,
- /// Temperature applied as the *request default* by the factory; an explicit
- /// per-call `ModelRequest` temperature still wins.
- temperature: f64,
- /// Built clients keyed by workload role. Guarded by a `std::sync::Mutex`
- /// held across no `.await` — model construction is synchronous.
- cache: Mutex<HashMap<&'static str, Arc<dyn ChatModel<()>>>>,
- /// The context the turn runs under; the host's own when none was bound.
- dispatch: Option<crate::core::runtime::DispatchCtx>,
-}
-
-impl OpenHumanModelResolver {
- /// Builds a resolver over `config`, using its configured default
- /// temperature.
- pub fn new(config: Arc<Config>) -> Self {
- let temperature = config.default_temperature;
- Self {
- config,
- temperature,
- cache: Mutex::new(HashMap::new()),
- dispatch: None,
- }
- }
-
- /// Resolve models under `dispatch`, the context of the turn this resolver
- /// serves (agent-local model overrides, tenant routes).
- #[must_use]
- pub fn with_dispatch(mut self, dispatch: crate::core::runtime::DispatchCtx) -> Self {
- self.dispatch = Some(dispatch);
- self
- }
-
- /// Builds a resolver that pins every resolved model to `temperature`
- /// instead of the config default.
- pub fn with_temperature(config: Arc<Config>, temperature: f64) -> Self {
- Self {
- config,
- temperature,
- cache: Mutex::new(HashMap::new()),
- dispatch: None,
- }
- }
-
- /// The config snapshot this resolver routes against.
- pub fn config(&self) -> &Arc<Config> {
- &self.config
- }
-
- /// Resolves (and memoizes) the state-agnostic client for one workload role.
- ///
- /// TODO(phase4): this returns the role's **primary** model only. OpenHuman's
- /// real per-turn bundle — primary + workload-tier fallback routes +
- /// summarizer — is `TurnModels`, built by
- /// `crate::agent::tinyagents::TurnModelSource::build` (see
- /// `build_turn_models_crate` in `crates/openhuman-core/src/tinyagents/mod.rs`). That is a
- /// bundle rather than a single `Arc<dyn ChatModel>`, so it does not fit the
- /// `ModelResolver` signature; wiring cross-tier fallback behind this seam
- /// needs either a crate-side registry hand-off or a second host capability,
- /// and is out of scope for a Phase 4 adapter.
- fn base_model_for_role(&self, role: &'static str) -> TaResult<Arc<dyn ChatModel<()>>> {
- if let Some(hit) = self
- .cache
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .get(role)
- {
- tracing::trace!(
- target: "tinyagents",
- role,
- "[tinyagents][model_resolver] reusing the cached client for this role"
- );
- return Ok(Arc::clone(hit));
- }
-
- // The one construction chokepoint: provider resolution, BYOK/local/managed
- // selection, and the egress disclosure all happen inside here.
- let (model, model_id) = create_chat_model_with_model_id_in(
- &self
- .dispatch
- .clone()
- .unwrap_or_else(crate::core::runtime::DispatchCtx::host_default),
- role,
- &self.config,
- self.temperature,
- )
- .map_err(|error| {
- TinyAgentsError::Model(format!(
- "openhuman: no model for workload role `{role}`: {error}"
- ))
- })?;
-
- tracing::debug!(
- target: "tinyagents",
- role,
- model_id = %model_id,
- "[tinyagents][model_resolver] built a chat model for this workload role"
- );
-
- self.cache
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .insert(role, Arc::clone(&model));
- Ok(model)
- }
-}
-
-impl std::fmt::Debug for OpenHumanModelResolver {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("OpenHumanModelResolver")
- .field("temperature", &self.temperature)
- .finish_non_exhaustive()
- }
-}
-
-#[async_trait]
-impl<State: Send + Sync> ModelResolver<State> for OpenHumanModelResolver {
- async fn resolve(&self, req: &ModelResolveRequest) -> TaResult<Arc<dyn ChatModel<State>>> {
- let role = workload_role_for(req);
- let inner = self.base_model_for_role(role)?;
- Ok(Arc::new(StatelessModel { inner }))
- }
-}
-
-#[cfg(test)]
-#[path = "model_resolver_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/model_resolver_tests.rs
deleted file mode 100644
index 8480bced92..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/model_resolver_tests.rs
+++ /dev/null
@@ -1,242 +0,0 @@
-use super::*;
-
-// ── role routing (the product policy — pure, no provider needed) ─────────
-
-fn req(agent: &str) -> ModelResolveRequest {
- ModelResolveRequest::new(agent)
-}
-
-#[test]
-fn structural_split_decides_when_no_role_is_supplied() {
- assert_eq!(workload_role_for(&req("worker")), SUBAGENT_DEFAULT_ROLE);
- assert_eq!(
- workload_role_for(&req("lead").as_team_lead()),
- LEAD_DEFAULT_ROLE
- );
-}
-
-/// Asserts the literal, not the constant: the point is that this seam agrees
-/// with `session/builder/factory.rs::provider_role_for`, whose
-/// `orchestrator_defaults_to_chat` pins the same answer. Comparing against
-/// `LEAD_DEFAULT_ROLE` would pass no matter what that constant was changed
-/// to, which is exactly the drift that would silently move a user's
-/// orchestrator off their configured chat provider. (`provider_role_for` is
-/// module-private, so this restates its answer rather than calling it.)
-#[test]
-fn an_unannotated_lead_routes_to_chat_like_the_live_session_path() {
- assert_eq!(
- workload_role_for(&req("orchestrator").as_team_lead()),
- "chat"
- );
-}
-
-#[test]
-fn agentic_is_reachable_only_through_an_explicit_hint() {
- assert_eq!(
- workload_role_for(&req("lead").as_team_lead().with_role("hint:agentic")),
- "agentic"
- );
-}
-
-/// `-v1` is a suffix heuristic, and `role_for_model_tier` answers `"chat"`
-/// for anything it does not recognise — so an exact model id that happens to
-/// end in `-v1` would be silently rerouted with no diagnostic.
-#[test]
-fn an_exact_model_id_ending_in_v1_is_not_mistaken_for_a_tier() {
- assert!(!is_known_model_tier("some-vendor-model-v1"));
- assert!(is_known_model_tier("reasoning-v1"));
- assert!(is_known_model_tier("reasoning-quick-v1"));
-
- // Falls through to the unknown-role path (structural default + warning)
- // rather than silently becoming chat via the tier table.
- assert_eq!(
- workload_role_for(&req("w").with_role("some-vendor-model-v1")),
- SUBAGENT_DEFAULT_ROLE
- );
-}
-
-#[test]
-fn an_explicit_role_beats_the_structural_default() {
- // A lead that says "summarization" gets summarization, not agentic —
- // otherwise leadership would silently override an explicit pin.
- let r = req("lead").with_role("summarization").as_team_lead();
- assert_eq!(workload_role_for(&r), "summarization");
-}
-
-#[test]
-fn plain_workload_roles_pass_through_case_insensitively() {
- for role in CHAT_WORKLOAD_ROLES {
- assert_eq!(workload_role_for(&req("a").with_role(*role)), *role);
- let shouted = role.to_ascii_uppercase();
- assert_eq!(workload_role_for(&req("a").with_role(shouted)), *role);
- }
-}
-
-#[test]
-fn tier_and_hint_spellings_normalise_through_the_factory() {
- // Both spellings are in live use: `agent.toml` files write `hint = "..."`
- // and the channel routes carry `*-v1` tier aliases.
- assert_eq!(
- workload_role_for(&req("a").with_role("hint:agentic")),
- "agentic"
- );
- assert_eq!(
- workload_role_for(&req("a").with_role("reasoning-v1")),
- "reasoning"
- );
- assert_eq!(
- workload_role_for(&req("a").with_role("vision-v1")),
- "vision"
- );
-}
-
-#[test]
-fn a_blank_role_reads_as_absent_and_uses_the_structural_default() {
- // `ModelResolveRequest::role()` maps whitespace to `None`; the resolver
- // must not treat "" as a role-specific branch.
- assert_eq!(
- workload_role_for(&req("a").with_role(" ")),
- SUBAGENT_DEFAULT_ROLE
- );
- assert_eq!(
- workload_role_for(&req("a").with_role("").as_team_lead()),
- LEAD_DEFAULT_ROLE
- );
-}
-
-#[test]
-fn an_unknown_role_falls_back_instead_of_failing() {
- assert_eq!(
- workload_role_for(&req("a").with_role("wizardry")),
- SUBAGENT_DEFAULT_ROLE
- );
- assert_eq!(
- workload_role_for(&req("a").with_role("wizardry").as_team_lead()),
- LEAD_DEFAULT_ROLE
- );
-}
-
-#[test]
-fn embeddings_is_not_routable_as_a_chat_role() {
- // The provider factory knows the role, but it names an embedding model:
- // returning one here would fail at dispatch instead of at resolution.
- assert!(!CHAT_WORKLOAD_ROLES.contains(&"embeddings"));
- assert_eq!(
- workload_role_for(&req("a").with_role("embeddings")),
- SUBAGENT_DEFAULT_ROLE
- );
-}
-
-// ── StatelessModel bridging (offline: no provider, no network) ───────────
-
-struct EchoModel(&'static str);
-
-#[async_trait]
-impl ChatModel<()> for EchoModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- Ok(ModelResponse::assistant(self.0))
- }
-}
-
-#[tokio::test]
-async fn stateless_model_invokes_the_inner_model_under_any_state() {
- let bridged = StatelessModel {
- inner: Arc::new(EchoModel("hi")),
- };
-
- // The same wrapper satisfies `ChatModel<State>` for unrelated states.
- let unit: &dyn ChatModel<()> = &bridged;
- assert_eq!(
- unit.invoke(&(), ModelRequest::default())
- .await
- .expect("invoke")
- .text(),
- "hi"
- );
-
- let stringy: &dyn ChatModel<String> = &bridged;
- assert_eq!(
- stringy
- .invoke(&"ignored".to_string(), ModelRequest::default())
- .await
- .expect("invoke")
- .text(),
- "hi"
- );
-}
-
-#[tokio::test]
-async fn stateless_model_is_usable_as_the_resolver_return_type() {
- // Object safety at the exact type the trait hands back is part of the
- // contract, not an implementation detail.
- let model: Arc<dyn ChatModel<u32>> = Arc::new(StatelessModel {
- inner: Arc::new(EchoModel("dyn")),
- });
- let response = model
- .invoke(&7, ModelRequest::default())
- .await
- .expect("invoke");
- assert_eq!(response.text(), "dyn");
-}
-
-// ── resolver wiring ──────────────────────────────────────────────────────
-
-#[test]
-fn new_takes_the_configured_default_temperature() {
- let mut config = Config::default();
- config.default_temperature = 0.42;
- let resolver = OpenHumanModelResolver::new(Arc::new(config));
- assert_eq!(resolver.temperature, 0.42);
-
- let pinned = OpenHumanModelResolver::with_temperature(Arc::new(Config::default()), 0.0);
- assert_eq!(pinned.temperature, 0.0);
-}
-
-#[tokio::test]
-async fn repeated_resolution_reuses_one_client_per_role() {
- // Whether a model can be *built* depends on the ambient config (a test
- // environment may have no provider configured at all), so this test
- // asserts the caching contract only when construction succeeds. The
- // failure path is covered by `unroutable_role_is_an_error`.
- let resolver = OpenHumanModelResolver::new(Arc::new(Config::default()));
- let Ok(first) = resolver.base_model_for_role("chat") else {
- return;
- };
- let second = resolver
- .base_model_for_role("chat")
- .expect("a role that built once must build again");
- assert!(
- Arc::ptr_eq(&first, &second),
- "resolving the same role twice must reuse the client, not rebuild its connection pool"
- );
-}
-
-#[tokio::test]
-async fn resolve_routes_through_the_role_policy() {
- let resolver = OpenHumanModelResolver::new(Arc::new(Config::default()));
- let request = ModelResolveRequest::new("lead").as_team_lead();
- let expected = workload_role_for(&request);
- assert_eq!(expected, LEAD_DEFAULT_ROLE);
-
- // Only assert the end-to-end hand-off when the role is buildable here;
- // the routing decision itself is pinned by the pure tests above.
- if resolver.base_model_for_role(expected).is_ok() {
- let resolved: TaResult<Arc<dyn ChatModel<()>>> =
- ModelResolver::<()>::resolve(&resolver, &request).await;
- assert!(resolved.is_ok(), "a buildable role must resolve");
- }
-}
-
-#[test]
-fn an_unroutable_role_is_reported_as_a_model_error() {
- // `base_model_for_role` only ever fails by way of the factory, so pin the
- // shape of the error the runtime sees rather than forcing that failure.
- let error = TinyAgentsError::Model(
- "openhuman: no model for workload role `chat`: unresolved".to_string(),
- );
- assert!(error.to_string().contains("no model for workload role"));
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs
deleted file mode 100644
index 4e5ddc99f9..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink.rs
+++ /dev/null
@@ -1,593 +0,0 @@
-//! Host capability: turns the crate's coarse [`ProgressEvent`] stream into
-//! OpenHuman's richer [`AgentProgress`] events.
-//!
-//! Adapts `crate::agent::progress` (the `AgentProgress` UI contract)
-//! for `tinyagents_harness::host::ProgressSink`. This is Phase 4 of
-//! `docs/specs/plan-agents.md`.
-//!
-//! # Why this file is the boundary
-//!
-//! `AgentProgress` is the **host's** UI contract — the chat processing
-//! timeline, the subagent drawer, the cost footer and the trace exporter all
-//! read it. The crate deliberately keeps `ProgressEvent` at five variants and
-//! says so in its own module docs: a presentation-shaped field added there
-//! becomes a compatibility surface for every consumer of a redistributed
-//! crate. So the projection runs here, host-side, and `AgentProgress` never
-//! crosses into `vendor/tinyagents`.
-//!
-//! # Why it forwards to an mpsc channel and not to `publish_web_channel_event`
-//!
-//! The obvious-looking shortcut — build a `WebChannelEvent` and publish it
-//! straight onto the web-channel bus — is wrong here. Everything that makes a
-//! web-channel progress event correct is owned by
-//! [`crate::web_chat::progress_bridge::spawn_progress_bridge`]: the
-//! per-request monotonic `seq` stamp the frontend dedups on, the
-//! `TurnStateMirror` snapshot, the run-ledger upserts, the tracing span
-//! collector, and the client/thread/request routing ids that a `ProgressEvent`
-//! does not carry at all. A second independent producer of "what is happening
-//! now" would drift from the bridge's ordering and from the persisted turn
-//! state, and the drift would only show up as a mis-rendered timeline.
-//!
-//! So this sink writes `AgentProgress` into the same
-//! `mpsc::Sender<AgentProgress>` the existing agent turn loop uses
-//! (`OpenHumanSessionHost::set_on_progress`), and the established bridge does the publishing.
-//! `publish_web_channel_event` is still the terminal step — one hop further
-//! down, where it already lives.
-//!
-//! # Contract mismatches, and how they are resolved
-//!
-//! * **`emit` cannot fail, but not every event is equally droppable.** Token
-//! deltas use `try_send` and are *dropped* when the bridge is behind, per the
-//! crate's "dropping progress events is always preferable to slowing the
-//! turn" rule. Lifecycle events (`TurnStarted`, `ToolCallStarted`,
-//! `TurnCompleted`) are not interchangeable with them: the bridge is a state
-//! machine, so a lost one leaves a tool row stuck in `running` forever rather
-//! than costing a UI tick. They therefore wait up to
-//! [`LIFECYCLE_SEND_GRACE`] for room — bounded, never indefinite, because an
-//! unbounded await on this shared channel is the documented subagent-stall
-//! flake (`tool_progress.rs::emit`). Nothing here blocks a turn or panics.
-//! * **The coarse stream has no iteration boundary.** `AgentProgress` carries a
-//! 1-based `iteration` on almost every variant; `ProgressEvent` has no
-//! equivalent. The sink derives one **per run**: a *batch* of consecutive
-//! `ToolCall`s is one iteration, and model output (`Token`) closes the batch
-//! so the next call opens a new one. Counting every call instead would report a
-//! turn that requested two tools in parallel as three iterations. Still a
-//! *lower bound* — two sequential tool batches with no tokens between them are
-//! indistinguishable from one parallel batch. See the `TODO(phase4)` below.
-//! * **One sink may serve several runs.** `Arc<OpenHumanProgressSink>` is
-//! explicitly shared across concurrent sub-runs, so all counters are keyed by
-//! [`RunId`] and only the **first run seen** projects top-level `TurnStarted` /
-//! `TurnCompleted`. A shared counter would let a child's tool calls renumber
-//! the parent's iterations, and a child's `Finished` would tell the progress
-//! bridge the whole request had completed while other runs were still
-//! emitting.
-//! * **`ToolCallCompleted` is emitted from `ProgressEvent::ToolCallFinished`.**
-//! This previously read "none is ever emitted, and none can be": the crate's
-//! stream had no tool-completion milestone, so a row opened by `ToolCall`
-//! could never be closed truthfully, and synthesising one would have asserted
-//! `success: true` for a tool that may have failed — corrupting the timeline
-//! and the trace exporter rather than merely leaving them incomplete. The
-//! crate now emits `ProgressEvent::ToolCallFinished`.
-//!
-//! Two of the three fields `AgentProgress::ToolCallCompleted` needs still do
-//! not travel on the closing event — the tool *name* and the *duration* — so
-//! both are captured when the call opens (`RunState::open_calls`) and
-//! recovered on close. The recorded iteration is used rather than the live
-//! counter, because model output between a call and its result advances the
-//! round and would otherwise file the tool under the wrong one.
-//!
-//! A close with no matching open call is **dropped, not emitted**: without
-//! the opening record there is no honest tool name or duration to report, and
-//! the original reasoning still applies — a missing row is recoverable, a
-//! fabricated one is not.
-//!
-//! `arguments` stays `None`. The crate emits arguments on neither event, so
-//! there is nothing to backfill the span input with, and `None` says "not
-//! captured" rather than "there were none".
-//! * **`ProgressEvent::Error` has no `AgentProgress` counterpart.** The host
-//! enum models a turn's failure through the turn's own `Err` return (which
-//! `web_chat::ops` renders as `chat_error`), not through a progress event.
-//! Synthesising a `TurnCompleted` here would report a failed turn as a
-//! successful one to the ledger and the timeline, so the sink logs the
-//! failure and forwards nothing.
-//! * **`ProgressEvent::Finished { usage }` is not a cost event.**
-//! `AgentProgress::TurnCostUpdated` requires a model id and a USD total that
-//! the crate event does not carry, and OpenHuman's authoritative cost figures
-//! come from the inference layer's charged amounts. Fabricating a
-//! `model: ""` / `total_usd: 0.0` update would silently under-report in the
-//! chat cost footer, so the usage is logged and only `TurnCompleted` is
-//! forwarded.
-
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::Mutex;
-use std::time::Instant;
-
-use async_trait::async_trait;
-use tokio::sync::mpsc::error::TrySendError;
-use tokio::sync::mpsc::Sender;
-
-use tinyagents_harness::host::{ProgressEvent, ProgressSink};
-
-use crate::agent::progress::AgentProgress;
-
-/// How long a **lifecycle** event may wait for room on a full channel.
-///
-/// Sized to ride out the transient window a burst of token deltas opens, while
-/// staying far below anything a user or a parent turn would perceive as a
-/// stall. Deltas never wait at all.
-const LIFECYCLE_SEND_GRACE: std::time::Duration = std::time::Duration::from_millis(50);
-
-/// Iteration bookkeeping for one run.
-// No longer `Copy`: `open_calls` owns per-call state, so the struct is moved or
-// borrowed rather than duplicated. It is only ever touched through the `runs()`
-// mutex guard, which never needed a copy.
-#[derive(Debug, Default, Clone)]
-struct RunState {
- /// Model iterations observed so far, 0 before the first tool call.
- rounds: u32,
- /// Whether the events seen most recently were a run of `ToolCall`s.
- ///
- /// A model can request several tools in one response, and the runtime emits
- /// one event per tool — so consecutive calls are one iteration, not several.
- in_tool_batch: bool,
- /// Tool calls opened but not yet closed, keyed by call id.
- ///
- /// `ProgressEvent::ToolCallFinished` carries neither the tool name nor a
- /// duration, so both are captured when the call *opens* and recovered here.
- /// Keyed by call id rather than kept as a single slot because a model can
- /// request several tools in one response and they close in any order.
- open_calls: HashMap<String, OpenToolCall>,
-}
-
-/// What the opening `ToolCall` knew and the closing event does not.
-#[derive(Debug, Clone)]
-struct OpenToolCall {
- tool_name: String,
- started_at: Instant,
- /// Iteration the call was attributed to when it opened.
- ///
- /// Recorded rather than re-read at completion: model output between the
- /// call and its result advances the counter, so reading it late would
- /// report the tool under the wrong round.
- iteration: u32,
-}
-
-/// Forwards crate progress into an OpenHuman [`AgentProgress`] channel.
-///
-/// Construct one per turn with the same sender that would otherwise be handed
-/// to `OpenHumanSessionHost::set_on_progress`, so the existing
-/// `web_chat::progress_bridge` consumer sees an identical event stream
-/// regardless of which runtime produced it.
-///
-/// Cheap to clone-by-`Arc`: the crate's blanket
-/// `impl ProgressSink for Arc<T>` makes `Arc<OpenHumanProgressSink>` usable
-/// wherever a sink is wanted, which is how a sink shared by concurrent
-/// sub-runs is passed around.
-pub struct OpenHumanProgressSink {
- /// The per-request progress channel the turn loop's consumer owns.
- ///
- /// Bounded by whoever created it. Backpressure is handled by dropping, not
- /// by awaiting — see the module docs.
- tx: Sender<AgentProgress>,
-
- /// Per-run progress state, keyed by [`RunId`].
- ///
- /// Not a single counter, because the type doc explicitly supports one
- /// `Arc<OpenHumanProgressSink>` shared by concurrent sub-runs. With shared
- /// state, a child's `Started` would reset the parent's iteration count and
- /// a child's tool calls would advance it — so the parent's own events would
- /// carry a number describing somebody else's work.
- runs: Mutex<HashMap<String, RunState>>,
-
- /// The first run id observed, treated as the request's root.
- ///
- /// Only the root's lifecycle is projected as *top-level* `TurnStarted` /
- /// `TurnCompleted`. Without this, the first sub-run to finish would tell the
- /// progress bridge the whole request was complete while other runs were
- /// still going — the bridge would close out the turn and everything after it
- /// would render against a finished timeline.
- root_run: Mutex<Option<String>>,
-
- /// How many events were dropped because the channel was full or closed.
- ///
- /// Exposed via [`Self::dropped`] so a diagnostic can distinguish "the UI
- /// showed nothing because nothing happened" from "the UI showed nothing
- /// because the bridge fell behind". Never surfaced to the turn.
- dropped: AtomicU64,
-}
-
-impl OpenHumanProgressSink {
- /// Wraps a per-request `AgentProgress` sender.
- pub fn new(tx: Sender<AgentProgress>) -> Self {
- Self {
- tx,
- runs: Mutex::new(HashMap::new()),
- root_run: Mutex::new(None),
- dropped: AtomicU64::new(0),
- }
- }
-
- /// Number of events dropped so far (full or closed channel).
- pub fn dropped(&self) -> u64 {
- self.dropped.load(Ordering::Relaxed)
- }
-
- /// Locks the per-run state map, tolerating a poisoned mutex.
- fn runs(&self) -> std::sync::MutexGuard<'_, HashMap<String, RunState>> {
- self.runs
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- }
-
- /// Whether `run` is the request's root, claiming the slot if it is vacant.
- ///
- /// First run seen wins. The coarse stream carries no parent/child edge, so
- /// arrival order is the only signal available — and the root's `Started` is
- /// necessarily first, since a sub-run cannot begin before the turn that
- /// spawns it.
- fn is_root_run(&self, run: &str) -> bool {
- let mut root = self
- .root_run
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- match root.as_deref() {
- Some(existing) => existing == run,
- None => {
- *root = Some(run.to_string());
- true
- }
- }
- }
-
- /// The current 1-based iteration index for `run`.
- ///
- /// Starts at `1` — a turn is in its first round before it has called any
- /// tool.
- fn iteration_for(&self, run: &str) -> u32 {
- self.runs()
- .get(run)
- .map(|state| state.rounds.saturating_add(1))
- .unwrap_or(1)
- }
-
- /// Advances `run`'s iteration for a tool call and returns the 1-based index
- /// the call belongs to.
- ///
- /// A *batch* of tool calls is one model iteration. The runtime emits one
- /// `ToolCall` per requested tool, so a model that asks for two tools in
- /// parallel produces two consecutive events that belong to the same
- /// iteration — counting each one would report three iterations for a
- /// two-parallel-calls-then-answer turn and mislabel the second call. Only
- /// the first call after non-tool activity opens a new iteration.
- ///
- /// Still a lower bound, not a fact: the coarse stream has no explicit model
- /// boundary, so a turn that emits no tokens between two sequential tool
- /// batches cannot be distinguished from one parallel batch.
- fn advance_for_tool_call(&self, run: &str) -> u32 {
- let mut runs = self.runs();
- let state = runs.entry(run.to_string()).or_default();
- if !state.in_tool_batch {
- state.rounds = state.rounds.saturating_add(1);
- state.in_tool_batch = true;
- }
- state.rounds
- }
-
- /// Records that non-tool activity was seen for `run`, closing any open tool
- /// batch so the next `ToolCall` starts a fresh iteration.
- fn note_model_activity(&self, run: &str) {
- self.runs()
- .entry(run.to_string())
- .or_default()
- .in_tool_batch = false;
- }
-
- /// Hands one **lifecycle** event to the channel, waiting briefly if the
- /// channel is momentarily full.
- ///
- /// Lifecycle events are not interchangeable with token deltas: the web
- /// progress bridge is a state machine, so a lost `ToolCallStarted` or
- /// `TurnCompleted` leaves a tool row stuck in `running` forever, whereas a
- /// lost `TextDelta` is one missed UI tick. `turn/tools.rs::emit_progress`
- /// awaits its lifecycle sends for exactly that reason.
- ///
- /// It waits with a **bound** rather than awaiting outright, because the
- /// opposite failure is also real and also documented: the sink is a bounded
- /// channel shared by the orchestrator, every inline sub-agent, and their
- /// delta forwarders, and an unbounded `send().await` here can park a
- /// sub-agent's loop and hang the parent turn that is awaiting it — the
- /// subagent-stall flake `tool_progress.rs::emit` was written to avoid.
- /// [`LIFECYCLE_SEND_GRACE`] is the compromise: long enough to ride out the
- /// transient full-channel window a burst of deltas creates, far too short
- /// to stall a turn.
- async fn forward_lifecycle(&self, event: AgentProgress) {
- match self.tx.try_send(event) {
- Ok(()) => return,
- Err(TrySendError::Closed(dropped)) => {
- // No listener; waiting cannot help.
- let total = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
- log::trace!(
- "[tinyagents][progress] dropped lifecycle event on closed channel kind={:?} dropped_total={}",
- std::mem::discriminant(&dropped),
- total,
- );
- return;
- }
- Err(TrySendError::Full(event)) => {
- if self
- .tx
- .send_timeout(event, LIFECYCLE_SEND_GRACE)
- .await
- .is_ok()
- {
- return;
- }
- }
- }
-
- let total = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
- log::warn!(
- "[tinyagents][progress] dropped a lifecycle event after waiting {:?} — the progress \
- bridge may now be out of sync (dropped_total={})",
- LIFECYCLE_SEND_GRACE,
- total,
- );
- }
-
- /// Hands one high-frequency event to the channel, dropping it if the
- /// channel cannot take it right now.
- ///
- /// This is the whole of the sink's failure handling for token deltas, and it
- /// deliberately has no error path out: `ProgressSink::emit` returns unit
- /// precisely so a dead UI socket can never fail a turn.
- fn forward(&self, event: AgentProgress) {
- match self.tx.try_send(event) {
- Ok(()) => {}
- Err(TrySendError::Full(dropped)) => {
- let total = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
- log::debug!(
- "[tinyagents][progress] dropped event on full channel kind={:?} dropped_total={}",
- std::mem::discriminant(&dropped),
- total,
- );
- }
- Err(TrySendError::Closed(dropped)) => {
- let total = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
- log::trace!(
- "[tinyagents][progress] dropped event on closed channel kind={:?} dropped_total={}",
- std::mem::discriminant(&dropped),
- total,
- );
- }
- }
- }
-}
-
-#[async_trait]
-impl ProgressSink for OpenHumanProgressSink {
- /// Projects one [`ProgressEvent`] onto zero or one [`AgentProgress`]
- /// events and forwards it.
- ///
- /// Zero, for the two variants OpenHuman models elsewhere — see the module
- /// docs for `Error` and for the cost half of `Finished`. Never awaits
- /// anything that can block; the body is a counter bump and a `try_send`.
- async fn emit(&self, ev: ProgressEvent) {
- match ev {
- ProgressEvent::Started { run, thread, agent } => {
- // `TurnStarted` is a unit variant: the consumer already knows
- // its own client/thread/request ids (that is exactly why
- // `AgentProgress` carries no routing info), so run/thread/agent
- // are logged for correlation rather than forwarded.
- log::debug!(
- "[tinyagents][progress] turn started run={} thread={:?} agent={}",
- run,
- thread.as_ref().map(|t| t.as_str()),
- agent,
- );
- let is_root = self.is_root_run(run.as_str());
- self.runs()
- .insert(run.as_str().to_string(), RunState::default());
- if !is_root {
- // A sub-run beginning is not the request beginning. Emitting
- // `TurnStarted` here would restart the parent's timeline.
- log::debug!(
- "[tinyagents][progress] sub-run started run={run}; not emitting a \
- top-level TurnStarted"
- );
- return;
- }
- self.forward_lifecycle(AgentProgress::TurnStarted).await;
- }
-
- ProgressEvent::ToolCall { run, call, tool } => {
- // A tool call closes the current round, so the counter advances
- // first and the event is attributed to the round it belongs to.
- let iteration = self.advance_for_tool_call(run.as_str());
- log::debug!(
- "[tinyagents][progress] tool_call run={} call={} tool={} iteration={}",
- run,
- call,
- tool,
- iteration,
- );
- // Remember what the closing event will not carry: the tool name,
- // a start instant, and the round this call belongs to.
- if let Some(state) = self.runs().get_mut(run.as_str()) {
- state.open_calls.insert(
- call.as_str().to_string(),
- OpenToolCall {
- tool_name: tool.clone(),
- started_at: Instant::now(),
- iteration,
- },
- );
- }
- self.forward_lifecycle(AgentProgress::ToolCallStarted {
- call_id: call.as_str().to_string(),
- tool_name: tool,
- // The crate deliberately omits tool arguments from the
- // progress side channel (they can be large and can carry
- // untrusted or sensitive text). `Null` is already the
- // documented shape on the tinyagents path — see
- // `AgentProgress::ToolCallCompleted::arguments`, which
- // backfills the span input for exactly this reason.
- arguments: serde_json::Value::Null,
- iteration,
- // Server-computed timeline copy comes from
- // `Tool::display_label` / `display_detail` at the tool
- // registry, which this sink has no handle to; `None` tells
- // the client to use its own formatter.
- // TODO(phase4): resolve labels from the tool registry
- // (`tinytools::Tool::display_label`)
- // once the sink is constructed with a registry handle.
- display_label: None,
- display_detail: None,
- })
- .await;
- }
-
- ProgressEvent::ToolCallFinished {
- run,
- call,
- success,
- output,
- } => {
- // The tool name / duration / round come from the opening
- // `ToolCall`; the crate's event carries none of them.
- let opened = self
- .runs()
- .get_mut(run.as_str())
- .and_then(|state| state.open_calls.remove(call.as_str()));
- let Some(opened) = opened else {
- // No matching open call: the run was torn down, or a close
- // arrived twice. Emitting anyway would invent a tool name
- // and a duration, so this is dropped and logged instead —
- // a missing row is recoverable, a fabricated one is not.
- log::debug!(
- "[tinyagents][progress] tool_call_finished with no open call \
- run={run} call={call} success={success}; dropping"
- );
- return;
- };
-
- let elapsed_ms = opened.started_at.elapsed().as_millis() as u64;
- log::debug!(
- "[tinyagents][progress] tool_call_finished run={} call={} tool={} \
- success={} elapsed_ms={} output_chars={}",
- run,
- call,
- opened.tool_name,
- success,
- elapsed_ms,
- output.chars().count(),
- );
-
- // Classified only on failure, from the tool's own output — the
- // same text `tools::status::classify` sees on the legacy path,
- // so the timeline renders an identical cause/next-action.
- // `timed_out: false` because the coarse stream does not
- // distinguish a timeout from any other failure; claiming one
- // would put a specific, wrong cause in front of a user.
- let failure = if success {
- None
- } else {
- Some(tinytools::status::classify(&output, false))
- };
-
- self.forward_lifecycle(AgentProgress::ToolCallCompleted {
- call_id: call.as_str().to_string(),
- tool_name: opened.tool_name,
- success,
- output_chars: output.chars().count(),
- output,
- // The crate emits no arguments on either event, so there is
- // nothing to backfill the span input with. `None` says
- // "not captured", which is what actually happened.
- arguments: None,
- elapsed_ms,
- iteration: opened.iteration,
- failure,
- // Same registry gap as the `ToolCallStarted` arm above —
- // TODO(phase4): resolve labels from the tool registry.
- display_label: None,
- display_detail: None,
- // The coarse `ProgressEvent` stream carries no
- // `ToolResult`, so there is no metadata to copy structured
- // payloads from on this path.
- structured: None,
- })
- .await;
- }
-
- ProgressEvent::Token { run, text } => {
- // Model output closes any open tool batch: the next `ToolCall`
- // belongs to a new iteration.
- self.note_model_activity(run.as_str());
- let iteration = self.iteration_for(run.as_str());
- log::trace!(
- "[tinyagents][progress] token run={} chars={} iteration={}",
- run,
- text.len(),
- iteration,
- );
- self.forward(AgentProgress::TextDelta {
- delta: text,
- iteration,
- });
- }
-
- ProgressEvent::Finished { run, usage } => {
- let iterations = self.iteration_for(run.as_str());
- log::debug!(
- "[tinyagents][progress] turn finished run={} iterations={} usage={:?}",
- run,
- iterations,
- usage,
- );
- // TODO(phase4): the usage block is dropped rather than mapped
- // to `AgentProgress::TurnCostUpdated`, which needs a model id
- // and a USD total the crate event does not carry. The
- // authoritative cost path is
- // `crate::agent::cost::TurnCost`, fed from the
- // inference layer's charged amounts; wiring usage through would
- // mean threading the resolved model + a cost estimate into this
- // sink rather than inventing `model: ""` / `total_usd: 0.0`.
- let is_root = self.is_root_run(run.as_str());
- self.runs().remove(run.as_str());
- if !is_root {
- // A sub-run finishing is not the request finishing. This is
- // the corruption that matters most: the bridge would close
- // the turn out while other runs were still producing events.
- log::debug!(
- "[tinyagents][progress] sub-run finished run={run}; not emitting a \
- top-level TurnCompleted"
- );
- return;
- }
- self.forward_lifecycle(AgentProgress::TurnCompleted {
- iterations,
- stop: None,
- })
- .await;
- }
-
- ProgressEvent::Error { run, message } => {
- // Not forwarded on purpose. `AgentProgress` has no turn-level
- // failure variant — a failed turn surfaces through the turn's
- // own `Err`, which `web_chat::ops` renders as `chat_error` —
- // and emitting `TurnCompleted` here would record a failure as a
- // success in both the run ledger and the chat timeline.
- log::warn!("[tinyagents][progress] turn failed run={run} err={message}");
- // TODO(phase4): if the runtime ever becomes the only producer
- // of turn outcomes, this needs a real host-side failure event
- // (a new `AgentProgress` variant plus a `chat_error` mapping in
- // `web_chat::progress_bridge`), not a repurposed one.
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "progress_sink_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs
deleted file mode 100644
index c67be2d298..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/host/progress_sink_tests.rs
+++ /dev/null
@@ -1,492 +0,0 @@
-use super::*;
-use tinyagents_harness::ids::{CallId, RunId, ThreadId};
-use tinyinference_llm::usage::Usage;
-use tokio::sync::mpsc;
-
-fn run() -> RunId {
- RunId::new("run-1")
-}
-
-fn started() -> ProgressEvent {
- ProgressEvent::Started {
- run: run(),
- thread: Some(ThreadId::new("thread-1")),
- agent: "orchestrator".to_string(),
- }
-}
-
-fn tool_call(name: &str) -> ProgressEvent {
- ProgressEvent::ToolCall {
- run: run(),
- call: CallId::new("call-1"),
- tool: name.to_string(),
- }
-}
-
-fn tool_call_finished(success: bool, output: &str) -> ProgressEvent {
- ProgressEvent::ToolCallFinished {
- run: run(),
- call: CallId::new("call-1"),
- success,
- output: output.to_string(),
- }
-}
-
-fn sink(capacity: usize) -> (OpenHumanProgressSink, mpsc::Receiver<AgentProgress>) {
- let (tx, rx) = mpsc::channel(capacity);
- (OpenHumanProgressSink::new(tx), rx)
-}
-
-/// Drains and returns the first `ToolCallCompleted`, panicking if none
-/// arrives — a silently-absent completion is exactly the #88 bug.
-fn drain_completion(
- rx: &mut mpsc::Receiver<AgentProgress>,
-) -> (String, bool, usize, String, u64, u32, bool) {
- while let Ok(ev) = rx.try_recv() {
- if let AgentProgress::ToolCallCompleted {
- tool_name,
- success,
- output_chars,
- output,
- elapsed_ms,
- iteration,
- failure,
- ..
- } = ev
- {
- return (
- tool_name,
- success,
- output_chars,
- output,
- elapsed_ms,
- iteration,
- failure.is_some(),
- );
- }
- }
- panic!("no ToolCallCompleted was forwarded");
-}
-
-#[tokio::test]
-async fn a_finished_tool_call_closes_the_row_it_opened() {
- // The #88 payoff: a row opened by `ToolCall` must be closable. Before
- // the crate carried a completion milestone this could not be emitted at
- // all, and every timeline entry stayed `running` forever.
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("search")).await;
- sink.emit(tool_call_finished(true, "results")).await;
-
- let (tool_name, success, output_chars, output, _elapsed, iteration, has_failure) =
- drain_completion(&mut rx);
- // The tool name does not travel on the closing event; it is recovered
- // from the opening one.
- assert_eq!(tool_name, "search");
- assert!(success);
- assert_eq!(output, "results");
- assert_eq!(output_chars, "results".chars().count());
- assert_eq!(iteration, 1);
- assert!(!has_failure, "a success carries no failure classification");
-}
-
-#[tokio::test]
-async fn a_failed_tool_reports_failure_and_carries_a_classification() {
- // The specific corruption #88 warned about: defaulting `success: true`
- // would mark a failed tool successful in both the timeline and the
- // trace exporter.
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("search")).await;
- sink.emit(tool_call_finished(false, "connection refused"))
- .await;
-
- let (_tool, success, _chars, output, _elapsed, _iter, has_failure) = drain_completion(&mut rx);
- assert!(!success, "a failed tool must not report success");
- assert_eq!(output, "connection refused");
- assert!(
- has_failure,
- "a failure must carry a classification for the timeline"
- );
-}
-
-#[tokio::test]
-async fn a_completion_is_filed_under_the_round_its_call_opened_in() {
- // Model output between a call and its result advances the round, so
- // reading the live counter at completion would file the tool under the
- // wrong iteration.
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("search")).await;
- sink.emit(ProgressEvent::Token {
- run: run(),
- text: "thinking".to_string(),
- })
- .await;
- sink.emit(tool_call_finished(true, "ok")).await;
-
- let (_tool, _success, _chars, _output, _elapsed, iteration, _has_failure) =
- drain_completion(&mut rx);
- assert_eq!(iteration, 1, "the call opened in round 1");
-}
-
-#[tokio::test]
-async fn an_unmatched_completion_is_dropped_rather_than_invented() {
- // With no opening record there is no honest tool name or duration. A
- // missing row is recoverable; a fabricated one is not.
- let (sink, mut rx) = sink(16);
- sink.emit(started()).await;
- let _ = rx.try_recv();
- sink.emit(tool_call_finished(true, "orphan")).await;
-
- assert!(
- rx.try_recv().is_err(),
- "a completion with no open call must not be forwarded"
- );
-}
-
-#[tokio::test]
-async fn a_completion_is_emitted_only_once_per_call() {
- // The open-call record is removed on close, so a duplicate close (a
- // retry, or a re-delivered event) cannot produce a second row.
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("search")).await;
- sink.emit(tool_call_finished(true, "ok")).await;
- let _ = drain_completion(&mut rx);
-
- sink.emit(tool_call_finished(true, "ok")).await;
- assert!(
- rx.try_recv().is_err(),
- "a duplicate completion must not open a second row"
- );
-}
-
-#[tokio::test]
-async fn started_maps_to_turn_started() {
- let (sink, mut rx) = sink(8);
- sink.emit(started()).await;
- assert!(matches!(
- rx.try_recv().expect("event forwarded"),
- AgentProgress::TurnStarted
- ));
-}
-
-#[tokio::test]
-async fn tool_call_maps_to_tool_call_started_with_null_arguments() {
- let (sink, mut rx) = sink(8);
- sink.emit(tool_call("search")).await;
-
- match rx.try_recv().expect("event forwarded") {
- AgentProgress::ToolCallStarted {
- call_id,
- tool_name,
- arguments,
- iteration,
- display_label,
- display_detail,
- } => {
- assert_eq!(call_id, "call-1");
- assert_eq!(tool_name, "search");
- // The crate keeps tool arguments off the progress side channel;
- // a non-null value here would mean the adapter invented one.
- assert!(arguments.is_null());
- assert_eq!(iteration, 1, "iterations are 1-based");
- assert!(display_label.is_none());
- assert!(display_detail.is_none());
- }
- other => panic!("unexpected event: {other:?}"),
- }
-}
-
-#[tokio::test]
-async fn token_maps_to_text_delta_on_the_current_round() {
- let (sink, mut rx) = sink(8);
- sink.emit(ProgressEvent::Token {
- run: run(),
- text: "hello".to_string(),
- })
- .await;
-
- match rx.try_recv().expect("event forwarded") {
- AgentProgress::TextDelta { delta, iteration } => {
- assert_eq!(delta, "hello");
- assert_eq!(iteration, 1);
- }
- other => panic!("unexpected event: {other:?}"),
- }
-}
-
-#[tokio::test]
-async fn parallel_tool_calls_share_one_iteration() {
- // A model that requests two tools in one response produces two
- // consecutive `ToolCall` events belonging to the *same* LLM iteration.
- // Counting one per call reported this turn as three iterations and
- // mislabelled the second tool as iteration 2.
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("a")).await;
- sink.emit(tool_call("b")).await;
- sink.emit(ProgressEvent::Token {
- run: run(),
- text: "x".to_string(),
- })
- .await;
-
- let iterations: Vec<u32> = std::iter::from_fn(|| rx.try_recv().ok())
- .map(|ev| match ev {
- AgentProgress::ToolCallStarted { iteration, .. } => iteration,
- AgentProgress::TextDelta { iteration, .. } => iteration,
- other => panic!("unexpected event: {other:?}"),
- })
- .collect();
- // Both calls are iteration 1; the model's next reply is iteration 2.
- assert_eq!(iterations, vec![1, 1, 2]);
-}
-
-/// The failure that matters most on a shared sink: a sub-run finishing must
-/// not tell the bridge the whole request is done, or the turn is closed out
-/// while other runs are still emitting.
-#[tokio::test]
-async fn a_sub_runs_lifecycle_is_not_the_requests_lifecycle() {
- let (sink, mut rx) = sink(16);
- let root = RunId::new("root");
- let child = RunId::new("child");
-
- sink.emit(ProgressEvent::Started {
- run: root.clone(),
- thread: None,
- agent: "orchestrator".to_string(),
- })
- .await;
- sink.emit(ProgressEvent::Started {
- run: child.clone(),
- thread: None,
- agent: "worker".to_string(),
- })
- .await;
- sink.emit(ProgressEvent::Finished {
- run: child,
- usage: None,
- })
- .await;
-
- let events: Vec<AgentProgress> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
- assert_eq!(
- events.len(),
- 1,
- "only the root's start should surface, got {events:?}"
- );
- assert!(matches!(events[0], AgentProgress::TurnStarted));
-
- // The root's own completion still lands.
- sink.emit(ProgressEvent::Finished {
- run: root,
- usage: None,
- })
- .await;
- assert!(matches!(
- rx.try_recv().expect("root completion"),
- AgentProgress::TurnCompleted { .. }
- ));
-}
-
-/// A child's tool calls must not renumber the parent's iterations.
-#[tokio::test]
-async fn iteration_counters_are_scoped_per_run() {
- let (sink, mut rx) = sink(16);
- let root = RunId::new("root");
-
- sink.emit(ProgressEvent::Started {
- run: root.clone(),
- thread: None,
- agent: "orchestrator".to_string(),
- })
- .await;
- let _ = rx.try_recv();
-
- // Child does three rounds of work.
- for i in 0..3 {
- sink.emit(ProgressEvent::ToolCall {
- run: RunId::new("child"),
- call: CallId::new(format!("c{i}")),
- tool: "grep".to_string(),
- })
- .await;
- sink.emit(ProgressEvent::Token {
- run: RunId::new("child"),
- text: "x".to_string(),
- })
- .await;
- }
- while rx.try_recv().is_ok() {}
-
- // The parent's first tool call is still its first iteration.
- sink.emit(ProgressEvent::ToolCall {
- run: root,
- call: CallId::new("parent-1"),
- tool: "shell".to_string(),
- })
- .await;
-
- match rx.try_recv().expect("parent tool call") {
- AgentProgress::ToolCallStarted { iteration, .. } => assert_eq!(
- iteration, 1,
- "the child's work must not advance the parent's iteration"
- ),
- other => panic!("unexpected event: {other:?}"),
- }
-}
-
-#[tokio::test]
-async fn a_tool_call_after_model_output_opens_a_new_iteration() {
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("a")).await;
- sink.emit(ProgressEvent::Token {
- run: run(),
- text: "thinking".to_string(),
- })
- .await;
- sink.emit(tool_call("b")).await;
-
- let iterations: Vec<u32> = std::iter::from_fn(|| rx.try_recv().ok())
- .map(|ev| match ev {
- AgentProgress::ToolCallStarted { iteration, .. } => iteration,
- AgentProgress::TextDelta { iteration, .. } => iteration,
- other => panic!("unexpected event: {other:?}"),
- })
- .collect();
- assert_eq!(iterations, vec![1, 2, 2]);
-}
-
-#[tokio::test]
-async fn started_resets_the_round_counter_for_a_reused_sink() {
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("a")).await;
- sink.emit(started()).await;
- sink.emit(tool_call("b")).await;
-
- let mut iterations = Vec::new();
- while let Ok(ev) = rx.try_recv() {
- if let AgentProgress::ToolCallStarted { iteration, .. } = ev {
- iterations.push(iteration);
- }
- }
- assert_eq!(iterations, vec![1, 1], "a new turn restarts at round 1");
-}
-
-#[tokio::test]
-async fn finished_maps_to_turn_completed_carrying_the_round_count() {
- let (sink, mut rx) = sink(16);
- sink.emit(tool_call("a")).await;
- let _ = rx.try_recv();
-
- sink.emit(ProgressEvent::Finished {
- run: run(),
- usage: Some(Usage {
- input_tokens: 12,
- output_tokens: 3,
- total_tokens: 15,
- ..Usage::default()
- }),
- })
- .await;
-
- match rx.try_recv().expect("event forwarded") {
- AgentProgress::TurnCompleted { iterations, .. } => assert_eq!(iterations, 2),
- other => panic!("unexpected event: {other:?}"),
- }
- // Usage is deliberately NOT projected onto TurnCostUpdated — see the
- // module docs. A fabricated cost update would under-report in the UI.
- assert!(rx.try_recv().is_err(), "no cost event is synthesised");
-}
-
-#[tokio::test]
-async fn finished_without_usage_still_completes_the_turn() {
- let (sink, mut rx) = sink(8);
- sink.emit(ProgressEvent::Finished {
- run: run(),
- usage: None,
- })
- .await;
- assert!(matches!(
- rx.try_recv().expect("event forwarded"),
- AgentProgress::TurnCompleted {
- iterations: 1,
- stop: None
- }
- ));
-}
-
-#[tokio::test]
-async fn error_forwards_nothing() {
- let (sink, mut rx) = sink(8);
- sink.emit(ProgressEvent::Error {
- run: run(),
- message: "provider unavailable".to_string(),
- })
- .await;
- // Reporting a failure as a completion would corrupt both the run ledger
- // and the chat timeline; the turn's own Err is the authoritative path.
- assert!(rx.try_recv().is_err());
- assert_eq!(sink.dropped(), 0, "not forwarding is not dropping");
-}
-
-#[tokio::test]
-async fn a_permanently_full_channel_drops_instead_of_stalling_the_turn() {
- let (sink, mut rx) = sink(1);
- sink.emit(started()).await;
- // Nothing ever drains, so the grace window expires and the events are
- // dropped. The turn must still finish rather than park forever.
- sink.emit(tool_call("a")).await;
- sink.emit(tool_call("b")).await;
-
- assert!(matches!(
- rx.try_recv().expect("first event fits"),
- AgentProgress::TurnStarted
- ));
- assert_eq!(sink.dropped(), 2);
-}
-
-#[tokio::test]
-async fn a_lifecycle_event_survives_transient_backpressure_that_drops_a_delta() {
- // The regression: a burst of deltas fills the channel, and a
- // `ToolCallStarted` lost in that window leaves the tool row stuck in
- // `running` forever. A delta lost in the same window costs one UI tick.
- let (sink, mut rx) = sink(1);
- sink.emit(started()).await;
-
- // A delta finds the channel full and is dropped immediately.
- sink.emit(ProgressEvent::Token {
- run: run(),
- text: "hi".to_string(),
- })
- .await;
- assert_eq!(sink.dropped(), 1, "deltas never wait");
-
- // Drive the blocked send and the consumer concurrently on one task, so
- // the ordering comes from poll order rather than from wall-clock sleeps
- // racing the grace window — the send registers as a waiter, then the
- // first `recv` frees a slot and wakes it. No margin to lose under load.
- let consumer = async {
- let first = rx.recv().await;
- let second = rx.recv().await;
- (first, second)
- };
- let ((), (first, second)) = tokio::join!(sink.emit(tool_call("a")), consumer);
- assert!(matches!(first, Some(AgentProgress::TurnStarted)));
- assert!(
- matches!(second, Some(AgentProgress::ToolCallStarted { .. })),
- "the lifecycle event must ride out the transient window, got {second:?}"
- );
- assert_eq!(sink.dropped(), 1, "only the delta was dropped");
-}
-
-#[tokio::test]
-async fn a_closed_channel_is_survivable() {
- let (sink, rx) = sink(8);
- drop(rx);
- // A UI that hung up must not be able to fail the turn.
- sink.emit(started()).await;
- sink.emit(ProgressEvent::Finished {
- run: run(),
- usage: None,
- })
- .await;
- assert_eq!(sink.dropped(), 2);
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index fd2a920701..c1f07931d8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -23,7 +23,6 @@ pub mod config;
mod context_wiring;
mod deadline_wind_down;
pub mod discovery;
-mod embeddings;
pub mod host;
pub(crate) mod hosted_error;
pub(crate) mod journal;
@@ -74,7 +73,6 @@ pub(crate) use crate::agent::message_convert::chat_message_to_message;
pub(crate) use crate::agent::message_convert::ta_call_to_oh_call;
#[allow(unused_imports)] // Wired into the recall/retrieval facade in workstream 09.2.
-pub(crate) use embeddings::ProviderEmbeddingModel;
pub(crate) use observability::SubagentScope;
pub(crate) use reasoning::{apply_requested_effort, parse_reasoning_effort};
pub(crate) use turn_exec::TurnSpec;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index 8483c5f23e..3ed96781d9 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@ -591,7 +591,8 @@ async fn drive_turn(
tool_policy: tool_policy
.as_ref()
.map(|policy| Arc::new(policy.session.clone())),
- model_resolver: hosted_model_resolver,
+ model_resolver: hosted_model_resolver
+ .expect("hosted root retained its selected model resolver"),
},
&run_context,
);
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec_tests.rs
index d8959d27f9..aab0253902 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec_tests.rs
@@ -70,7 +70,6 @@ fn hosted_base() -> Arc<crate::agent::tinyagents::host::OpenHumanHostBase> {
crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only(),
),
security_policy: Arc::new(crate::security::policy::SecurityPolicy::default()),
- post_turn_hooks: Vec::new(),
session_definition: None,
})
}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 0e53ebd7fb..8f6880fdff 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 0e53ebd7fbad32137e5f2a9eefe9264c87744b60
+Subproject commit 8f6880fdfff4bed2b7646fed193e623adce03cfa