Skip to content

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

merge: resolve Embed conflicts with current main

Steven Enamakel30a1addc4ed9
diff --cc Cargo.lock
index 07575975db,774291f203..2bd0d26b49
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -4827,7 -4671,7 +4828,8 @@@ dependencies =
"chrono",
"dirs 6.0.0",
"env_logger",
+ "futures-core",
+ "jsonschema",
"log",
"openhuman",
"reqwest 0.12.28",
diff --cc crates/openhuman-core/Cargo.toml
index 60dd3b5ecd,ad453152f3..cbf7cbcca3
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@@ -691,14 -692,19 +692,21 @@@ tokio = { version = "1", features = ["t
proptest = "1"
[features]
+# Curated forwarding of the existing TinyAgents telemetry exporter.
+langfuse = ["tinyagents-harness/langfuse"]
# Storage drivers for `[storage] url` / `OPENHUMAN_STORAGE_URL` (see the
- # `storage` domain). Memory is always available. Off in the product until a
- # desktop domain moves onto the ports; a cloud build turns on `storage-mongodb`.
+ # `storage` domain). Memory and plain files are always available.
+ # `storage-sqlite` is in the contributor set and the product: the small
+ # desktop stores (approvals, devices, notifications, task sources) keep their
+ # rows in it by default. `storage-mongodb` is in neither; a cloud build turns
+ # it on. `storage-keyring` does not exist: the only tinystoragedrivers
+ # `keyring` gate is `KeyringSecrets`, which the core does not use (its OS
+ # keychain access is the `keyring` crate in `security/keyring`).
storage-sqlite = ["tinystoragedrivers/sqlite"]
storage-mongodb = ["tinystoragedrivers/mongodb"]
- storage-file = ["tinystoragedrivers/file"]
+ # Always on (the dependency enables `file`); kept so existing feature lists
+ # and the forwarding chain keep resolving.
+ storage-file = []
# THE CONTRIBUTOR SET — not the product set.
#
# This list is what a bare `cargo check`, `cargo test` and rust-analyzer
diff --cc crates/openhuman-core/src/agent/tinyagents/budget.rs
index 968d765698,0000000000..95866d319e
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/tinyagents/budget.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/budget.rs
@@@ -1,61 -1,0 +1,76 @@@
+//! Host budget policy, scoped once at admission and carried explicitly to children.
+use std::sync::Arc;
+pub use tinyinference_llm::model::budget::{
+ Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits,
+};
+use tinyinference_llm::model::ChatModel;
+
+/// A shared ledger and conservative reservation bounds for every physical call.
+#[derive(Debug, Clone)]
+pub struct ModelBudget {
+ /// Run/turn ledger. Children of a turn share it.
+ pub ledger: Budget,
+ /// Per-call input, output and charge upper bounds for all allowed routes.
+ pub call: CallBudget,
+}
+impl ModelBudget {
+ /// Apply the policy below retries and fallback selection.
+ pub(crate) fn wrap(&self, model: Arc<dyn ChatModel<()>>) -> Arc<dyn ChatModel<()>> {
+ Arc::new(tinyinference_llm::model::budget::BudgetedModel::new(
+ model,
+ self.ledger.clone(),
+ self.call,
+ ))
+ }
+}
+tokio::task_local! { static MODEL_BUDGET: ModelBudget; }
+/// Scope host policy around turn admission; the explicit run carrier copies it.
+pub async fn with_budget<F: std::future::Future>(budget: ModelBudget, future: F) -> F::Output {
+ MODEL_BUDGET.scope(budget, Box::pin(future)).await
+}
+pub(crate) fn current() -> Option<ModelBudget> {
+ MODEL_BUDGET.try_with(Clone::clone).ok()
+}
+
+// Fanout leaves narrow the existing host depth policy at admission.
+tokio::task_local! { static SPAWN_DEPTH_LIMIT: usize; }
+/// Run a typed fanout call with a narrower model-directed child-depth ceiling.
+pub async fn with_spawn_depth_limit<F: std::future::Future>(limit: usize, future: F) -> F::Output {
+ SPAWN_DEPTH_LIMIT.scope(limit, Box::pin(future)).await
+}
+pub(crate) fn spawn_depth_limit() -> Option<usize> {
+ SPAWN_DEPTH_LIMIT.try_with(|limit| *limit).ok()
+}
+
+/// Effective host depth ceiling, never wider than product policy.
+pub(crate) fn depth(context: &super::host::OpenHumanRunContext) -> usize {
+ context
+ .max_spawn_depth
+ .unwrap_or(crate::agent::harness::MAX_SPAWN_DEPTH)
+ .min(crate::agent::harness::MAX_SPAWN_DEPTH)
+}
+pub(super) fn install_depth(
+ harness: &mut tinyagents_harness::runtime::AgentHarness<(), super::host::OpenHumanRunContext>,
+ context: &super::host::OpenHumanRunContext,
+) {
+ if let Some(max_depth) = context.max_spawn_depth {
+ let mut policy = harness.policy().clone();
+ policy.limits.max_depth = policy.limits.max_depth.min(max_depth);
+ harness.with_policy(policy);
+ }
+}
++
++impl super::turn_models::TurnModels {
++ /// Wrap every concrete route and summarizer below harness retries/fallback.
++ pub(crate) fn with_budget(mut self, budget: Option<&ModelBudget>) -> Self {
++ let Some(budget) = budget else {
++ return self;
++ };
++ self.primary = budget.wrap(self.primary);
++ self.summarizer = budget.wrap(self.summarizer);
++ for (_, route) in &mut self.routes {
++ *route = budget.wrap(route.clone());
++ }
++ self
++ }
++}
diff --cc crates/openhuman-core/src/agent/tinyagents/response_shape.rs
index a5498f1504,7e04d4cadd..f6e1a450f7
--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
@@@ -37,42 -30,13 +37,44 @@@ pub struct ResponseShape
pub response_format: Option<ResponseFormat>,
/// Replaces the turn's per-call output cap.
pub max_output_tokens: Option<u32>,
+ /// Provider routing/reasoning options, applied to every model call.
+ pub provider_options: serde_json::Value,
+ /// Require a successful tool execution before accepting terminal output.
+ pub require_tool_call: bool,
+ /// Nucleus sampling probability applied to every call of this turn.
+ pub top_p: Option<f64>,
}
+/// Validates terminal provider text without retrieving external resources.
+pub trait ResponseValidator: Send + Sync {
+ /// Returns a safe classification, never response content.
+ fn validate(&self, text: &str, finish_reason: Option<&str>) -> Result<(), String>;
+}
+
+impl std::fmt::Debug for ResponseShape {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ResponseShape")
+ .field("response_format", &self.response_format)
+ .field("max_output_tokens", &self.max_output_tokens)
+ .field("validator", &self.validator.is_some())
+ .field("structured_retries", &self.structured_retries)
+ .finish()
+ }
+}
+
/// What the turn's final model call reported.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, PartialEq)]
pub struct FinalResponse {
+ /// Reported accounting captured before the harness can refuse an answer.
+ pub usage: Option<ResponseUsage>,
+ /// Whether any call omitted its charged cost.
+ pub unknown_cost: bool,
+ /// Strict validation classification of the last terminal answer.
+ pub validation_error: Option<String>,
+ /// Number of terminal answer attempts (excluding tool calls).
+ pub structured_attempts: u16,
+ /// Whether the harness ended with a structured validation error.
+ pub structured_failed: bool,
/// The provider's finish reason for the last call (`stop`, `length`, ...).
pub finish_reason: Option<String>,
/// The model the provider says answered the last call.
diff --cc crates/openhuman-embed/README.md
index 74a7018a7a,7e6c1979f1..c6603b764f
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@@ -1,784 -1,9 +1,13 @@@
- # openhuman-embed
+ # OpenHuman Embed
- `openhuman-embed` is the library crate a product depends on to run the
- OpenHuman core inside its own process. It turns the core's JSON controllers
- and ambient task-locals into ordinary Rust types: build one `Runtime`, put any
- number of `Agent`s on it, and run turns that return a typed `TurnOutcome`.
- OpenCompany and other embedding products use it directly, and
- `openhuman-tinyhumans` wraps it to add the hosted TinyHumans backend. The
- narrative walkthrough is
- [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md).
+ A typed Rust facade for running the OpenHuman core inside your application: one Runtime per process, with independently configured Agents.
- Standalone source pins, generated Cargo patches, feature boundaries and shared server runtimes: [consumer setup](CONSUMERS.md).
+ Read the [embedding documentation](https://github.com/tinyhumansai/openhuman/blob/main/gitbooks/developing/embed/README.md), [installation](https://github.com/tinyhumansai/openhuman/blob/main/gitbooks/developing/embed/installation.md), and [quickstart](https://github.com/tinyhumansai/openhuman/blob/main/gitbooks/developing/embed/quickstart.md).
- ## How it works
+ The [cookbook](https://github.com/tinyhumansai/openhuman/blob/main/gitbooks/developing/embed/cookbook.md) is generated from executable examples. Generate complete local API docs with `cargo doc -p openhuman-embed --all-features --no-deps --open`; this workspace crate is currently unpublished.
- The crate has two entry points, and they sit at different heights over the
- core.
+ Hosts supply transport, credentials and application resources. Runtime settings establish shared defaults; agents narrow provider, access, prompt and tool behavior. Use ProfileRuntime when users require separate credentials and workspaces.
+
- ```text
- host product
- |
- | Runtime::builder() ... build() Core::from_runtime(rt)
- v |
- +-----------+ agent(spec) +---------+ |
- | Runtime | --------------> | Agent | (n per |
- +-----------+ +---------+ runtime) |
- | | |
- | CoreBuilder::build | Turn::send | Config / Auth /
- v v | CoreAgent
- +----------------------------------------------+ |
- | openhuman-core (package `openhuman`) | <---+
- | CoreRuntime, CoreContext, controller registry|
- +----------------------------------------------+
- ```
-
- The library API is `Runtime` then `Agent`. `RuntimeBuilder::build` claims the
- process slot, resolves a workspace on disk, assembles one base `Config`,
- writes the TinyHumans API key into the credential store (when given), and
- hands everything to the core's `CoreBuilder`. The result is one booted
- `CoreRuntime` wrapped in a `Runtime`.
-
- `Runtime::agent(spec)` then turns an `AgentSpec` into an `Agent`. Nothing runs
- and no RPC is made. `agent::build::instantiate` validates the id, clones the
- runtime's base config, and applies the spec on top in a fixed order: access,
- provider model, MCP servers, Composio credential, memory binding, then the
- `config` escape hatch. It creates the agent's directories, copies its skills,
- builds its `AgentDefinition`, checks that the agent only narrows the runtime's
- `DomainSet` and `ToolGroups`, and finally derives a per-agent `CoreContext`
- with `CoreContext::derive_with`.
-
- A turn on that agent goes through `Turn::send`:
-
- ```text
- agent.turn("msg").session(id).send()
- |
- |- mint a session id ("embed-<uuid>") if none was given
- |- refuse a half route, or a bearer sent to a non-https endpoint
- |- enter the origin and progress task-local scopes, if set
- |- runtime.run_in(agent ctx, ...)
- | agent_chat_for(config, AgentChatTarget::Definition { .. }, ...)
- | (inference::host_runtime::ops, native, no JSON)
- v
- TurnOutcome { reply, session_id, usage }
- ```
-
- Because the turn runs under the agent's own context, the core's config
- loader, `DomainSet` gate, tool-group filter and skill discovery all read that
- agent's settings. Two agents on one runtime never see each other's provider,
- access tier, MCP servers or skills. Conversations are keyed by thread id and
- agent id, so a turn only resumes its own agent's thread.
-
- The second entry point is `Core`, for a host that built a `CoreRuntime` with
- `CoreBuilder` itself. `Core::from_runtime` wraps it and exposes typed
- sub-facades (`config()`, `auth()`, `agent()`). These go through
- `CoreRuntime::invoke` (the private `call` helper in [`src/call.rs`](src/call.rs)), so they
- honour `DomainSet` gating and absorb the variable `{result, logs}` envelope
- that controllers emit. `CoreAgent` runs the runtime's orchestrator over the
- `inference.agent_chat` RPC. `Core::raw()` is the escape hatch for a call the
- facade does not model yet; a raw call that keeps coming back is a candidate
- for a typed method here.
-
- ## Cancelling one turn
-
- Acquire `Turn::cancellation_handle()` before sending a turn. The handle is
- cloneable and `cancel().await` waits for the turn to stop and for tracked
- commands to be reaped. The agent remains available for later turns:
-
- ```rust,no_run
- # async fn demo(agent: &openhuman_embed::Agent) -> Result<(), Box<dyn std::error::Error>> {
- let mut turn = agent.turn("Run the job.");
- let cancel = turn.cancellation_handle();
- let running = tokio::spawn(turn.send());
- // When the host receives an abort request:
- cancel.cancel().await;
- assert!(matches!(running.await?, Err(openhuman_embed::CoreError::TurnCancelled { .. })));
- # Ok(())
- # }
- ```
-
- Cancellation is scoped to this turn, including while waiting for inference.
- Before send, cancellation prevents dispatch; after completion it is a no-op.
- On Unix, the built-in shell, Node, Python and npm commands kill their process
- group, including descendants. Other platforms stop the direct command. Host
- tools that spawn independent tasks or processes must provide their own cleanup;
- MCP server lifecycles remain owned by the agent. Keep polling `send()` while
- awaiting cancellation, for example in a spawned task as above.
-
- ## Using it
-
- Use the [pinned consumer bootstrap](CONSUMERS.md) to prepare source,
- recursive submodules and the consumer-root Cargo patches together. It generates:
-
- ```toml
- [features]
- default = []
- embed = ["dep:openhuman-embed"]
-
- [dependencies]
- openhuman-embed = { path = "vendor/openhuman/crates/openhuman-embed", optional = true, default-features = false }
- ```
-
- The dependency and generated patch sections belong in the host's workspace
- root. Enabling `embed` still includes the core and its HTTP libraries; the
- host's default build can leave that optional dependency disabled.
-
- ### A runtime and several agents
-
- For hosted TinyHumans inference and services, build the runtime with
- [`openhuman_tinyhumans::RuntimeBuilder`](../openhuman-tinyhumans/README.md).
- It mirrors this crate's builder and installs the SDK-backed backend transport
- on `build()`. The plain `openhuman_embed::RuntimeBuilder` suits standalone
- hosts that bring their own providers.
-
- ```rust,no_run
- use openhuman_tinyhumans::{
- embed::{Access, AgentSpec, McpServer, Provider, Workspace},
- RuntimeBuilder,
- };
-
- # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
- let runtime = RuntimeBuilder::new()
- .workspace(Workspace::dir("/var/lib/my-product/openhuman"))
- .api_key("th_live_...") // the only credential in library mode
- .build()
- .await?;
-
- let reviewer = runtime.agent(
- AgentSpec::new("reviewer")
- .system_prompt("You review pull requests and never edit files.")
- .access(Access::readonly())
- .skills_dir("./skills/review") // copied into this agent's skills root
- .action_dir("/srv/checkouts/pr-42"),
- )?;
-
- let fixer = runtime.agent(
- AgentSpec::new("fixer")
- .provider(Provider::openai_compatible("https://api.example/v1", "sk-...").model("gpt-5"))
- .access(Access::full())
- .mcp(McpServer::stdio("github", "gh-mcp", ["stdio"]))
- .action_dir("/srv/checkouts/pr-42"),
- )?;
-
- let review = reviewer.run("Summarise the risks in this change.").await?;
- let fix = fixer
- .turn(format!("Address these findings:\n{}", review.reply))
- .send()
- .await?;
-
- // Continue the same conversation with the same agent.
- let again = fixer.turn("Now run the tests.").session(&fix.session_id).send().await?;
- println!("{}", again.reply);
- # Ok(())
- # }
- ```
-
- `McpServer` and `AgentSpec::mcp` need the `mcp` feature; `skills_dir` needs
- `skills`. `Agent::run` always starts a new conversation. To continue one, pass
- the returned `session_id` to `Turn::session`.
-
- A `Turn` has more knobs than the example shows: `model` and `temperature`
- for one turn, `cwd` to root the file and shell tools somewhere else (use
- `openhuman_embed::absolute` for a relative path, since the core resolves a
- relative `cwd` against `action_dir`), `route` for a one-off endpoint,
- `origin` for the authority the turn claims, `on_progress` for live
- `AgentProgress` events, `meter` for usage that is reported even when the turn
- fails, and `seed` to replace the session's history with rows the host
- supplies.
-
- ### Harness: the one-agent shorthand
-
- `Harness` is a `Runtime` plus exactly one `Agent` with the id `harness`,
- built from one set of inputs. `harness.runtime()` and `harness.agent()` hand
- out the two halves, so a host that outgrows one agent adds more on the same
- runtime instead of building a second harness.
-
- ```rust,no_run
- use openhuman_embed::{Access, Harness, Provider, Workspace};
-
- # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
- let harness = Harness::builder()
- .provider(Provider::openai_compatible("https://api.example/v1", "sk-...").model("gpt-5"))
- .workspace(Workspace::Ephemeral)
- .access(Access::readonly())
- .build()
- .await?;
-
- let first = harness.run("Summarize what you can see.").await?;
- let second = harness
- .turn("Now list the risks.")
- .session(&first.session_id)
- .send()
- .await?;
- println!("{}", second.reply);
- # Ok(())
- # }
- ```
-
- A harness keeps a few older defaults. Its agent's `action_dir` is the
- workspace's own `action/` directory, its skills are copied into the shared
- `<workspace>/skills` root, and it only turns on the `mcp` and `skills` domain
- families when servers or a skills directory were supplied. See
- [`src/harness/README.md`](src/harness/README.md).
-
- ### The typed core facade
-
- ```rust,no_run
- use std::sync::Arc;
-
- use openhuman_embed::{Core, CoreBuilder, DomainSet, HostKind, ServiceSet};
-
- # async fn run() -> Result<(), Box<dyn std::error::Error>> {
- let runtime = CoreBuilder::new(HostKind::Library)
- .domains(DomainSet::embedded())
- .services(ServiceSet::none())
- .build()
- .await?;
- let core = Core::from_runtime(Arc::new(runtime));
- let flags = core.config().runtime_flags().await?;
- println!("log_prompts={}", flags.log_prompts);
- # Ok(())
- # }
- ```
-
- `Core::agent()` needs the `inference` domain family at runtime. Note that
- `DomainSet::harness()` leaves `inference` off despite its name; use
- `DomainSet::embedded()`.
-
- ### Product identity
-
- An embedding product sets its identity once at startup, before any backend
- client is built. It becomes the `x-sdk-name` header on TinyHumans requests.
-
- ```rust,no_run
- use openhuman_tinyhumans::{set_product_identity, ProductIdentity};
-
- if let Some(identity) = ProductIdentity::new("opencompany") {
- set_product_identity(identity);
- }
- ```
-
- `openhuman_tinyhumans::RuntimeBuilder::product_identity` does the same as
- part of the build.
-
- ## What the runtime owns and what an agent owns
-
- The runtime owns everything that is process-scoped in the core: the
- workspace and credential store, the event bus, the keyring, the RPC bearer,
- the background `ServiceSet`, the registered `DomainSet` and the API key.
- Agents can only narrow the domain set, so a runtime has to register `mcp` and
- `skills` if any agent will use them. The default runtime does when those
- features are compiled in.
-
- Each agent owns its provider route and model, its access tier and turn
- origin, its `action_dir`, its MCP servers, its skills root, its
- `AgentDefinitionSpec` (system prompt, tool scope, sandbox mode, iteration cap,
- temperature), its narrowed `DomainSet` and `ToolGroups`, its memory binding
- and an optional host tool factory.
-
- The on-disk layout under a runtime-owned root:
-
- ```text
- <root>/
- config.toml, auth-profiles.json, core.token runtime-wide
- workspace/
- session_db/sessions.db runtime-wide run ledger
- agents/<id>/session_raw/ each agent's transcripts
- agents/<id>/skills/, workflows/ each agent's skills roots
- agents/<id>/cron/jobs.db each agent's cron jobs
- agents/<id>/action/ default action_dir per agent
- ```
-
- The default `action_dir` sits beside the workspace, never inside it, because
- the core refuses agent writes beneath the workspace. An inherited workspace
- uses `<action_dir>/agents/<id>` instead.
-
- ### Per agent
-
- Every agent on a runtime is isolated from its siblings on the same workspace:
-
- - Policy and approvals: the autonomy tier, `auto_approve`, `auto_approve_all`
- and the approval gate switch come from the agent's `Access`
- (`auto_approve`, `auto_approve_all`, `approval_gate`). Parked approvals
- carry the agent id; `Agent::approvals()` lists and decides only that
- agent's requests, and a chat reply routes by agent and thread.
- - Sub-agents: `AgentSpec::subagents` declares workers only that agent can
- delegate to. Built-in ids (`orchestrator`, `planner`, …) are reserved.
- Detached sub-agents keep the agent's provider route.
- - MCP: each agent has its own MCP host and dynamic registry under
- `<workspace>/agents/<id>/`, plus the servers its spec declares.
- - Transcripts: `<workspace>/agents/<id>/session_raw/`. Conversations written
- before this layout into `<workspace>/session_raw/` stay readable and are
- copied into the agent's directory when resumed; the shared file is never
- changed.
- - Skills: `install_skill` and `create_skill` write user-scope bundles into
- `<workspace>/agents/<id>/skills/` and `workflows/`, which only that agent
- discovers. The operator's `~/.openhuman` is untouched.
- - Cron: jobs an agent creates live in `<workspace>/agents/<id>/cron/jobs.db`
- and run under that agent's context, provider and policy.
- - Memory sources are synced per live agent, under its own context.
- - Turn tables, plan mode, reasoning effort, turn citations, budget signals,
- the request journal, sub-agent dedupe and the `run_workflow` guard live in
- the agent's context, so two agents can use the same thread or session id
- at the same time.
-
- ### Lifecycle
-
- `RuntimeBuilder::max_agents` caps live agents (default
- `DEFAULT_MAX_AGENTS`, 1024); `Runtime::agent` returns
- `AgentError::AgentLimit` past it. `Runtime::remove_agent(id)` denies the
- agent's parked approvals (resolution `agent_removed`), refuses new turns and
- ends the ones in flight with `CoreError::AgentRemoved` (waiting up to ten
- seconds for them to unwind), then drops its state slots and MCP host and
- deregisters its context, which leaves its cron jobs dormant. The id is
- reusable once it returns; `.purge()` also deletes the agent's home.
- Dropping the last handle to an agent tears it down the same way with
- resolution `agent_dropped`. Cancellation is cooperative: a tool already
- executing, or a sub-agent the turn detached, may finish after removal.
-
- ### Still process-owned
-
- - The event bus, keyring and credential store, and the API key (or
- session): one per runtime, shared by every agent.
- - The approval gate engine and its store. Rows are labelled and decided per
- agent, but the store is one file per workspace.
- - Sub-agent run-ledger rows. They are keyed by unique run ids; an owner
- column would need a schema change in the vendored `tinyagents-session`.
- - The host-installed session store (`openhuman_rpc::session_store`) keeps
- its single-operator layout; the per-agent transcript layout applies to the
- core's file fallback and to embedded agents.
- - Background-delivery busy flags and skill run cancellation, which are keyed
- by unique session and run ids.
- - A per-turn `Turn::route` override reaches that turn only; detached
- sub-agents use the agent's own route.
-
- ### Out of scope
-
- - A per-agent cost log. It is accounting rather than behaviour isolation,
- `Turn::meter` already reports per turn, and a per-agent budget is a
- separate request.
- - Embedded agents delegating to one another. Peer delegation is a
- cross-agent trust decision that TinyHiveMind owns.
- - An API to add a memory source to a running agent. `AgentSpec` memory
- sources are taken when the agent is created; nothing needs more yet.
-
- ## Authentication and the backend
-
- Library mode has no user login. `RuntimeBuilder::api_key` stores a
- TinyHumans API key in the runtime's credential store before the core boots.
- Managed inference then sends it as `Authorization: Bearer <key>`, backend
- REST calls send it as `x-api-key`, and the scheduler gate treats the runtime
- as signed in. There is no `/auth/me` round trip and no session to expire. An
- agent that names its own `Provider` never uses the key for inference.
-
- The key covers the hosted features the core reaches: managed inference,
- cloud embeddings, voice (STT and TTS), web search, media generation, the Jev
- ranker, Composio and the other `/agent-integrations/*` tools, referral and
- webhooks. Callers that can only send a bearer (the vendored STT and embedding
- clients, the connector module's proxy route, the memory engine's sync) send
- the key as `Authorization: Bearer`, which the backend accepts by its
- `tiny_live_` / `tiny_test_` prefix. What a key may reach is decided by its
- scopes on the backend (`inference`, `voice`, `search`, `media`, `storage`,
- `account`, `connections`); a missing scope answers `403`, and a key minted
- through the grant flow omits `connections` unless it was asked for. The
- session-bound `/auth/*` flows (OAuth connect, channel link tokens, login
- tokens), the realtime voice agent and the Socket.IO relay still need a
- signed-in user. See
- [`gitbooks/developing/tinyhumans-api-key.md`](../../gitbooks/developing/tinyhumans-api-key.md).
-
- A host that drives backend features for a signed-in user passes a `Session`
- to `RuntimeBuilder::session` (or `HarnessBuilder::session`, or later
- `Auth::store`). The core stores it through `openhuman.auth_set_credential`
- and never validates it. Obtaining and checking the JWT is the host's job,
- which `openhuman_tinyhumans::session` does for the desktop app and TUI.
- `Session::local` builds the offline `.local` token form, which authorizes
- nothing at the backend.
-
- The core reaches the hosted backend only through a `BackendTransport`
- (re-exported here). This crate installs none. Without one, agents, memory,
- skills, tools and RPC still work, and hosted surfaces (managed inference,
- billing, integrations tools, cloud voice, channel relay) answer with a typed
- `BACKEND_UNAVAILABLE:` error. `openhuman_tinyhumans::RuntimeBuilder` installs
- the SDK transport for you; `RuntimeBuilder::backend_transport` takes your own.
-
- ## Memory per tenant
-
- Bind an agent with
- `AgentSpec::memory(MemoryBinding::new(agent_id).root("team:acme"))` and its
- turns run TinyMemory's lifecycle under `team:acme/agent:<agent_id>`.
- `Runtime::memory("team:acme")` returns a `memory::Memory`, the operator's view
- of that tenant: its agents, items, learnings and brain documents, with every
- call confined to the root's subtree. `RuntimeBuilder::memory_engine` installs
- a host-supplied engine in place of the configured one. See
- [`docs/specs/memory-v2.md`](../../docs/specs/memory-v2.md).
-
- ## Conversations in a host store
-
- By default an agent's transcripts, turn journal, run status, goals and todos
- are files under the workspace. A host serving many users from one process
- keeps them in its own database instead:
-
- ```rust,ignore
- let runtime = Runtime::builder()
- .workspace(Workspace::stateless()) // nothing durable on disk
- .session_store(Arc::new(MyMongoStores::new(db)))
- .build()
- .await?;
- ```
-
- The runtime asks the provider (`session_store::SessionStoreProvider`) for each
- agent's stores by agent id, so a provider over a shared database scopes every
- query by agent. A reopened agent resumes its thread from the store, in any
- process. `InMemorySessionStores` keeps everything in memory, and the
- conformance suites re-exported from `session_store` are what a host's
- provider is held to. `Workspace::stateless()` refuses to build without a
- store (`RuntimeError::NoSessionStore`); a private scratch directory, removed
- with the runtime, still holds process-local caches. The desktop app, CLI and
- TUI install `openhuman_rpc::session_store`, the classic on-disk layout behind
- the same port.
-
- ### Scheduling
-
- `Runtime::cron()` upserts named jobs (`JobSpec::agent` for a turn of a
- runtime agent with its host tools, `JobSpec::system` for a handler registered
- with `Runtime::on_system_job`), lists, removes, runs them now and reads their
- history. A `ServiceSet` with `cron: true` starts the scheduler on `build()`
- and stops it with the runtime; `start_services` / `stop_services` control it
- explicitly. See [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md#scheduling)
- and `tests/cron_agents.rs`.
-
- ### Channels
-
- `Runtime::channels().telegram(TelegramChannelSpec::new(token, agent_id))`
- starts a Telegram listener whose every message is a turn of that runtime
- agent: its prompt, its host tools and the chat's history. The agent must
- exist first (`ChannelError::UnknownAgent` otherwise), and if it is dropped
- later the bot answers that it is unavailable rather than falling back to the
- orchestrator. Turns run as `ExternalChannel` and are capped at read-only:
- tools that write or reach outside are withheld or refused at once. The
- returned `ChannelListener` stops the bot when it is dropped. Behind the
- `channels` feature (on by default). See the gitbook's "Channels" section and
- `tests/channel_agents.rs`.
-
- ## Many users in one process: `ProfileRuntime`
-
- `Runtime` serves one operator. A server that already authenticates its own
- users and wants each of them isolated (their own workspace, credential,
- threads, memory and policy) uses `ProfileRuntime` instead: the SaaS profile
- host (`openhuman_core::profiles`) driven in-process, without the JSON-RPC
- gateway.
-
- ```rust,no_run
- # async fn demo() -> Result<(), openhuman_embed::ProfileError> {
- use openhuman_embed::profiles::ProfileCredentialKind;
- use openhuman_embed::{ProfileRuntime, RelayMessage, SaasConfig};
-
- let profiles = ProfileRuntime::build(SaasConfig::new("/srv/openhuman")).await?;
- let alice = profiles.provision("alice").await?;
- profiles
- .set_credential(&alice.profile_id, ProfileCredentialKind::ApiKey, "th_...")
- .await?;
-
- let handle = profiles.open("alice").await?; // keeps alice open
- let reply = handle.chat("t1", "hello").await?; // web chat, final reply
- let mut events = handle.events(); // only alice's events
- handle
- .relay_inbound(RelayMessage::new("telegram", "777", "555", "tg-1", "hi"))
- .await?; // reply arrives as `channel_outbound`
- # let _ = (reply, events.recv().await); Ok(()) }
- ```
-
- - `ProfileRuntime::{build, builder}` boot `core::runtime::saas::build` with a
- `SaasConfig` (the operator's settings: root, slots, idle eviction, id mode,
- storage URL, node id, lease TTL). `ProfileRuntimeBuilder::session_store`
- installs a host session store first. When the configured service token file
- is missing, `build` writes a random owner-only one, since nothing serves a
- gateway here; the rest of the boot guard runs unchanged.
- - `provision(user_id)`, `open(user_id)`, `list()`, `release(&ProfileId)`,
- `deprovision(&ProfileId)`, `set_credential(..)` and `shutdown()` map onto
- the `ProfileHost`. `open` answers `OpenError::HeldElsewhere(record)` for a
- profile another node holds the lease on.
- - A `ProfileHandle` holds its profile **in use** while it (or a clone) lives:
- not evicted, and `release` refuses it. Every call runs under the profile's
- own `CoreContext`, through the same `USER_METHODS` surface as the gateway:
- `chat(thread, text)` (creates the thread, waits for `chat_done` /
- `chat_error`), `relay_inbound(RelayMessage)`, `events()`, `threads()`,
- `messages(thread)`, `call(method, params)` and `scope(fut)`.
- - **It locks the process into SaaS mode** (`core/runtime/mode.rs`). It fails
- if any core already runs in the process, and once it is built
- `Runtime::builder()`, `Harness` and a second `ProfileRuntime` all refuse to
- boot. Use it in a process of its own.
- - A profile's config is forced: it names no inference endpoint. Turns use
- managed inference through the installed backend transport
- (`openhuman_tinyhumans::install` in a real host) with each profile's own
- credential.
-
- See [`examples/profiles.rs`](examples/profiles.rs), `tests/saas_profiles.rs`,
- [`gitbooks/developing/saas-profiles.md`](../../gitbooks/developing/saas-profiles.md)
- and [`profiles/README.md`](../openhuman-core/src/profiles/README.md).
-
- ## Tools on an agent
-
- `AgentSpec::tools` gives an agent the host's own in-process tools, each with
- its own schema on the wire. The factory runs once per session build, which
- in practice is once per turn, and receives a `TurnContext` naming the agent
- and the session. `Agent::attach_tools` adds a permanent named tool source to
- an agent that already exists, which is how one library hands a configured
- agent to another. See [`src/agent/README.md`](src/agent/README.md).
-
- ## Layout
-
- | Path | What it does |
- | --- | --- |
- | [`src/lib.rs`](src/lib.rs) | Re-exports (core runtime types, `Tool`, `ToolGroups`, the backend port, `session_store`, `agent_progress`) and `Core`, the typed facade over a caller-built `CoreRuntime`. |
- | [`src/runtime/`](src/runtime/README.md) | `Runtime`, `RuntimeBuilder`, `ApiKey`, and the `CoreGuard` that owns process-scoped state until the last handle drops. |
- | [`src/agent/`](src/agent/README.md) | `Agent`, `AgentSpec`, `AgentDefinitionSpec`, `AgentLayout`, `MemoryBinding`, the build step, and permanent tool attachments. |
- | [`src/harness/`](src/harness/README.md) | `Harness` and `HarnessBuilder`, plus the shared input types: `Access`, `Provider`, `Workspace`, `McpServer`, skill copying, `HarnessError`. |
- | [`src/turn.rs`](src/turn.rs) | `Turn`, `TurnRequest`, `TurnOutcome`, `Route`: one turn, its ambient scopes, and its dispatch to an agent or to the orchestrator. |
- | [`src/call.rs`](src/call.rs) | The private typed dispatch helper over `CoreRuntime::invoke` that every facade method uses. |
- | [`src/config.rs`](src/config.rs), [`src/auth.rs`](src/auth.rs), [`src/core_agent.rs`](src/core_agent.rs) | The `Core` sub-facades: runtime flags, credentials (`Session`, `AuthState`), and the orchestrator turn. |
- | [`src/memory.rs`](src/memory.rs) | `Memory`, the per-tenant memory facade returned by `Runtime::memory`. |
- | [`src/profiles.rs`](src/profiles.rs), [`src/profiles/handle.rs`](src/profiles/handle.rs) | `ProfileRuntime`, `ProfileRuntimeBuilder`, `ProfileHandle`, `ProfileEvents`, `ProfileError`: SaaS profiles in-process (locks the process to SaaS mode). |
- | [`src/process.rs`](src/process.rs), [`src/process_sentry.rs`](src/process_sentry.rs) | Host lifecycle helpers: the agent-sized tokio runtime, logging init, dotenv and launch overrides, the master key, and (`crash-reporting`) the Sentry `ClientOptions` with the single `before_send` chain. |
- | [`src/artifacts.rs`](src/artifacts.rs), [`src/chat_surface.rs`](src/chat_surface.rs), [`src/identity.rs`](src/identity.rs), [`src/modules.rs`](src/modules.rs) | Curated host facades: artifact file resolution, the in-process web-chat event stream, the signed-in identity peek, bundled module releases. `config` also carries `load_or_init`, `load_config_with_timeout`, `default_root_openhuman_dir`, `read_active_user_id`. |
- | [`src/host_internals.rs`](src/host_internals.rs) | `__host` (doc-hidden): an explicit list of core items (nested modules mirroring the core paths, each entry used by a named consumer) for `openhuman-tinyhumans` and `openhuman-rpc` only. |
- | [`src/error.rs`](src/error.rs) | `CoreError`, the error every facade call returns (`Domain`, `Unavailable`, `Rpc`, route refusals). |
- | [`examples/`](examples/README.md) | Runnable programs: one turn on a harness, two agents on one runtime, and two users' profiles on one thread id. |
- | [`tests/`](tests/README.md) | End-to-end suites against `wiremock` providers. |
-
- ## Key types and entry points
-
- - `Runtime` and `RuntimeBuilder` ([`src/runtime/`](src/runtime/)): build once per process,
- then call `Runtime::agent`. `Runtime::core()` gives non-turn access
- (config, auth) without exposing a way to start a turn.
- - `AgentSpec` ([`src/agent/spec.rs`](src/agent/spec.rs)): the pure-data description of an agent.
- Ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`.
- - `Agent` ([`src/agent/mod.rs`](src/agent/mod.rs)): a cheap clone handle. `run`, `turn`,
- `attach_tools`, and path accessors (`action_dir`, `home_dir`,
- `skills_dir`, `transcripts_dir`).
- - `Turn` and `TurnOutcome` ([`src/turn.rs`](src/turn.rs)): configure, then `send`.
- - `Access` ([`src/harness/access.rs`](src/harness/access.rs)): the autonomy tier and turn origin,
- always set together. Presets are `readonly`, `supervised` (the default)
- and `full`.
- - `Provider` ([`src/harness/provider.rs`](src/harness/provider.rs)): `openai_compatible(base_url, key)`
- plus `model`, or `inherit()` for the machine's configured inference.
- - `Workspace` ([`src/harness/workspace.rs`](src/harness/workspace.rs)): `Ephemeral` (default), `Dir`,
- `Stateless`, or `Inherit`.
- - `Harness` ([`src/harness/mod.rs`](src/harness/mod.rs)): one runtime, one agent.
- - `Core` ([`src/lib.rs`](src/lib.rs)): the typed facade over a caller-built runtime.
- - `ProfileRuntime` and `ProfileHandle` ([`src/profiles.rs`](src/profiles.rs)): one SaaS profile per
- user, in-process. Exclusive with `Runtime` in a process.
-
- ## One model call, no runtime: `Completer`
-
- A host that needs *a completion*, not an agent — a code reviewer asking for a
- JSON verdict, a classifier, an extractor — uses `complete::Completer`. It needs
- no `Runtime`, so none of the one-per-process and worker-stack constraints above
- apply, and any number of calls can run concurrently.
-
- ```rust,no_run
- # async fn demo() -> Result<(), openhuman_embed::CoreError> {
- use openhuman_embed::complete::{ChatMessage, CompletionRequest, Completer, ResponseFormat};
- use openhuman_embed::Route;
-
- let completer = Completer::new(Route::openai_compatible("https://openrouter.ai/api/v1", "sk-…"))
- .header("X-Title", "my-app");
- let response = completer
- .complete(
- CompletionRequest::new("openai/gpt-5-mini", vec![ChatMessage::user("Is 7 prime?")])
- .response_format(ResponseFormat::JsonObject)
- .max_tokens(64)
- .provider_options(serde_json::json!({"usage": {"include": true}})),
- )
- .await?;
- println!("{:?} {:?} {:?}", response.structured, response.finish_reason, response.usage);
- # Ok(())
- # }
- ```
-
- It differs from an agent turn on purpose: no prompt-injection guard (callers
- pass untrusted text *as data*), no tools (a request declaring tools is
- refused), no session or orchestrator prompt, and no model fallback — the
- requested model is sent verbatim and `answered_model` reports what the
- provider says actually ran. `finish_reason`, token usage (cached and reasoning
- included) and the gateway-reported cost come back on the response; a
- `CompletionObserver` sees every call, success or failure, for trace export.
-
- `openhuman_embed::embeddings` re-exports the embedding models (OpenAI, Voyage,
- Cohere, Ollama, mock) for hosts that keep their own vector index, with the
- signature format unchanged so stored vectors stay in their partition.
-
- ## Locked-down agents: `HostOnly`
-
- An agent that reads untrusted input (a PR diff) and must never act takes
- `ToolScopeSpec::HostOnly`: the tools it can see and call are the ones the host
- supplies (`AgentSpec::tools`, `Agent::attach_tools`) and nothing else.
-
- ```rust,no_run
- use openhuman_embed::{AgentDefinitionSpec, AgentSpec, HostTurnTools, ToolScopeSpec};
- # fn read_only_tools() -> Vec<Box<dyn openhuman_embed::Tool>> { Vec::new() }
- let spec = AgentSpec::new("reviewer")
- .definition(
- AgentDefinitionSpec::new()
- .bare_prompt("You review pull requests.")
- .tools(ToolScopeSpec::HostOnly),
- )
- .tools(|_| HostTurnTools::advertised(read_only_tools()));
- ```
-
- - No config-derived tool is built and no delegation tool is synthesised, so
- shell, file writes, network, memory, skills, MCP and sub-agents do not exist
- for the model. A deny-by-default gate refuses any other name it calls anyway.
- - Access and sandbox are forced read-only, whatever `Access` was set (even
- after `AgentSpec::config`). Declaring MCP servers or skills is an error.
- - The agent needs its own prompt. `bare_prompt(text)` makes `text` the whole
- system prompt: no identity, safety, tools, workspace or memory section.
-
- Host tools should themselves be read-only: `HostOnly` bounds which tools
- exist, not what they do.
-
- Per turn, `Turn::response_format(ResponseFormat)` (the `complete` type) and
- `Turn::max_tokens(n)` apply to every call of the tool loop on any runtime-owned
- agent. `TurnOutcome` then carries `structured` (the reply parsed as JSON),
- `finish_reason`, `answered_model`, and `usage.reasoning_tokens`.
- `Turn::untrusted_input(true)` reads the message as data, so the prompt-injection
- guard and screen are skipped. It is accepted only on a `HostOnly` agent; any
- other agent refuses the turn (`untrusted_input_requires_host_only`).
-
- ## Feature flags
-
- Every feature is a pass-through to the same-named feature on
- `openhuman-core` (package `openhuman`): `default`, `http-server`, `inference`,
- `documents`, `hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,
- `flows`, `skills`, `mcp`, `crash-reporting`, `channels`, `whatsapp-web`,
- `file-logging` and `scheduler-gate`. A gate added to the core has to be
- forwarded here (and then by `openhuman-tinyhumans` and `openhuman-cli`);
- [`scripts/ci/check-feature-forwarding.mjs`](../../scripts/ci/check-feature-forwarding.mjs) checks the chain.
-
- Three features also gate this crate's own surface. `channels` adds `Runtime::channels`, `Channels`, `TelegramChannelSpec`, `ChannelListener`, `ChannelError` and `StreamMode`. `mcp` adds `HttpHeader`,
- `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`.
- `skills` adds `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.
-
- [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md) has a
- measured minimal feature set, and
- [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)
- has the resulting binary sizes and per-agent memory.
-
- ## Boundaries
-
- - The only in-repo dependency is `openhuman-core` with
- `default-features = false`. Every capability comes from a forwarded
- feature.
- - No JSON-RPC here. This crate does not depend on `openhuman-rpc`; `Outcome`
- and `StructuredRpcError` are core types. `openhuman-app` and
- `openhuman-tui` use `openhuman-rpc` and the core directly and do not use
- this crate.
- - No backend client. The hosted transport, product identity, login-token
- exchange and `/auth/me` live in `openhuman-tinyhumans`.
- - The agent loop, transcripts, session identity and tool-call parsing belong
- to [`vendor/tinyagents`](../../vendor/tinyagents/) (repo `tinyhumansai/tinyagents`); the `Tool` trait
- belongs to its nested `tinytools`. Use the `Tool` re-exported here: a
- separately added `tinytools` builds an incompatible type.
- - Memory contracts come from [`vendor/tinymemory`](../../vendor/tinymemory/) (`tinymemory-api`).
-
- ## Gotchas
-
- - A `ProfileRuntime` locks the process to SaaS mode for good: build it in a
- process that runs no `Runtime`, `Harness` or caller-built core, before and
- after.
- - One runtime per process. The keyring master key, the RPC bearer, the
- event bus and the `Once`-guarded domain subscribers are process-scoped
- (`CoreContext::init`). A second `RuntimeBuilder::build` returns
- `RuntimeError::AlreadyRunning`; a second harness returns
- `HarnessError::AlreadyRunning`. `Core::from_runtime` is not guarded, but
- the same rule applies to the `CoreRuntime` beneath it. The slot is
- released only when the `Runtime` and every `Agent` built on it are
- dropped.
- - Build the tokio runtime yourself. A turn is a deep async state machine,
- and a nested sub-agent overflows tokio's default 2 MiB worker stack, so
- `#[tokio::main]` is not enough. `embed::process` builds one sized for
- turns (`AGENT_WORKER_STACK_BYTES`, `MAX_BLOCKING_THREADS`, both re-exported
- there), so the host needs no core dependency to name them:
-
- ```rust,no_run
- let runtime = openhuman_embed::process::tokio_runtime().expect("tokio runtime");
- ```
-
- - Access has two halves. The autonomy tier drives `SecurityPolicy`, and the
- turn origin (a task-local) drives the approval gate. `Access::full()` sets
- both; setting only the tier through `config` gives an agent whose acting
- tools refuse while the transcript looks plausible. `readonly()` and
- `supervised()` set no origin and leave the approval gate on, so an
- unattended supervised agent stalls on approvals until they expire.
- - When building a `CoreRuntime` yourself, set `config_path` together with
- `workspace_dir` (`CoreBuilder::workspace(dir)` does both). Credentials,
- auth profiles and the keyring file resolve beside `config_path`, so a
- workspace-only override reads the operator's real credentials. `Runtime`
- and `Harness` handle this for `Ephemeral`, `Stateless` and `Dir`, and the
- `AgentSpec::config` escape hatch cannot move it.
- - Supply skills through `skills_dir`, which copies bundles. Skill discovery
- rejects symlinked bundles, so linking them in silently does nothing.
- - `Provider::model` is advisory. A model no provider serves falls back to
- the default rather than failing, and a route with no model resolved is
- ignored.
- - A `Route` (or `Provider::openai_compatible`) that pairs a key with a plain
- `http://` endpoint is refused before dispatch with
- `CoreError::InsecureRoute`. A route without a key is allowed.
- - A resumed session keeps its first system prompt and tool list. Prompt
- changes and a tool factory that returns a different belt only reach new
- sessions.
-
- ## Tests
-
- The integration suites under [`tests/`](tests/README.md) each build one
- runtime per process against `wiremock` providers; unit tests sit beside
- their modules as `*_tests.rs`.
-
- ```bash
- cargo test -p openhuman-embed --features inference,mcp,skills
- cargo test -p openhuman-embed --features inference,mcp,skills --test runtime_agents
- cargo test -p openhuman-embed --features inference,mcp,skills --test cron_agents
- cargo test -p openhuman-embed --features inference,mcp,skills --test channel_agents
- cargo test -p openhuman-embed --test saas_profiles
- ```
-
- `tests/channel_agents.rs` drives a runtime agent from a mocked Telegram Bot API: the bound agent answers with its prompt and read-only host tool under the `ExternalChannel` origin, its write tool is withheld and refused, and the reply is posted back to the chat.
- `tests/saas_profiles.rs` boots a `ProfileRuntime` on a temp root against a mocked inference endpoint: two users on thread `t1` see only their own messages and ride their own credential, a held handle keeps its profile from being released, a relayed Telegram message lands on the user's `channel:` thread with its reply on that user's events only, and the process refuses any other core afterwards.
- `tests/cron_agents.rs` runs a cron job as a runtime agent with its host tool under the
- `TrustedAutomation { Cron }` origin, records a system job handler's error, and starts and
- stops the scheduler with the runtime.
-
- The repository-root [`examples/embed_headless.rs`](../../examples/embed_headless.rs) and [`examples/embed_kernel.rs`](../../examples/embed_kernel.rs)
- use this crate's `Runtime` (`Runtime::builder()`, then `core_runtime().invoke`
- for raw RPC methods). They are `[[example]]` targets of `openhuman-cli`:
- `cargo run -p openhuman-cli --example embed_headless`.
-
- ## Further reading
-
- - [`crates/openhuman-embed/examples/README.md`](examples/README.md): the examples module README.
- - [`gitbooks/developing/embedding.md`](../../gitbooks/developing/embedding.md): embedding the core in another product.
- - [`gitbooks/developing/tinyhumans-api-key.md`](../../gitbooks/developing/tinyhumans-api-key.md): running on a TinyHumans API key.
- - [`gitbooks/developing/architecture.md`](../../gitbooks/developing/architecture.md): architecture overview.
- - [`gitbooks/developing/architecture/agent-harness.md`](../../gitbooks/developing/architecture/agent-harness.md): the agent harness.
- - [`gitbooks/developing/loadable-modules.md`](../../gitbooks/developing/loadable-modules.md): loadable modules.
- - [`crates/README.md`](../README.md): crates overview.
-
- ## Relationship to other crates
-
- Its only in-repo dependency is `openhuman-core` (package `openhuman`) with
- `default-features = false`: every capability comes from a feature forwarded
- above. It does not depend on `openhuman-rpc`; `Outcome` and `StructuredRpcError`
- are core types (`openhuman_core::core`). `openhuman-app` and `openhuman-tui`
- depend on `openhuman-rpc` for its client (and the app on its server) and on
- `openhuman-core`; neither uses `openhuman-embed`.
-
- ## Permanent tools on supplied agents
-
- Hosts can pass an existing configured `Agent` to another library, which adds
- its tools through `Agent::attach_tools` without constructing a replacement.
- Attachments are shared by clones, always directly advertised, and update only
- their managed system catalogue when a continuing conversation gains tools.
- See [agent attachment semantics and example](src/agent/README.md#attach-tools-to-an-existing-agent)
- for source identity, collision errors, policy composition, and runtime identity.
-
- Ordered fallbacks and required exploration: [routing](ROUTING.md). Host telemetry and the existing exporter: [observers](OBSERVERS.md).
++Standalone exact source pins and generated Cargo patches: [consumer setup](CONSUMERS.md).
++Ordered fallbacks and required exploration: [routing](ROUTING.md).
++Host telemetry and the existing exporter: [observers](OBSERVERS.md).
diff --cc crates/openhuman-embed/src/lib.rs
index 9c93d96c62,a2326ce9a4..4e1e2d4b35
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@@ -294,8 -295,21 +303,26 @@@ impl std::fmt::Debug for Core
}
}
+/// Strict structured output failure metadata.
+pub mod structured;
+
+/// Acknowledged cancellation for stateless completion operations.
+pub mod cancellation;
+ /// Runtime event subscriptions without content or credentials.
+ pub mod events;
+ /// Owned streaming turns and cooperative cancellation.
+ pub mod stream;
+ pub use agent::{ApprovalHandler, ApprovalSubscription};
+ pub use events::{EventStreamError, RuntimeEvent, RuntimeEventKind, RuntimeEvents};
+ pub use stream::{CancellationToken, StreamEvent, TurnStream};
+ /// Native custom-provider contract and request/response types.
+ pub mod providers {
+ pub use tinyinference_llm::message::MessageDelta;
+ pub use tinyinference_llm::model::{
+ ChatModel, DeferredHandle, DeferredStatus, ModelProfile, ModelRequest, ModelResponse,
+ ModelStream, ModelStreamItem, ModelStreamMetadata,
+ };
+ pub use tinyinference_llm::{Error, Result};
+ }
+
+ pub use agent_progress::AgentProgress;
diff --cc crates/openhuman-embed/src/stream.rs
index 0000000000,fa29049791..3a95ef004d
mode 000000,100644..100644
--- a/crates/openhuman-embed/src/stream.rs
+++ b/crates/openhuman-embed/src/stream.rs
@@@ -1,0 -1,85 +1,89 @@@
+ //! Owned turn streaming over the harness's existing progress sink.
+ use crate::{AgentProgress, CoreError, Turn, TurnOutcome};
+ use futures_core::Stream;
+ pub use openhuman_core::agent::host_overrides::CancellationToken;
+ use std::pin::Pin;
+ use std::task::{Context, Poll};
+ use tokio::sync::mpsc;
+ use tokio_stream::wrappers::ReceiverStream;
+
+ /// One live progress notification or the final typed turn result.
+ #[derive(Debug)]
+ pub enum StreamEvent {
+ /// Token deltas, tool events, and harness boundaries as they arrive.
+ Progress(AgentProgress),
+ /// Exactly one final result, after all preceding progress.
+ Finished(Result<TurnOutcome, CoreError>),
+ }
+
+ /// A bounded stream that cooperatively cancels its turn when dropped.
+ pub struct TurnStream {
+ inner: ReceiverStream<StreamEvent>,
+ cancellation: CancellationToken,
+ }
+ impl TurnStream {
+ pub(crate) fn start(turn: Turn) -> Self {
+ let cancellation = turn.stream_cancellation();
+ let (tx, rx) = mpsc::channel(64);
+ let (progress_tx, mut progress_rx) = mpsc::channel(64);
+ let token = cancellation.clone();
+ tokio::spawn(async move {
+ let mut result = Box::pin(
+ turn.on_progress(progress_tx)
+ .cancellation(token.clone())
+ .send(),
+ );
- loop {
++ let (outcome, pending) = loop {
+ tokio::select! {
+ biased;
++ outcome = &mut result => break (outcome, None),
+ item = progress_rx.recv() => {
+ if let Some(item) = item {
++ // A blocked stream consumer must not stop polling
++ // turn cancellation, deadlines or cleanup.
++ let retained = item.clone();
+ tokio::select! {
++ outcome = &mut result => break (outcome, Some(retained)),
+ sent = tx.send(StreamEvent::Progress(item)) => { if sent.is_err() { token.cancel(); } },
+ _ = token.cancelled() => {},
+ }
+ } else {
- let outcome = result.await;
- let _ = tx.send(StreamEvent::Finished(outcome)).await;
- break;
++ break ((&mut result).await, None);
+ }
+ }
- outcome = &mut result => {
- while let Ok(item) = progress_rx.try_recv() {
- tokio::select! { _ = tx.send(StreamEvent::Progress(item)) => {}, _ = token.cancelled() => {} }
- }
- let _ = tx.send(StreamEvent::Finished(outcome)).await;
- break;
- }
+ }
++ };
++ drop(result);
++ // The item whose send lost to completion precedes everything still
++ // buffered. Keep progress ordered before the terminal notification.
++ let mut pending = pending;
++ while let Some(item) = pending.take().or_else(|| progress_rx.try_recv().ok()) {
++ tokio::select! { _ = tx.send(StreamEvent::Progress(item)) => {}, _ = token.cancelled() => {} }
+ }
++ let _ = tx.send(StreamEvent::Finished(outcome)).await;
+ });
+ Self {
+ inner: ReceiverStream::new(rx),
+ cancellation,
+ }
+ }
+ /// Receive the next notification without importing a stream extension trait.
+ pub async fn recv(&mut self) -> Option<StreamEvent> {
+ std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
+ }
+ /// The token shared with this turn and its recursive children.
+ pub fn cancellation_token(&self) -> CancellationToken {
+ self.cancellation.clone()
+ }
+ }
+ impl Stream for TurnStream {
+ type Item = StreamEvent;
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+ Pin::new(&mut self.inner).poll_next(cx)
+ }
+ }
+ impl Drop for TurnStream {
+ fn drop(&mut self) {
+ self.cancellation.cancel();
+ }
+ }
diff --cc crates/openhuman-embed/src/turn.rs
index c7e6210165,2806e804c8..36c154afb5
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@@ -76,15 -256,10 +76,18 @@@ pub struct Turn
seed: Option<Vec<(String, String)>>,
meter: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,
response_format: Option<crate::complete::ResponseFormat>,
+ structured_retries: u8,
max_tokens: Option<u32>,
+ top_p: Option<f64>,
- cancellation: Option<crate::CancellationToken>,
++ token_cancellation: Option<crate::CancellationToken>,
+ provider_options: serde_json::Value,
+ require_tool_call: bool,
untrusted_input: bool,
+ cancellation: Option<crate::TurnCancellation>,
+ timeout: Option<std::time::Duration>,
++ control_deadline: Option<tokio::time::Instant>,
+ observer: Option<Arc<dyn crate::observe::TurnObserver>>,
+ trace_content: crate::observe::TraceContent,
}
impl Turn {
@@@ -99,15 -273,10 +102,18 @@@
seed: None,
meter: None,
response_format: None,
+ structured_retries: 0,
max_tokens: None,
+ top_p: None,
- cancellation: None,
++ token_cancellation: None,
+ provider_options: serde_json::Value::Null,
+ require_tool_call: false,
untrusted_input: false,
+ cancellation: None,
+ timeout: None,
++ control_deadline: None,
+ observer: None,
+ trace_content: crate::observe::TraceContent::MetadataOnly,
}
}
@@@ -306,6 -450,27 +312,27 @@@
self
}
+ /// Nucleus sampling for this turn; must be finite and between zero and one.
+ pub fn top_p(mut self, probability: f64) -> Self {
+ self.top_p = Some(probability);
+ self
+ }
+
+ /// Bind caller cancellation to the turn and its recursive tool/agent tree.
+ pub fn cancellation(mut self, token: crate::CancellationToken) -> Self {
- self.cancellation = Some(token);
++ self.token_cancellation = Some(token);
+ self
+ }
+
+ pub(crate) fn stream_cancellation(&self) -> crate::CancellationToken {
- self.cancellation.clone().unwrap_or_default()
++ self.token_cancellation.clone().unwrap_or_default()
+ }
+
+ /// Start this configured turn as an owned stream, cancelled when dropped.
+ pub fn stream(self) -> crate::TurnStream {
+ crate::TurnStream::start(self)
+ }
+
/// Stream live turn progress — tool calls, deltas, turn boundaries.
///
/// The core **awaits** its sends, so the channel's capacity is real
diff --cc crates/openhuman-embed/src/turn_control.rs
index c754e757f5,0000000000..ba160fa2c0
mode 100644,000000..100644
--- a/crates/openhuman-embed/src/turn_control.rs
+++ b/crates/openhuman-embed/src/turn_control.rs
@@@ -1,348 -1,0 +1,499 @@@
+//! Whole-turn validation, observation, cancellation, deadlines and dispatch.
+use super::*;
+
++struct CancellationRelay(tokio::task::JoinHandle<()>);
++
++impl Drop for CancellationRelay {
++ fn drop(&mut self) {
++ self.0.abort();
++ }
++}
++
+impl Turn {
+ /// Run the turn.
+ ///
+ /// Establishes the origin and progress scopes described in the module docs,
+ /// then dispatches through [`call`](crate::call::call) so the
+ /// `{result, logs}` envelope, [`DomainSet`](openhuman_core::core::runtime::DomainSet)
+ /// gating and error classification are handled the same way as every other
+ /// facade method.
+ ///
+ /// # Errors
+ ///
+ /// [`CoreError::Unavailable`] when the `inference` domain family is off —
+ /// that is a build/composition fact, not a failure, and a host should hide
+ /// the surface rather than report an error.
+ pub async fn send(mut self) -> Result<TurnOutcome, CoreError> {
++ // External cancellation cascades inward; cancelling this turn through
++ // its acknowledgement handle/deadline must not cancel a shared parent.
++ let token = self
++ .token_cancellation
++ .clone()
++ .unwrap_or_default()
++ .child_token();
++ // A synchronously ready model stream can stay inside one dispatch poll.
++ // Relay control independently so its native cancellation checks also
++ // interrupt that poll; abort the relay when this turn ends or is dropped.
++ self.control_deadline = self
++ .timeout
++ .and_then(|duration| tokio::time::Instant::now().checked_add(duration));
++ let cancellation = self.cancellation.clone();
++ let deadline = self.control_deadline;
++ let _relay = (cancellation.is_some() || deadline.is_some()).then(|| {
++ let native = token.clone();
++ CancellationRelay(tokio::spawn(async move {
++ tokio::select! {
++ _ = async {
++ match cancellation {
++ Some(handle) => handle.cancelled().await,
++ None => std::future::pending().await,
++ }
++ } => {},
++ _ = async {
++ match deadline {
++ Some(deadline) => tokio::time::sleep_until(deadline).await,
++ None => std::future::pending().await,
++ }
++ } => {},
++ }
++ native.cancel();
++ }))
++ });
++ openhuman_core::agent::host_overrides::with_cancellation(token, self.send_traced()).await
++ }
++
++ async fn send_traced(mut self) -> Result<TurnOutcome, CoreError> {
+ // Keep cancellation acknowledgement behind the terminal callback too.
+ let _observer_guard = self.cancellation.as_ref().map(|handle| handle.enter());
+ let Some(observer) = self.observer.take() else {
- return self.send_controlled().await;
++ return self.send_events().await;
+ };
+ let capture = self.trace_content;
+ let session_id = self
+ .session_id
+ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.session_id = Some(session_id.clone());
+ let message = self.request.message.clone();
- crate::observe::observe_turn(
- observer,
- capture,
- &session_id,
- &message,
- self.send_controlled(),
- )
- .await
++ crate::observe::observe_turn(observer, capture, &session_id, &message, self.send_events())
++ .await
++ }
++
++ // Runtime lifecycle events enclose control/cleanup, while progress delivery
++ // keeps polling that control future even when the caller stops draining.
++ async fn send_events(mut self) -> Result<TurnOutcome, CoreError> {
++ let (hub, agent_id) = match &self.target {
++ TurnTarget::Agent(agent) => (
++ Some(agent._runtime_guard.events.clone()),
++ Some(agent.id.clone()),
++ ),
++ TurnTarget::Runtime(_) => (None, None),
++ };
++ let Some(hub) = hub else {
++ return self.send_controlled().await;
++ };
++ let session_id = self
++ .session_id
++ .clone()
++ .filter(|id| !id.trim().is_empty())
++ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
++ self.session_id = Some(session_id.clone());
++ let thread_id = event_thread_id(self.origin.as_ref(), &session_id);
++ let turn_id = hub.begin_turn(agent_id.clone(), &thread_id);
++ let mut end = ObservedTurn {
++ hub: hub.clone(),
++ agent_id: agent_id.clone(),
++ thread_id,
++ turn_id: turn_id.clone(),
++ success: false,
++ };
++ let forward = self.progress.take();
++ let token = openhuman_core::agent::host_overrides::current_cancellation();
++ let acknowledgement = self.cancellation.clone();
++ let deadline = self.control_deadline;
++ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
++ self.progress = Some(tx);
++ let mut dispatch = self.send_controlled();
++ let mut pending_progress = None;
++ let mut outcome = loop {
++ tokio::select! {
++ biased;
++ result = &mut dispatch => break result,
++ item = rx.recv() => if let Some(item) = item {
++ observe_progress(&hub, &agent_id, &turn_id, &item);
++ if let Some(sink) = &forward {
++ let retained = item.clone();
++ tokio::select! {
++ _ = sink.send(item) => {},
++ _ = token.cancelled() => {},
++ result = &mut dispatch => { pending_progress = Some(retained); break result; },
++ }
++ }
++ } else { break (&mut dispatch).await; },
++ }
++ };
++ drop(dispatch);
++ while let Some((item, observed)) = pending_progress
++ .take()
++ .map(|item| (item, true))
++ .or_else(|| rx.try_recv().ok().map(|item| (item, false)))
++ {
++ if !observed {
++ observe_progress(&hub, &agent_id, &turn_id, &item);
++ }
++ if outcome.is_ok() {
++ if let Some(sink) = &forward {
++ tokio::select! {
++ _ = sink.send(item) => {},
++ _ = token.cancelled() => outcome = Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
++ _ = async {
++ match &acknowledgement {
++ Some(handle) => handle.cancelled().await,
++ None => std::future::pending().await,
++ }
++ } => outcome = Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
++ _ = async {
++ match deadline {
++ Some(deadline) => tokio::time::sleep_until(deadline).await,
++ None => std::future::pending().await,
++ }
++ } => outcome = Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),
++ }
++ }
++ }
++ }
++ end.success = outcome.is_ok();
++ outcome
+ }
+
+ // Erase this large dispatch future at the control boundary: composing
+ // several observed/cancellable turns must not multiply caller stack use.
+ fn send_controlled(
+ mut self,
+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TurnOutcome, CoreError>> + Send>>
+ {
+ Box::pin(async move {
- let timeout = self.timeout.take();
++ let deadline = self.control_deadline;
++ let token = self.token_cancellation.clone();
++ let native = openhuman_core::agent::host_overrides::current_cancellation();
+ let cancellation = match self.cancellation.take() {
+ Some(cancellation) => cancellation,
- None if timeout.is_some() => crate::TurnCancellation::default(),
++ None if deadline.is_some() || token.is_some() => crate::TurnCancellation::default(),
+ None => return Box::pin(self.send_inner()).await,
+ };
+ let _guard = cancellation.enter();
+ let outcome = cancellation
+ .cleanup()
+ .scope(async {
+ tokio::select! {
+ biased;
++ _ = async {
++ match &token {
++ Some(token) => token.cancelled().await,
++ None => std::future::pending().await,
++ }
++ } => Err(CoreError::TurnCancelled { method: AGENT_CHAT }),
+ _ = cancellation.cancelled() => {
++ native.cancel();
+ log::debug!("[embed][agent] turn cancelled");
+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })
+ }
+ _ = async {
- match timeout {
- Some(duration) => tokio::time::sleep(duration).await,
++ match deadline {
++ Some(deadline) => tokio::time::sleep_until(deadline).await,
+ None => std::future::pending().await,
+ }
- } => Err(CoreError::DeadlineExceeded { method: AGENT_CHAT }),
++ } => {
++ native.cancel();
++ Err(CoreError::DeadlineExceeded { method: AGENT_CHAT })
++ },
+ outcome = Box::pin(self.send_inner()) => outcome,
+ }
+ })
+ .await;
+ // The dispatch future is dropped before waiting for its command
+ // waiters. No new command can register after this point.
+ cancellation.cleanup().wait().await;
+ outcome
+ })
+ }
+
+ /// Observe completion and, on runtime-owned agents, model and tool events.
+ /// Caller-built core runtimes provide terminal metadata only. Payloads are
+ /// omitted unless [`Self::trace_content`] explicitly enables them.
+ pub fn observer(mut self, observer: Arc<dyn crate::observe::TurnObserver>) -> Self {
+ self.observer = Some(observer);
+ self
+ }
+
+ /// Explicitly consent to model messages and tool payloads in observations.
+ pub fn trace_content(mut self, content: crate::observe::TraceContent) -> Self {
+ self.trace_content = content;
+ self
+ }
+
+ /// Bound the entire turn, including tool calls and answer repair.
+ /// Deadline errors are returned only after registered subprocess cleanup.
+ pub fn timeout(mut self, duration: std::time::Duration) -> Self {
+ self.timeout = Some(duration);
+ self
+ }
+
+ /// Obtain a cloneable handle that cancels only this turn and awaits its
+ /// subprocess cleanup. Acquire it before moving the turn to `send()`.
+ pub fn cancellation_handle(&mut self) -> crate::TurnCancellation {
+ self.cancellation
+ .get_or_insert_with(Default::default)
+ .clone()
+ }
+
+ async fn send_inner(mut self) -> Result<TurnOutcome, CoreError> {
+ // The core neither mints nor returns a session id, so continuing a
+ // conversation would otherwise be impossible without the caller
+ // inventing an id scheme — which every embedder has then done
+ // differently. Mint one here and hand it back.
+ let session_id = self
+ .session_id
+ .take()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
+ self.request.thread_id = Some(session_id.clone());
+
+ log::debug!(
+ "[embed][agent] turn session={session_id} model={:?} routed={} cwd_set={}",
+ self.request.model_override,
+ self.request.inference_url.is_some(),
+ self.request.cwd.is_some(),
+ );
+
+ validate_route(&self.request)?;
+ self.validate_turn_options()?;
+
+ // Never transmit the bearer over a non-TLS channel. The route accepts
+ // an arbitrary base URL, so guard here — before any request is built —
+ // rather than trusting every embedder to only name https endpoints. A
+ // `Route` is refused when it pairs a credential with a non-HTTPS
+ // endpoint; a route without a credential is allowed through (some
+ // embedders run a local, unauthenticated OpenAI-compatible server over
+ // plain http, and there is nothing sensitive on the wire for them).
+ if self
+ .request
+ .api_key
+ .as_deref()
+ .is_some_and(|k| !k.is_empty())
+ {
+ if let Some(endpoint) = self.request.inference_url.as_deref() {
+ if !is_safe_endpoint_for_bearer(endpoint) {
+ return Err(crate::error::CoreError::InsecureRoute {
+ method: AGENT_CHAT,
+ endpoint: sanitize_url_for_display(endpoint),
+ });
+ }
+ }
+ }
+
+ // Filled by the turn itself, before any error is raised, so a failed
+ // turn is still metered. Read back below whether the dispatch returned
+ // a reply or an error.
+ let usage: UsageSink = std::sync::Mutex::new(None);
+ let meter = self.meter.take();
+ let wants_json = self
+ .response_format
+ .as_ref()
+ .is_some_and(crate::complete::ResponseFormat::wants_json);
+ let validator =
+ crate::structured::Validator::new(self.response_format.as_ref()).map_err(|reason| {
+ CoreError::StructuredOutput {
+ method: AGENT_CHAT,
+ failure: crate::structured::StructuredOutputFailure {
+ attempts: 0,
+ reason,
+ finish_reason: None,
+ answered_model: None,
+ usage: None,
+ },
+ }
+ })?;
+ let options = AgentTurnOptions {
+ shape: openhuman_core::agent::tinyagents::response_shape::ResponseShapeScope::new(
+ openhuman_core::agent::tinyagents::response_shape::ResponseShape {
+ response_format: self
+ .response_format
+ .take()
+ .map(crate::complete::ResponseFormat::into_wire),
+ max_output_tokens: self.max_tokens,
++ top_p: self.top_p,
+ validator: wants_json.then(|| std::sync::Arc::new(validator) as std::sync::Arc<dyn openhuman_core::agent::tinyagents::response_shape::ResponseValidator>),
+ structured_retries: self.structured_retries,
+ provider_options: self.provider_options.clone(),
+ require_tool_call: self.require_tool_call,
+ observer: openhuman_core::agent::tinyagents::turn_observer::current_scope(),
+ },
+ ),
+ untrusted_input: self.untrusted_input,
+ };
+ let budget = self.budget.take().map(|budget| crate::budget::ModelBudget {
+ ledger: budget.ledger.child(crate::budget::SpendLimits::default()),
+ call: budget.call,
+ });
+ let dispatch = dispatch(self.target, self.request, self.seed.take(), &usage, options);
+ let dispatch = async {
+ match &budget {
+ Some(budget) => {
+ openhuman_core::agent::tinyagents::budget::with_budget(budget.clone(), dispatch)
+ .await
+ }
+ None => dispatch.await,
+ }
+ };
+
+ let reply = match (self.origin, self.progress) {
+ (Some(origin), Some(sink)) => {
+ openhuman_core::agent::progress_sink::with_progress_sink(
+ sink,
+ openhuman_core::agent::turn_origin::with_origin(origin, dispatch),
+ )
+ .await
+ }
+ (Some(origin), None) => {
+ openhuman_core::agent::turn_origin::with_origin(origin, dispatch).await
+ }
+ (None, Some(sink)) => {
+ openhuman_core::agent::progress_sink::with_progress_sink(sink, dispatch).await
+ }
+ (None, None) => dispatch.await,
+ }
+ .inspect_err(|err| {
+ // Log a redacted failure event so dispatch errors are visible in
+ // host logs without spilling the request, credentials, working
+ // directory, or the error's full payload (CoreError::Domain can
+ // carry arbitrary `data`). Only the session id and the coarse
+ // variant classification are logged; the error itself propagates
+ // to the caller untouched.
+ let tag = match err {
+ crate::error::CoreError::TurnCancelled { .. } => "turn_cancelled",
+ crate::error::CoreError::Cancelled { .. } => "cancelled",
+ crate::error::CoreError::DeadlineExceeded { .. } => "deadline",
+ crate::error::CoreError::StructuredOutput { .. } => "structured_output",
+ crate::error::CoreError::BudgetExceeded { .. } => "budget_exceeded",
+ crate::error::CoreError::Domain { .. } => "domain",
+ crate::error::CoreError::Unavailable { .. } => "unavailable",
+ crate::error::CoreError::Rpc { .. } => "rpc",
+ crate::error::CoreError::Encode { .. } => "encode",
+ crate::error::CoreError::Decode { .. } => "decode",
+ crate::error::CoreError::InsecureRoute { .. } => "insecure_route",
+ crate::error::CoreError::InvalidRoute { .. } => "invalid_route",
+ crate::error::CoreError::AgentRemoved { .. } => "agent_removed",
+ };
+ log::debug!("[embed][agent] turn_failed session={session_id} kind={tag}");
+ });
+
+ // Before the `?`. A turn that errored still spent what it spent, and
+ // this is the only place both the sink and a failing result are in
+ // hand -- `TurnOutcome` below is never built on that path.
+ if let Some(meter) = meter {
+ meter(
+ usage
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone(),
+ );
+ }
+ let reply = reply.map_err(|error| {
+ match budget.as_ref().and_then(|budget| budget.ledger.refusal()) {
+ Some(source) => CoreError::BudgetExceeded {
+ method: AGENT_CHAT,
+ source,
+ },
+ None => error,
+ }
+ });
+ let (reply, report) = reply?;
+ let structured = if wants_json {
+ serde_json::from_str(reply.trim()).ok()
+ } else {
+ None
+ };
+
+ log::debug!(
+ "[embed][agent] turn_completed session={session_id} reply_len={} structured={} \
+ finish_reason={:?}",
+ reply.len(),
+ structured.is_some(),
+ report.as_ref().and_then(|r| r.finish_reason.as_deref())
+ );
+
+ let report = report.unwrap_or_default();
+ Ok(TurnOutcome {
+ reply,
+ session_id,
+ usage: usage
+ .into_inner()
+ .unwrap_or_else(std::sync::PoisonError::into_inner),
+ structured,
+ finish_reason: report.finish_reason,
+ answered_model: report.answered_model,
+ })
+ }
+
+ /// Refuse the per-turn options the target cannot honour, before anything
+ /// is dispatched.
+ fn validate_turn_options(&self) -> Result<(), CoreError> {
+ if self.structured_retries > 3 {
+ return Err(CoreError::StructuredOutput {
+ method: AGENT_CHAT,
+ failure: crate::structured::StructuredOutputFailure {
+ attempts: 0,
+ reason: crate::structured::StructuredFailureReason::RetryLimit,
+ finish_reason: None,
+ answered_model: None,
+ usage: None,
+ },
+ });
+ }
+ let refuse = |message: &str, kind: &str| {
+ Err(CoreError::Domain {
+ method: AGENT_CHAT,
+ message: message.to_owned(),
+ kind: Some(kind.to_owned()),
+ data: None,
+ expected_user_state: true,
+ })
+ };
++ if self
++ .top_p
++ .is_some_and(|p| !p.is_finite() || !(0.0..=1.0).contains(&p))
++ {
++ return refuse(
++ "top_p must be finite and between zero and one",
++ "invalid_model_parameter",
++ );
++ }
+ let host_only = match &self.target {
+ TurnTarget::Agent(agent) => agent.host_only,
+ TurnTarget::Runtime(_) => {
+ if self.response_format.is_some()
+ || self.max_tokens.is_some()
++ || self.top_p.is_some()
+ || self.structured_retries != 0
+ || !self.provider_options.is_null()
+ || self.require_tool_call
+ {
+ return refuse(
+ "response_format and max_tokens need a runtime-owned Agent",
+ "turn_shape_unsupported",
+ );
+ }
+ false
+ }
+ };
+ if self.untrusted_input && !host_only {
+ return refuse(
+ "untrusted_input is only allowed on a HostOnly agent",
+ "untrusted_input_requires_host_only",
+ );
+ }
+ Ok(())
+ }
+}
diff --cc crates/openhuman-embed/tests/stream_cancellation.rs
index 0000000000,f247144d6c..a09af7ad2d
mode 000000,100644..100644
--- a/crates/openhuman-embed/tests/stream_cancellation.rs
+++ b/crates/openhuman-embed/tests/stream_cancellation.rs
@@@ -1,0 -1,211 +1,294 @@@
+ //! Dropping a stream cancels the native turn instead of detaching it forever.
+ mod common;
+ use async_trait::async_trait;
+ use openhuman_embed::providers::{ChatModel, ModelRequest, ModelResponse};
+ use openhuman_embed::{Access, AgentDefinitionSpec, AgentSpec, Provider, Runtime, ToolScopeSpec};
+ use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ };
+
+ struct BlockingFirstCall {
+ first: AtomicBool,
+ started: tokio::sync::mpsc::UnboundedSender<()>,
+ released: tokio::sync::mpsc::UnboundedSender<()>,
+ }
+ struct InFlight(tokio::sync::mpsc::UnboundedSender<()>);
+ impl Drop for InFlight {
+ fn drop(&mut self) {
+ let _ = self.0.send(());
+ }
+ }
+ #[async_trait]
+ impl ChatModel<()> for BlockingFirstCall {
+ async fn invoke(
+ &self,
+ _: &(),
+ _: ModelRequest,
+ ) -> openhuman_embed::providers::Result<ModelResponse> {
+ if self.first.swap(false, Ordering::SeqCst) {
+ let _guard = InFlight(self.released.clone());
+ self.started.send(()).unwrap();
+ std::future::pending::<()>().await;
+ }
+ Ok(ModelResponse::assistant("after cancellation"))
+ }
+ }
+
+ struct FloodModel {
+ buffered: tokio::sync::mpsc::UnboundedSender<()>,
+ released: tokio::sync::mpsc::UnboundedSender<()>,
+ }
+ struct FloodStream {
+ emitted: usize,
+ buffered: tokio::sync::mpsc::UnboundedSender<()>,
+ _guard: InFlight,
+ }
+ impl futures_core::Stream for FloodStream {
+ type Item = openhuman_embed::providers::ModelStreamItem;
+ fn poll_next(
+ mut self: std::pin::Pin<&mut Self>,
+ _: &mut std::task::Context<'_>,
+ ) -> std::task::Poll<Option<Self::Item>> {
+ self.emitted += 1;
+ if self.emitted == 128 {
+ self.buffered.send(()).unwrap();
+ }
+ std::task::Poll::Ready(Some(Self::Item::MessageDelta(
+ openhuman_embed::providers::MessageDelta {
+ text: "delta".into(),
+ reasoning: String::new(),
+ tool_call: None,
+ },
+ )))
+ }
+ }
+ #[async_trait]
+ impl ChatModel<()> for FloodModel {
+ fn profile(&self) -> Option<&openhuman_embed::providers::ModelProfile> {
+ static PROFILE: std::sync::LazyLock<openhuman_embed::providers::ModelProfile> =
+ std::sync::LazyLock::new(|| openhuman_embed::providers::ModelProfile {
+ streaming: true,
+ ..Default::default()
+ });
+ Some(&PROFILE)
+ }
+ async fn invoke(
+ &self,
+ _: &(),
+ _: ModelRequest,
+ ) -> openhuman_embed::providers::Result<ModelResponse> {
+ panic!("the streaming fixture must stream");
+ }
+ async fn stream(
+ &self,
+ _: &(),
+ _: ModelRequest,
+ ) -> openhuman_embed::providers::Result<openhuman_embed::providers::ModelStream> {
+ Ok(openhuman_embed::providers::ModelStream::new(Box::pin(
+ FloodStream {
+ emitted: 0,
+ buffered: self.buffered.clone(),
+ _guard: InFlight(self.released.clone()),
+ },
+ )))
+ }
+ }
+
+ #[test]
+ fn dropping_a_stream_releases_the_inflight_model_and_the_agent_can_run_again() {
+ common::runtime().block_on(async {
+ tokio::spawn(async {
+ let backend = common::stub_backend().await;
+ let (started, mut start_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (released, mut release_rx) = tokio::sync::mpsc::unbounded_channel();
+ let model = Arc::new(BlockingFirstCall {
+ first: AtomicBool::new(true),
+ started,
+ released,
+ });
+ let runtime = Runtime::builder()
+ .config(common::offline_config())
+ .backend_url(backend.uri())
+ .access(Access::readonly())
+ .provider(Provider::custom(model.clone()).model("cancel-model"))
+ .build()
+ .await
+ .unwrap();
+ let agent = runtime
+ .agent(
+ AgentSpec::new("stream-cancel").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply.")
+ .tools(ToolScopeSpec::Named(Vec::new())),
+ ),
+ )
+ .unwrap();
+ let stream = agent.stream("wait forever");
+ let token = stream.cancellation_token();
+ tokio::time::timeout(std::time::Duration::from_secs(10), start_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ drop(stream);
+ assert!(token.is_cancelled());
+ tokio::time::timeout(std::time::Duration::from_secs(10), release_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ let reply =
+ tokio::time::timeout(std::time::Duration::from_secs(10), agent.run("next turn"))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(reply.reply, "after cancellation");
+ model.first.store(true, Ordering::SeqCst);
+ let external = openhuman_embed::CancellationToken::new();
+ let mut stream = agent
+ .turn("cancel externally")
+ .cancellation(external.clone())
+ .stream();
+ tokio::time::timeout(std::time::Duration::from_secs(10), start_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ external.cancel();
+ assert!(stream.cancellation_token().is_cancelled());
+ tokio::time::timeout(std::time::Duration::from_secs(10), release_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ while let Some(event) =
+ tokio::time::timeout(std::time::Duration::from_secs(10), stream.recv())
+ .await
+ .unwrap()
+ {
+ if matches!(event, openhuman_embed::StreamEvent::Finished(_)) {
+ break;
+ }
+ }
+ drop(stream);
++ // Ordinary send shares the same native child scope. Cancelling
++ // its acknowledgement handle must leave the caller's parent usable.
++ model.first.store(true, Ordering::SeqCst);
++ let shared = openhuman_embed::CancellationToken::new();
++ let mut configured = agent
++ .turn("cancel ordinary send")
++ .cancellation(shared.clone());
++ let handle = configured.cancellation_handle();
++ let running = tokio::spawn(configured.send());
++ tokio::time::timeout(std::time::Duration::from_secs(10), start_rx.recv())
++ .await
++ .unwrap()
++ .unwrap();
++ tokio::time::timeout(std::time::Duration::from_secs(10), handle.cancel())
++ .await
++ .expect("ordinary send acknowledges native cleanup");
++ assert!(running.await.unwrap().is_err());
++ tokio::time::timeout(std::time::Duration::from_secs(10), release_rx.recv())
++ .await
++ .unwrap()
++ .unwrap();
++ assert!(
++ !shared.is_cancelled(),
++ "turn-local cancellation must not cancel its parent"
++ );
++ assert_eq!(
++ agent
++ .turn("reuse caller parent")
++ .cancellation(shared)
++ .send()
++ .await
++ .unwrap()
++ .reply,
++ "after cancellation"
++ );
+ let (buffered, mut buffered_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (released, mut released_rx) = tokio::sync::mpsc::unbounded_channel();
+ let flood = runtime
+ .agent(
+ AgentSpec::new("backpressured")
+ .provider(
+ Provider::custom(Arc::new(FloodModel { buffered, released }))
+ .model("flood"),
+ )
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply.")
+ .tools(ToolScopeSpec::Named(Vec::new())),
+ ),
+ )
+ .unwrap();
+ let external = openhuman_embed::CancellationToken::new();
+ let unread = flood
+ .turn("fill the bounded buffers")
+ .cancellation(external.clone())
+ .stream();
+ tokio::time::timeout(std::time::Duration::from_secs(10), buffered_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ external.cancel();
+ // Keep the receiver alive and unread: cancellation must interrupt a
+ // blocked progress send rather than waiting for the consumer to drain.
+ tokio::time::timeout(std::time::Duration::from_secs(10), released_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ drop(unread);
++ // The acknowledgement handle and deadline also release a model
++ // while the stream receiver remains alive and backpressured.
++ let mut configured = flood.turn("cancel with the acknowledgement handle");
++ let handle = configured.cancellation_handle();
++ let mut unread = configured.stream();
++ tokio::time::timeout(std::time::Duration::from_secs(10), buffered_rx.recv())
++ .await
++ .unwrap()
++ .unwrap();
++ tokio::time::timeout(std::time::Duration::from_secs(10), handle.cancel())
++ .await
++ .expect("acknowledged cancellation under backpressure");
++ tokio::time::timeout(std::time::Duration::from_secs(10), released_rx.recv())
++ .await
++ .unwrap()
++ .unwrap();
++ while let Some(event) = unread.recv().await {
++ if let openhuman_embed::StreamEvent::Finished(result) = event {
++ assert!(matches!(
++ result,
++ Err(openhuman_embed::CoreError::TurnCancelled { .. })
++ ));
++ break;
++ }
++ }
++ drop(unread);
++ let mut unread = flood
++ .turn("deadline with an unread stream")
++ .timeout(std::time::Duration::from_secs(2))
++ .stream();
++ tokio::time::timeout(std::time::Duration::from_secs(10), buffered_rx.recv())
++ .await
++ .unwrap()
++ .unwrap();
++ tokio::time::timeout(std::time::Duration::from_secs(10), released_rx.recv())
++ .await
++ .expect("deadline interrupts backpressure")
++ .unwrap();
++ while let Some(event) = unread.recv().await {
++ if let openhuman_embed::StreamEvent::Finished(result) = event {
++ assert!(matches!(
++ result,
++ Err(openhuman_embed::CoreError::DeadlineExceeded { .. })
++ ));
++ break;
++ }
++ }
++ drop(unread);
+ drop(flood);
+ drop(agent);
+ drop(runtime);
+ })
+ .await
+ .expect("scenario runs on tuned worker");
+ });
+ }
diff --cc docs/TEST-COVERAGE-MATRIX.md
index b95182b61a,e99a038c5a..9f9bb7eb64
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@@ -661,15 -661,20 +661,28 @@@ The thread JSONL store moved to `tinyag
| 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |
| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused |
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
+| 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. |
+| 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/turn_usage.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON; successful charged usage reaches outcome/meter, invalid buyer charges stay unknown, root overlays retain child spend and session context. |
+| 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/completion_cost.rs` | ✅ | Ordered fallbacks, per-rung option/cap overrides, bounded case-insensitive length/max_tokens truncation retries, unpinned terminal provider selection, image/options preservation, accumulated buyer-first reported costs with invalid-charge guards, actual answering model and refusal of schema-valid output before successful tool execution |
+| 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
+| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
+| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |
+| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |
+| 16.1.20 | Host turn observer privacy and runtime propagation | RI | `crates/openhuman-embed/tests/turn_observers.rs`, `crates/openhuman-embed/tests/observed_turns.rs` | ✅ | Sanitized terminal failures, opt-in payloads, root runtime scope propagation, real model/tool callbacks and answering-model usage |
+ ### 16.2 Dynamic runtime and agent configuration
+
+ | ID | Feature | Layer | Test path(s) | Status | Notes |
+ | --- | --- | --- | --- | --- | --- |
+ | 16.2.1 | Defaults, templates and typed configuration | RU+RI | `crates/openhuman-embed/src/runtime/defaults_tests.rs`, `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-embed/src/agent/definition_tests.rs`, `crates/openhuman-embed/tests/runtime_configuration.rs` | ✅ | Config, runtime, template, agent and turn overrides preserve unspecified fields; invalid sampling, unknown templates and capability widening are rejected. |
+ | 16.2.2 | Versioned capabilities and runtime weight | RU | `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-rpc/src/host_tests.rs`, `crates/openhuman-embed/examples/capability_report.rs` | ✅ | Reports compiled gates, selected domains/services/modules and effective limits; credentials, endpoints and prompts stay out of JSON. Unavailable modules identify their required feature. |
+ | 16.2.3 | Configured storage and driver feature gates | RU+RI | `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-embed/tests/runtime_configuration.rs`, `crates/openhuman-embed/examples/storage.rs` | ✅ | Configured memory/SQLite storage is installed before boot and supplies session stores; MongoDB requires its Cargo feature and operator configuration. Automated recipes use local storage without contacting MongoDB. |
+ | 16.2.4 | Native providers, role pins and ordered fallback | RU+RI | `crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/examples/custom_provider.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/fallback_tests.rs` | ✅ | Agent-local native providers receive effective sampling parameters; `crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs` pins explicit turn temperature over the stored definition. Explicit role pins override config routing. Generic fallback preserves deferred polling and never switches after visible content. |
+ | 16.2.5 | Live hooks and isolated session stores | RU+RI | `crates/openhuman-core/src/agent/host_overrides_tests.rs`, `crates/openhuman-embed/src/runtime/seams_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/examples/runtime_events.rs` | ✅ | Runtime hooks compose with local hooks, can be replaced or removed between turns, and restore prior registrations on drop; agent-local session stores do not leak transcripts. |
+ | 16.2.6 | Runtime events and approval callbacks | RU+RI | `crates/openhuman-embed/src/events_tests.rs`, `crates/openhuman-embed/src/turn_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/tests/approval_lifecycle.rs`, `crates/openhuman-embed/examples/approvals.rs` | ✅ | Ordered, bounded, content-free events identify agents and individual calls, retain approval origins, and report lag. Callback approve/deny and subscription-drop cancellation exercise real shell markers. Removed-agent handles are invalidated and IDs stay reserved until teardown completes, including cancelled removals. |
+ | 16.2.7 | Streaming and cancellation under backpressure | RU+RI | `crates/openhuman-embed/tests/stream_cancellation.rs`, `crates/openhuman-embed/examples/streaming.rs` | ✅ | Progress precedes the final result; dropping the stream or cancelling its supplied token releases native model work even with an unread bounded receiver. |
+ | 16.2.8 | Executable recipes and generated documentation | scripts+RI | `scripts/__tests__/run-embed-examples.test.mjs`, `scripts/__tests__/generate-embed-docs.test.mjs`, `scripts/run-embed-examples.mjs` | ✅ | Every recipe runs with loopback fixtures and an explicit output contract. Snippets, cookbook metadata, builder signatures and capability output regenerate from source; drift, hidden rustdoc lines and broken links fail checks. |
+
## Summary
| Status | Count |
diff --cc scripts/__tests__/embed-contract-boundary.test.mjs
index 0000000000,03ce72a5d8..4f50f5403b
mode 000000,100644..100644
--- a/scripts/__tests__/embed-contract-boundary.test.mjs
+++ b/scripts/__tests__/embed-contract-boundary.test.mjs
@@@ -1,0 -1,48 +1,54 @@@
+ import test from 'node:test';
+ import assert from 'node:assert/strict';
+ import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+ import { tmpdir } from 'node:os';
+ import { dirname, resolve } from 'node:path';
+ import { spawnSync } from 'node:child_process';
+
+ function check(files) {
+ const root = mkdtempSync(resolve(tmpdir(), 'embed-contract-boundary-'));
+ try {
+ mkdirSync(resolve(root, 'scripts/ci'), { recursive: true });
- mkdirSync(resolve(root, 'vendor/tinyagents/crates'), { recursive: true });
++ mkdirSync(resolve(root, 'scripts/lib'), { recursive: true });
++ const bridge = 'vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/bridge.rs';
++ mkdirSync(dirname(resolve(root, bridge)), { recursive: true });
++ writeFileSync(resolve(root, bridge), 'struct ChatMessage { pub(crate) role: String, pub(crate) content: String, }\n');
+ copyFileSync(new URL('../ci/check-agent-runtime-boundary.mjs', import.meta.url), resolve(root, 'scripts/ci/check-agent-runtime-boundary.mjs'));
++ for (const helper of ['runtime-boundary-types.mjs', 'agent-sdk-contracts.mjs']) {
++ copyFileSync(new URL(`../lib/${helper}`, import.meta.url), resolve(root, `scripts/lib/${helper}`));
++ }
+ writeFileSync(resolve(root, 'scripts/ci/agent-runtime-boundary-baseline.json'), '[]\n');
+ for (const [path, source] of Object.entries(files)) {
+ mkdirSync(dirname(resolve(root, path)), { recursive: true });
+ writeFileSync(resolve(root, path), source);
+ }
+ const result = spawnSync(process.execPath, [resolve(root, 'scripts/ci/check-agent-runtime-boundary.mjs')], { encoding: 'utf8' });
+ assert.equal(result.error, undefined);
+ return { status: result.status, output: result.stdout + result.stderr };
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }
+
+ const contracts = {
+ 'crates/openhuman-core/src/agent/host_overrides.rs': 'pub use tinyagents_harness::cancel::CancellationToken;\n',
+ 'crates/openhuman-embed/src/config.rs': 'pub use tinytools::{\n DefaultEffect, Patterns, RuleEffect, Surface, ToolMatcher, ToolRule, ToolRules,\n};\n',
+ 'crates/openhuman-embed/src/lib.rs': 'pub mod providers {\n pub use tinyinference_llm::message::MessageDelta;\n pub use tinyinference_llm::model::{\n ChatModel, DeferredHandle, DeferredStatus, ModelProfile, ModelRequest, ModelResponse,\n ModelStream, ModelStreamItem, ModelStreamMetadata,\n };\n pub use tinyinference_llm::{Error, Result};\n}\n',
+ };
+
+ test('Embed exposes the native provider and policy contracts without copying their owners', () => {
+ const result = check(contracts);
+ assert.equal(result.status, 0, result.output);
+ });
+
+ test('the public contract allowance does not admit another export in an approved file', () => {
+ const result = check({ ...contracts, 'crates/openhuman-embed/src/lib.rs': contracts['crates/openhuman-embed/src/lib.rs'].replace('ModelStreamMetadata,', 'ModelStreamMetadata, UnreviewedType,') });
+ assert.equal(result.status, 1, result.output);
+ assert.match(result.output, /openhuman-upstream-reexport/);
+ });
+
+ test('the same native contract remains forbidden outside its owning adapter', () => {
+ const result = check({ 'crates/openhuman-core/src/other/mod.rs': contracts['crates/openhuman-core/src/agent/host_overrides.rs'] });
+ assert.equal(result.status, 1, result.output);
+ assert.match(result.output, /openhuman-upstream-reexport/);
+ });
diff --cc scripts/__tests__/root-rust-targets.test.mjs
index 0000000000,0000000000..2e0e8862c5
new file mode 100644
--- /dev/null
+++ b/scripts/__tests__/root-rust-targets.test.mjs
@@@ -1,0 -1,0 +1,23 @@@
++import { test } from "node:test";
++import assert from "node:assert/strict";
++import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
++import { tmpdir } from "node:os";
++import { join } from "node:path";
++import { rootRustTargetNames } from "../lib/root-rust-targets.mjs";
++
++test("absent root target directories are empty and existing targets remain inventoried", () => {
++ const fixture = mkdtempSync(join(tmpdir(), "root-rust-targets-"));
++ try {
++ const directory = join(fixture, "examples");
++ assert.deepEqual([...rootRustTargetNames(directory)], []);
++ mkdirSync(directory);
++ writeFileSync(join(directory, "review.rs"), "");
++ writeFileSync(join(directory, "README.md"), "");
++ assert.deepEqual([...rootRustTargetNames(directory)], ["review"]);
++ assert.throws(() => rootRustTargetNames(join(directory, "review.rs")), {
++ code: "ENOTDIR",
++ });
++ } finally {
++ rmSync(fixture, { recursive: true, force: true });
++ }
++});
diff --cc scripts/ci/check-agent-runtime-boundary.mjs
index 63c99687b0,dc8eb952de..7e881bfe1d
--- a/scripts/ci/check-agent-runtime-boundary.mjs
+++ b/scripts/ci/check-agent-runtime-boundary.mjs
@@@ -16,6 -15,36 +16,51 @@@ const tinyagentsRoot = resolve(repoRoot
const writeBaseline = process.argv.includes("--write-baseline");
const noBaseline = process.argv.includes("--no-baseline");
+ // Embed's injection API exposes the original provider/policy contracts (#7306)
+ // so callers need only the facade dependency. These are exact declarations,
+ // not alternative implementations or compatibility layers. Keep the allowance
+ // bounded by both file and the complete statement, including grouped members.
-const embedContractExports = new Map([
- ["crates/openhuman-core/src/agent/host_overrides.rs", [
- "pub use tinyagents_harness::cancel::CancellationToken;",
- ]],
- ["crates/openhuman-embed/src/config.rs", [
- "pub use tinytools::{DefaultEffect, Patterns, RuleEffect, Surface, ToolMatcher, ToolRule, ToolRules};",
- ]],
- ["crates/openhuman-embed/src/lib.rs", [
- "pub use tinyinference_llm::message::MessageDelta;",
- "pub use tinyinference_llm::model::{ChatModel, DeferredHandle, DeferredStatus, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem, ModelStreamMetadata};",
- "pub use tinyinference_llm::{Error, Result};",
- ]],
-].map(([path, statements]) => [path, new Set(statements.map(normalizeExport))]));
++const embedContractExports = new Map(
++ [
++ [
++ "crates/openhuman-core/src/agent/host_overrides.rs",
++ ["pub use tinyagents_harness::cancel::CancellationToken;"],
++ ],
++ [
++ "crates/openhuman-embed/src/config.rs",
++ [
++ "pub use tinytools::{DefaultEffect, Patterns, RuleEffect, Surface, ToolMatcher, ToolRule, ToolRules};",
++ ],
++ ],
++ [
++ "crates/openhuman-embed/src/lib.rs",
++ [
++ "pub use tinyinference_llm::message::MessageDelta;",
++ "pub use tinyinference_llm::model::{ChatModel, DeferredHandle, DeferredStatus, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem, ModelStreamMetadata};",
++ "pub use tinyinference_llm::{Error, Result};",
++ ],
++ ],
++ ].map(([path, statements]) => [
++ path,
++ new Set(statements.map(normalizeExport)),
++ ]),
++);
+
+ function normalizeExport(statement) {
+ return statement.replace(/\s+/g, "").replace(/,}/g, "}");
+ }
+
+ function isEmbedContractExport(path, lines, index) {
+ const allowed = embedContractExports.get(path);
+ if (!allowed) return false;
- const remaining = lines.slice(index).map(({ text }) => text).join("\n");
++ const remaining = lines
++ .slice(index)
++ .map(({ text }) => text)
++ .join("\n");
+ const end = remaining.indexOf(";");
+ return end >= 0 && allowed.has(normalizeExport(remaining.slice(0, end + 1)));
+ }
+
// Product types need not start with `OpenHuman`, so this is an explicit,
// reviewed inventory rather than a naming convention.
const openhumanDomainTypes = new Set([
@@@ -362,14 -391,6 +407,23 @@@ function isBehaviorFreeForwarder(source
}
function assertSelfTests() {
+ const sdkPath = "crates/openhuman-core/src/agent/tinyagents/budget.rs";
- const sdkStatement = "pub use tinyinference_llm::model::budget::{Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits};";
++ const sdkStatement =
++ "pub use tinyinference_llm::model::budget::{Budget, BudgetExceeded, BudgetSnapshot, CallBudget, Spend, SpendLimits};";
+ if (
+ sanctionedSdkReexportLines(sdkPath, sdkStatement).size !== 1 ||
- sanctionedSdkReexportLines(sdkPath, sdkStatement.replace("SpendLimits", "SpendLimits, BudgetedModel")).size !== 0 ||
- sanctionedSdkReexportLines(sdkPath, "pub use tinyagents_harness::runtime::AgentHarness;").size !== 0
++ sanctionedSdkReexportLines(
++ sdkPath,
++ sdkStatement.replace("SpendLimits", "SpendLimits, BudgetedModel"),
++ ).size !== 0 ||
++ sanctionedSdkReexportLines(
++ sdkPath,
++ "pub use tinyagents_harness::runtime::AgentHarness;",
++ ).size !== 0
+ )
- throw new Error("agent-runtime boundary self-test: host SDK inventory leaked runtime contracts");
++ throw new Error(
++ "agent-runtime boundary self-test: host SDK inventory leaked runtime contracts",
++ );
const fixture = [
"[dependencies.openhuman]",
'version = "1"',
@@@ -477,9 -498,8 +531,10 @@@ for (const path of await filesUnder
(path) => path.endsWith(".rs") && /\/src\//.test(path),
)) {
const rel = relative(repoRoot, path);
- const lines = codeLines(await readFile(path, "utf8"));
+ const source = await readFile(path, "utf8");
+ const sdkContractLines = sanctionedSdkReexportLines(rel, rustCode(source));
- for (const { line, text, raw } of codeLines(source)) {
++ const lines = codeLines(source);
+ for (const [index, { line, text, raw }] of lines.entries()) {
if (!text.trim()) continue;
const compact = compactRustPath(text);
if (/\btinyagents_harness::tool_calling\b/.test(compact))
@@@ -528,7 -548,8 +583,9 @@@
if (
/\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(
text,
- ) && !sdkContractLines.has(line)
- )
- && !isEmbedContractExport(rel, lines, index)
++ ) &&
++ !sdkContractLines.has(line) &&
++ !isEmbedContractExport(rel, lines, index)
)
add("openhuman-upstream-reexport", path, line, raw);
}
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 5caeba4b71,5caeba4b71..745ad99fcf
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -2,6 -2,6 +2,7 @@@
import fs from "node:fs";
import path from "node:path";
++import { rootRustTargetNames } from "../lib/root-rust-targets.mjs";
const ROOT = "crates/openhuman-core/src";
const CRATES_ROOT = "crates";
@@@ -159,12 -159,12 +160,7 @@@ for (const [directory, table] of
["tests", "test"],
["examples", "example"],
]) {
-- const files = new Set(
-- fs
-- .readdirSync(directory)
-- .filter((name) => name.endsWith(".rs"))
-- .map((name) => name.slice(0, -3)),
-- );
++ const files = rootRustTargetNames(directory);
const declared = declaredTargets(table);
for (const name of files) {
if (!declared.has(name))
diff --cc scripts/lib/root-rust-targets.mjs
index 0000000000,0000000000..317213f924
new file mode 100644
--- /dev/null
+++ b/scripts/lib/root-rust-targets.mjs
@@@ -1,0 -1,0 +1,17 @@@
++import { readdirSync } from "node:fs";
++
++// Root targets are explicit; an empty directory may be absent in a checkout.
++export function rootRustTargetNames(directory) {
++ let entries;
++ try {
++ entries = readdirSync(directory);
++ } catch (error) {
++ if (error.code !== "ENOENT") throw error;
++ entries = [];
++ }
++ return new Set(
++ entries
++ .filter((name) => name.endsWith(".rs"))
++ .map((name) => name.slice(0, -3)),
++ );
++}
diff --cc vendor/tinyagents
index a9b93b7d88,87ec7f3845..554a20ac62
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit a9b93b7d88fad75b057b35bd591c6835db0decb6
-Subproject commit 87ec7f3845f98040500d37a0ecaaf84785e5ea3e
++Subproject commit 554a20ac6230d07c32163a2085a712fab3c1a8b2