Skip to content

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

feat(embed): add dynamic runtime APIs and verified documentation

Steven Enamakel606d255ef481
diff --git a/.github/ci-paths-filter.yml b/.github/ci-paths-filter.yml
index 5da78fa8e7..44e4f24a08 100644
--- a/.github/ci-paths-filter.yml
+++ b/.github/ci-paths-filter.yml
@@ -44,6 +44,20 @@ docs:
- 'scripts/generate-architecture-docs.mjs'
- 'scripts/__tests__/generate-architecture-docs.test.mjs'
- 'gitbooks/developing/architecture/frontend.md'
+ - 'gitbooks/developing/embed/**'
+ - 'gitbooks/developing/embedding.md'
+ - 'gitbooks/SUMMARY.md'
+ - 'docs/gitbooks/en/developing/embed/**'
+ - 'docs/gitbooks/en/developing/embedding.md'
+ - 'docs/gitbooks/en/SUMMARY.md'
+ - 'crates/openhuman-embed/**'
+ - 'scripts/generate-embed-docs.mjs'
+ - 'scripts/run-embed-examples.mjs'
+ - 'scripts/__tests__/generate-embed-docs.test.mjs'
+ - 'scripts/__tests__/run-embed-examples.test.mjs'
+ - 'llms.txt'
+ - 'llms-full.txt'
+ - 'EMBED.md'
- 'package.json'
rust-core:
- '.github/workflows/ci-*.yml'
diff --git a/.github/workflows/test-reusable.yml b/.github/workflows/test-reusable.yml
index 93e9ba9015..ab899bfeeb 100644
--- a/.github/workflows/test-reusable.yml
+++ b/.github/workflows/test-reusable.yml
@@ -244,6 +244,9 @@ jobs:
# The core binary and developer bins live in the CLI crate.
bash scripts/ci-cancel-aware.sh cargo test -p openhuman-cli --bins --features "${CLI_FEATURES}"
bash scripts/ci-cancel-aware.sh cargo test -p openhuman --doc --features "${FEATURES}"
+ bash scripts/ci-cancel-aware.sh cargo test -p openhuman-embed --doc --features "${FEATURES}"
+ RUSTDOCFLAGS="-D warnings" bash scripts/ci-cancel-aware.sh cargo doc -p openhuman-embed --no-deps --features "${FEATURES}"
+ node scripts/run-embed-examples.mjs
while IFS= read -r target; do
[ -n "${target}" ] || continue
diff --git a/AGENTS.md b/AGENTS.md
index e2ae8e2346..ab6e5c5f7d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -405,6 +405,12 @@ Additional rules:
## Tool, harness, and runtime boundaries
+Embed public API documentation: [Embedding](gitbooks/developing/embed/README.md),
+[concepts](gitbooks/developing/embed/concepts/README.md), and the source-generated
+[builder setters](gitbooks/developing/embed/builder-setters.md). Snippets come from
+compiled examples; run `pnpm docs:generate` and `pnpm docs:check` after changing them.
+
+
`tinyagents` owns tool-call dialects, parsing, catalog rendering, transcript
replay, session identity, and the agent loop. `tinytools` owns the shared
`Tool` trait and tool types. OpenHuman owns execution policy, approvals,
diff --git a/Cargo.lock b/Cargo.lock
index aa91c7be64..d1956cd9d7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4668,6 +4668,7 @@ dependencies = [
"chrono",
"dirs 6.0.0",
"env_logger",
+ "futures-core",
"log",
"openhuman",
"reqwest",
@@ -4684,6 +4685,7 @@ dependencies = [
"tinymemory-tools",
"tinytools",
"tokio",
+ "tokio-stream",
"tracing-subscriber",
"url",
"uuid",
diff --git a/EMBED.md b/EMBED.md
new file mode 100644
index 0000000000..80c8176624
--- /dev/null
+++ b/EMBED.md
@@ -0,0 +1,54 @@
+# OpenHuman Embed
+
+> Embed OpenHuman runtimes and independently configured agents in Rust applications.
+
+- [Embedding OpenHuman](gitbooks/developing/embed/README.md): `openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+- [Embedding API reference](gitbooks/developing/embed/api-reference.md): Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+- [Embedding architecture](gitbooks/developing/embed/architecture.md): Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+- [Concepts](gitbooks/developing/embed/concepts/README.md): Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+- [Access and approvals](gitbooks/developing/embed/concepts/access-approvals.md): `Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+- [Agents](gitbooks/developing/embed/concepts/agents.md): Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+- [Channels](gitbooks/developing/embed/concepts/channels.md): `Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+- [Completer](gitbooks/developing/embed/concepts/completer.md): Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+- [Cron](gitbooks/developing/embed/concepts/cron.md): The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+- [Errors](gitbooks/developing/embed/concepts/errors.md): Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+- [Hooks and seams](gitbooks/developing/embed/concepts/hooks-seams.md): Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+- [MCP](gitbooks/developing/embed/concepts/mcp.md): MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+- [Memory](gitbooks/developing/embed/concepts/memory.md): `Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+- [Observability](gitbooks/developing/embed/concepts/observability.md): Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+- [Profiles and SaaS](gitbooks/developing/embed/concepts/profiles-saas.md): Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+- [Providers](gitbooks/developing/embed/concepts/providers.md): A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+- [Runtime defaults](gitbooks/developing/embed/concepts/runtime-defaults.md): The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+- [Runtime](gitbooks/developing/embed/concepts/runtime.md): A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+- [Skills](gitbooks/developing/embed/concepts/skills.md): A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+- [Testing](gitbooks/developing/embed/concepts/testing.md): The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+- [Tools](gitbooks/developing/embed/concepts/tools.md): An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+- [Turns and sessions](gitbooks/developing/embed/concepts/turns-sessions.md): `Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+- [Embedding FAQ](gitbooks/developing/embed/faq.md): An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See runtime and profiles.
+- [Embedding guides](gitbooks/developing/embed/guides/README.md): Choose the guide that matches your host:
+- [CLI chatbot](gitbooks/developing/embed/guides/cli-chatbot.md): Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+- [Deploy a server](gitbooks/developing/embed/guides/deploy-server.md): Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+- [Lean and headless hosts](gitbooks/developing/embed/guides/lean-headless.md): `RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+- [Test with a mock backend](gitbooks/developing/embed/guides/mock-backend-testing.md): Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+- [Multiple agents](gitbooks/developing/embed/guides/multi-agent.md): A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+- [SaaS with multiple tenants](gitbooks/developing/embed/guides/saas-multi-tenant.md): Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+- [Installation](gitbooks/developing/embed/installation.md): `openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+- [Embedding integrations](gitbooks/developing/embed/integrations/README.md): An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+- [Channels](gitbooks/developing/embed/integrations/channels.md): Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+- [Composio](gitbooks/developing/embed/integrations/composio.md): Composio calls use the host backend transport. Install that transport before booting a managed runtime; see TinyHumans managed inference. An explicit inference provider route supplies model inference, not the connector transport.
+- [Local and custom models](gitbooks/developing/embed/integrations/local-models.md): For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The OpenAI-compatible example controls can point a live example at that local server.
+- [MCP servers](gitbooks/developing/embed/integrations/mcp.md): Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+- [OpenAI-compatible providers and BYOK](gitbooks/developing/embed/integrations/openai-compatible.md): Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+- [Storage drivers](gitbooks/developing/embed/integrations/storage-drivers.md): Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+- [TinyHumans managed inference](gitbooks/developing/embed/integrations/tinyhumans-managed.md): Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+- [Quickstart](gitbooks/developing/embed/quickstart.md): Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+- [Embedding troubleshooting](gitbooks/developing/embed/troubleshooting.md): Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+- [OpenHuman Embed](crates/openhuman-embed/README.md): A typed Rust facade for running the OpenHuman core inside your application: one Runtime per process, with independently configured Agents.
+- [Embedding OpenHuman](gitbooks/developing/embedding.md): The embedding documentation now lives in the Embedding section.
+- [Cookbook](gitbooks/developing/embed/cookbook.md): Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+- [Compiled feature matrix](gitbooks/developing/embed/capability-matrix.md): This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+- [RuntimeBuilder setters](gitbooks/developing/embed/builder-setters.md): Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+- [API index](gitbooks/developing/embed/api-index.md): Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. Canonical facade source.
+- [Embed examples](crates/openhuman-embed/examples/README.md): Cookbook
+
+See the generated [API index](gitbooks/developing/embed/api-index.md) for build capabilities.
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock
index 25dd7ce3b7..c4391f867a 100644
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@ -4580,6 +4580,7 @@ dependencies = [
"anyhow",
"async-trait",
"chrono",
+ "futures-core",
"log",
"openhuman",
"sentry",
@@ -4595,6 +4596,7 @@ dependencies = [
"tinymemory-tools",
"tinytools",
"tokio",
+ "tokio-stream",
"url",
"uuid",
]
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml
index 5e7df5e55b..93fca6cfdd 100644
--- a/crates/openhuman-cli/Cargo.toml
+++ b/crates/openhuman-cli/Cargo.toml
@@ -266,13 +266,7 @@ path = "../../tests/observability_wallet_expected_e2e.rs"
name = "skills_mcp_registry_live"
path = "../../tests/skills_mcp_registry_live.rs"
-[[example]]
-name = "embed_headless"
-path = "../../examples/embed_headless.rs"
-[[example]]
-name = "embed_kernel"
-path = "../../examples/embed_kernel.rs"
[dependencies]
# The only openhuman crate the binary depends on. Every gate below forwards to
diff --git a/crates/openhuman-cli/README.md b/crates/openhuman-cli/README.md
index 84be2686bb..9e87f9bf9d 100644
--- a/crates/openhuman-cli/README.md
+++ b/crates/openhuman-cli/README.md
@@ -135,7 +135,7 @@ transport from `main.rs`.
| [`src/main.rs`](src/main.rs) | The `openhuman-core` binary entry point described above. |
| [`src/bin/`](src/bin/README.md) | Ops binaries: `test-mcp-stub`, `openhuman-fleet`. The benchmark binaries live in [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks) (`profile/`, #6944). |
| `../../tests/*.rs` | 27 `[[test]]` targets, including the two aggregators. See [`tests/README.md`](../../tests/README.md). |
-| `../../examples/*.rs` | 2 `[[example]]` targets on the `openhuman_embed::Runtime` API: `embed_headless` and `embed_kernel`. |
+| [`../openhuman-embed/examples/`](../openhuman-embed/examples/README.md) | Offline embedding examples, built and run as `openhuman-embed` targets. |
| `../../build.rs` | Shared build script: generates the `raw_coverage_all` and `in_process_all` module lists and exports `OPENHUMAN_REPOSITORY_ROOT`. |
## Targets
diff --git a/crates/openhuman-core/src/agent/hooks.rs b/crates/openhuman-core/src/agent/hooks.rs
index e855e4d776..e0d1b809b3 100644
--- a/crates/openhuman-core/src/agent/hooks.rs
+++ b/crates/openhuman-core/src/agent/hooks.rs
@@ -36,10 +36,14 @@ pub fn replace_embedder_post_turn_hook(name: &str, hook: Option<Arc<dyn PostTurn
/// Snapshot hooks supplied by the embedding host.
pub fn embedder_post_turn_hooks() -> Vec<Arc<dyn PostTurnHook>> {
- EMBEDDER_POST_TURN_HOOKS
+ let mut hooks = EMBEDDER_POST_TURN_HOOKS
.lock()
.expect("embedder post-turn hooks poisoned")
- .clone()
+ .clone();
+ if let Some(local) = crate::core::runtime::CoreContext::current_host_overrides() {
+ hooks.extend(local.post_turn_hooks());
+ }
+ hooks
}
/// Snapshot of a completed agent turn, passed to every registered hook.
@@ -266,10 +270,14 @@ pub fn replace_embedder_tool_hook(name: &str, hook: Option<Arc<dyn ToolHook>>) {
/// Snapshot tool hooks supplied by the embedding host.
pub fn embedder_tool_hooks() -> Vec<Arc<dyn ToolHook>> {
- EMBEDDER_TOOL_HOOKS
+ let mut hooks = EMBEDDER_TOOL_HOOKS
.lock()
.expect("embedder tool hooks poisoned")
- .clone()
+ .clone();
+ if let Some(local) = crate::core::runtime::CoreContext::current_host_overrides() {
+ hooks.extend(local.tool_hooks());
+ }
+ hooks
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/agent/host_overrides.rs b/crates/openhuman-core/src/agent/host_overrides.rs
new file mode 100644
index 0000000000..f87001346a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/host_overrides.rs
@@ -0,0 +1,125 @@
+//! Live, agent-owned host adapters inherited by derived turn contexts.
+//!
+//! These are OpenHuman's injection points into its session builder. The model
+//! contract remains TinyInference's, and the session-store contract remains
+//! TinyAgents'. Credentials and the event bus are deliberately not overridden.
+
+use std::collections::BTreeMap;
+use std::sync::{Arc, RwLock};
+
+use crate::agent::hooks::{PostTurnHook, ToolHook};
+use tinyinference_llm::model::ChatModel;
+
+pub use tinyagents_harness::cancel::CancellationToken;
+
+/// Runtime or agent host adapters, shared by every context derived from it.
+#[derive(Default)]
+pub struct HostOverrides {
+ /// Parent runtime adapters; local hook registration never edits this parent.
+ pub parent: Option<Arc<HostOverrides>>,
+ post_turn_hooks: RwLock<BTreeMap<String, Arc<dyn PostTurnHook>>>,
+ tool_hooks: RwLock<BTreeMap<String, Arc<dyn ToolHook>>>,
+ /// Native inference used by this agent instead of config-routed inference.
+ pub model: Option<Arc<dyn ChatModel<()>>>,
+ /// Role-specific native models; absent roles use `model` or config routing.
+ pub role_models: BTreeMap<String, Arc<dyn ChatModel<()>>>,
+ /// The agent's durable session store, ahead of the runtime's store.
+ pub session_store: Option<Arc<dyn crate::agent::session_store::SessionStoreProvider>>,
+}
+
+impl std::fmt::Debug for HostOverrides {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("HostOverrides")
+ .field("has_model", &self.model.is_some())
+ .field("model_roles", &self.role_models.keys().collect::<Vec<_>>())
+ .field("has_session_store", &self.session_store.is_some())
+ .finish_non_exhaustive()
+ }
+}
+
+impl HostOverrides {
+ /// Add or replace an agent-local post-turn hook by name; `None` removes it.
+ pub fn post_turn_hook(&self, name: &str, hook: Option<Arc<dyn PostTurnHook>>) {
+ let mut hooks = self
+ .post_turn_hooks
+ .write()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ hooks.remove(name);
+ if let Some(hook) = hook {
+ hooks.insert(name.to_owned(), hook);
+ }
+ }
+
+ /// Add or replace an agent-local tool hook by name; `None` removes it.
+ pub fn tool_hook(&self, name: &str, hook: Option<Arc<dyn ToolHook>>) {
+ let mut hooks = self
+ .tool_hooks
+ .write()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ hooks.remove(name);
+ if let Some(hook) = hook {
+ hooks.insert(name.to_owned(), hook);
+ }
+ }
+
+ /// Snapshot the agent-local post-turn hooks for a new session.
+ pub fn post_turn_hooks(&self) -> Vec<Arc<dyn PostTurnHook>> {
+ let mut hooks = self
+ .parent
+ .as_ref()
+ .map(|parent| parent.post_turn_hooks())
+ .unwrap_or_default();
+ hooks.extend(
+ self.post_turn_hooks
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .values()
+ .cloned(),
+ );
+ hooks
+ }
+
+ /// Snapshot the agent-local tool hooks for a new turn.
+ pub fn tool_hooks(&self) -> Vec<Arc<dyn ToolHook>> {
+ let mut hooks = self
+ .parent
+ .as_ref()
+ .map(|parent| parent.tool_hooks())
+ .unwrap_or_default();
+ hooks.extend(
+ self.tool_hooks
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .values()
+ .cloned(),
+ );
+ hooks
+ }
+
+ /// Resolve a native model for a workload role without touching credentials.
+ pub fn model_for(&self, role: &str) -> Option<Arc<dyn ChatModel<()>>> {
+ self.role_models
+ .get(role)
+ .cloned()
+ .or_else(|| self.model.clone())
+ }
+}
+
+tokio::task_local! { static TURN_CANCELLATION: CancellationToken; }
+
+/// Run a turn with a caller-owned cancellation token, shared with child runs.
+pub async fn with_cancellation<F: std::future::Future>(
+ token: CancellationToken,
+ future: F,
+) -> F::Output {
+ TURN_CANCELLATION.scope(token, future).await
+}
+
+/// The caller's token, or a fresh token for entrypoints without one.
+pub fn current_cancellation() -> CancellationToken {
+ TURN_CANCELLATION.try_with(Clone::clone).unwrap_or_default()
+}
+
+#[cfg(test)]
+#[path = "host_overrides_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/host_overrides_tests.rs b/crates/openhuman-core/src/agent/host_overrides_tests.rs
new file mode 100644
index 0000000000..43b2b667ef
--- /dev/null
+++ b/crates/openhuman-core/src/agent/host_overrides_tests.rs
@@ -0,0 +1,35 @@
+use super::*;
+use async_trait::async_trait;
+
+struct Hook;
+#[async_trait]
+impl PostTurnHook for Hook {
+ fn name(&self) -> &str {
+ "local"
+ }
+ async fn on_turn_complete(&self, _: &crate::agent::hooks::TurnContext) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+#[test]
+fn local_hooks_do_not_escape_their_agent_and_can_be_removed() {
+ let a = HostOverrides::default();
+ let b = HostOverrides::default();
+ a.post_turn_hook("local", Some(Arc::new(Hook)));
+ assert_eq!(a.post_turn_hooks().len(), 1);
+ assert!(b.post_turn_hooks().is_empty());
+ a.post_turn_hook("local", None);
+ assert!(a.post_turn_hooks().is_empty());
+}
+
+#[tokio::test]
+async fn caller_cancellation_is_shared_and_does_not_escape_its_scope() {
+ let token = CancellationToken::new();
+ with_cancellation(token.clone(), async {
+ token.cancel();
+ assert!(current_cancellation().is_cancelled());
+ })
+ .await;
+ assert!(!current_cancellation().is_cancelled());
+}
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 32ad053a51..83f8b18e8f 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -33,6 +33,7 @@ pub mod hooks;
/// Host-registered agents the core's own drivers (cron, workflow nodes) can
/// resolve by id, with their definition, host tools and context.
pub mod host_agents;
+pub mod host_overrides;
pub mod host_runtime;
pub mod library;
pub(crate) mod message_convert;
diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rs
index 24cc424e7c..3926e45165 100644
--- a/crates/openhuman-core/src/agent/session_store/mod.rs
+++ b/crates/openhuman-core/src/agent/session_store/mod.rs
@@ -91,12 +91,19 @@ pub fn restore(provider: Option<Arc<dyn SessionStoreProvider>>) {
/// one, if any.
#[must_use]
pub fn installed() -> Option<Arc<dyn SessionStoreProvider>> {
- SCOPED.try_with(Arc::clone).ok().or_else(|| {
- PROVIDER
- .read()
- .unwrap_or_else(PoisonError::into_inner)
- .clone()
- })
+ SCOPED
+ .try_with(Arc::clone)
+ .ok()
+ .or_else(|| {
+ crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.session_store.clone())
+ })
+ .or_else(|| {
+ PROVIDER
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clone()
+ })
}
/// Whether a host session store is in effect.
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index fb577d6aa5..58af670e8a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -400,7 +400,7 @@ impl OpenHumanRunContext {
subagent_usage: Arc::new(Mutex::new(Vec::new())),
parent_subagent_usage: None,
resolved_route: Arc::new(Mutex::new(None)),
- cancellation: tinyagents_harness::cancel::CancellationToken::new(),
+ cancellation: crate::agent::host_overrides::current_cancellation(),
thread_id: None,
root_run_id: None,
workspace: None,
diff --git a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs b/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
index bf150571a9..4dc771292f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
@@ -131,7 +131,7 @@ const REAPER_BOOT_CHILD_ENV: &str = "OPENHUMAN_TEST_REAPER_BOOT_CHILD";
/// The child half of `a_build_only_runtime_is_swept_before_it_can_be_invoked`:
/// build a runtime with no transport and no services — the shape
-/// `examples/embed_headless.rs` documents — against the `OPENHUMAN_WORKSPACE`
+/// `crates/openhuman-embed/examples/lean_headless.rs` documents — against the `OPENHUMAN_WORKSPACE`
/// the parent exported, and check the build resolved that workspace. The
/// parent reads the sweep's effect out of the store afterwards.
async fn boot_child() {
diff --git a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
index 9c866b58e4..7e04d4cadd 100644
--- a/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/response_shape.rs
@@ -30,6 +30,8 @@ pub struct ResponseShape {
pub response_format: Option<ResponseFormat>,
/// Replaces the turn's per-call output cap.
pub max_output_tokens: Option<u32>,
+ /// Nucleus sampling probability applied to every call of this turn.
+ pub top_p: Option<f64>,
}
/// What the turn's final model call reported.
@@ -119,6 +121,9 @@ impl Middleware<(), OpenHumanRunContext> for ResponseShapeMiddleware {
if let Some(cap) = shape.max_output_tokens {
request.max_tokens = Some(cap);
}
+ if let Some(top_p) = shape.top_p {
+ request.top_p = Some(top_p);
+ }
Ok(())
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
index 538825807e..d3bd235b7d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
@@ -215,6 +215,11 @@ fn build_turn_models_crate(
// The primary honours an explicit provider-string override when the producer's
// effective provider differs from `provider_for_role(role)` (triage #1257).
let build_primary = |m: &str| -> anyhow::Result<TurnChatModel> {
+ if let Some(chat) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.model_for(role))
+ {
+ return Ok(chat);
+ }
let managed = primary_override
.map(|provider| {
let provider = provider.trim();
@@ -281,6 +286,24 @@ fn build_turn_models_crate(
continue;
}
let tier_role = factory::role_for_model_tier(tier);
+ if let Some(custom) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| {
+ local
+ .role_models
+ .get(tier)
+ .or_else(|| local.role_models.get(tier_role))
+ .cloned()
+ })
+ {
+ routes.push((
+ tier.to_string(),
+ crate::agent::attachments::provider::wrap_injected(
+ custom,
+ Arc::new(config.clone()),
+ ),
+ ));
+ continue;
+ }
let route = if factory::resolves_to_managed_backend(tier_role, config) {
factory::make_openhuman_backend_model_for_thread(
tier_role, config, tier, true, thread_id,
@@ -322,7 +345,15 @@ fn build_turn_models_crate(
}
// The summarizer is a distinct adapter instance (own empty error slot).
- let summarizer = build_primary(model)?;
+ let summarizer = match crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.role_models.get("summarization").cloned())
+ {
+ Some(custom) => crate::agent::attachments::provider::wrap_injected(
+ custom,
+ Arc::new(config.clone()),
+ ),
+ None => build_primary(model)?,
+ };
anyhow::Ok((primary, routes, summarizer))
})?;
@@ -466,6 +497,13 @@ impl TurnModelSource {
let Some(source) = self.crate_native.as_ref() else {
return crate::inference::model_context::context_window_for_model(model);
};
+ if let Some(custom) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.model_for(&source.role))
+ {
+ return custom
+ .profile()
+ .and_then(|profile| profile.max_input_tokens);
+ }
let provider_string = source.primary_override.clone().unwrap_or_else(|| {
crate::inference::provider::provider_for_role(&source.role, &source.config)
});
@@ -487,6 +525,38 @@ impl TurnModelSource {
context_window: Option<u64>,
thread_id: Option<&str>,
) -> anyhow::Result<TurnModels> {
+ if let Some(source) = &self.crate_native {
+ if let Some(local) = crate::core::runtime::CoreContext::current_host_overrides() {
+ if let Some(custom) = local.model_for(&source.role) {
+ let mut models = Self::from_model(custom)
+ .with_attachment_config(source.config.clone())
+ .build(model, temperature, context_window, thread_id)?;
+ for &tier in routes::WORKLOAD_ROUTE_TIERS {
+ let role = crate::inference::provider::factory::role_for_model_tier(tier);
+ if let Some(custom) = local
+ .role_models
+ .get(tier)
+ .or_else(|| local.role_models.get(role))
+ {
+ models.routes.push((
+ tier.to_owned(),
+ crate::agent::attachments::provider::wrap_injected(
+ custom.clone(),
+ source.config.clone(),
+ ),
+ ));
+ }
+ }
+ if let Some(custom) = local.role_models.get("summarization") {
+ models.summarizer = crate::agent::attachments::provider::wrap_injected(
+ custom.clone(),
+ source.config.clone(),
+ );
+ }
+ return Ok(models);
+ }
+ }
+ }
if let Some(direct) = &self.direct_model {
let mut profile = direct.profile().cloned().unwrap_or_default();
if let Some(window) = context_window.filter(|window| *window > 0) {
@@ -594,6 +664,18 @@ impl TurnModelSource {
});
}
if let Some(cn) = &self.crate_native {
+ if let Some(custom) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| {
+ local
+ .model_for("summarization")
+ .or_else(|| local.model_for(&cn.role))
+ })
+ {
+ return Ok(crate::agent::attachments::provider::wrap_injected(
+ custom,
+ cn.config.clone(),
+ ));
+ }
let managed = cn
.primary_override
.as_deref()
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
index e294ba4129..2f1d41d5f8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
@@ -9,6 +9,39 @@ use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};
use super::{TurnModelResolver, TurnModels};
use crate::agent::tinyagents::TurnModelSource;
+#[tokio::test]
+async fn role_pins_apply_when_the_primary_uses_config_routing() {
+ use crate::agent::host_overrides::HostOverrides;
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ let config = crate::config::Config::default();
+ let mut overrides = HostOverrides::default();
+ overrides
+ .role_models
+ .insert("coding".into(), Arc::new(NamedModel("pinned coding")));
+ overrides.role_models.insert(
+ "summarization".into(),
+ Arc::new(NamedModel("pinned summary")),
+ );
+ let root = CoreContext::for_test(DomainSet::full(), None);
+ let context = root.derive_with(
+ ContextOverlay::new(config.clone(), DomainSet::full(), Default::default())
+ .host_overrides(Arc::new(overrides)),
+ );
+ CoreContext::scope(context, async {
+ let models = TurnModelSource::new_crate_native("chat", Arc::new(config))
+ .build("hint:chat", 0.0, None, None)
+ .expect("config-routed models");
+ let coding = models
+ .routes
+ .iter()
+ .find(|(tier, _)| tier == "hint:coding")
+ .expect("pinned role route");
+ assert_eq!(name_of(&coding.1).await, "pinned coding");
+ assert_eq!(name_of(&models.summarizer).await, "pinned summary");
+ })
+ .await;
+}
+
/// A stub that answers with its own name so a test can tell which model the
/// resolver handed back.
struct NamedModel(&'static str);
diff --git a/crates/openhuman-core/src/core/bus.rs b/crates/openhuman-core/src/core/bus.rs
index efba0df950..9bf21bc78b 100644
--- a/crates/openhuman-core/src/core/bus.rs
+++ b/crates/openhuman-core/src/core/bus.rs
@@ -36,8 +36,10 @@
//! keep working, and an early-startup publish does not panic.
use tinybus::events::EventBusConfig;
+// Curated adapter types for hosts subscribing without a second bus dependency.
use tinybus::global::OnceBus;
use tinybus::version::{InterfaceVersion, PeerManifest, Version};
+pub use tinybus::{EventHandler, SubscriptionHandle};
use crate::core::events::DomainEvent;
diff --git a/crates/openhuman-core/src/core/runtime/README.md b/crates/openhuman-core/src/core/runtime/README.md
index 83ec9b473f..53bbdba4d1 100644
--- a/crates/openhuman-core/src/core/runtime/README.md
+++ b/crates/openhuman-core/src/core/runtime/README.md
@@ -61,9 +61,9 @@ registry filters on.
| Preset | Shape |
| --- | --- |
| `DomainSet::full()` | Every family on: today's default, byte-identical to registration with no runtime narrowing. |
-| `DomainSet::harness()` | `agent` + `memory` + `threads` + `config` + `security` only; every gate family and `platform` off. The embeddable agent core (`examples/embed_headless.rs`). |
+| `DomainSet::harness()` | `agent` + `memory` + `threads` + `config` + `security` only; every gate family and `platform` off. The embeddable agent core; see the [lean headless example](../../../../openhuman-embed/examples/lean_headless.rs). |
| `DomainSet::embedded()` | The harness families plus `flows` (boot reconciliation keys off `ctx.domains().flows`), `skills`, `channels` (`channel.web_chat` is tagged `Channels` and is how an embedded host drives chat turns), `inference`, `integrations`, `automation`, `runtimes`, and `platform`. `mcp`/`web3`/`voice`/`media`/`desktop`/`hosted`/`modules` stay off: an embedded host supplies its own routing and presentation. |
-| `DomainSet::kernel()` | The floor: `threads` + `config` + `security` only. Distinct from `none()`: this is "opt a subsystem back in from nothing," so `agent` and `memory` (the two largest, most replaceable subsystems) are deliberately off. See `examples/embed_kernel.rs`. |
+| `DomainSet::kernel()` | The floor: `threads` + `config` + `security` only. Distinct from `none()`: this is "opt a subsystem back in from nothing," so `agent` and `memory` (the two largest, most replaceable subsystems) are deliberately off. See the [capability report example](../../../../openhuman-embed/examples/capability_report.rs) for inspecting runtime composition. |
| `DomainSet::none()` | Every family off. |
## `TokenSource`: how the RPC bearer is seeded
diff --git a/crates/openhuman-core/src/core/runtime/context_agent.rs b/crates/openhuman-core/src/core/runtime/context_agent.rs
index 8ab6c016eb..874817c6e1 100644
--- a/crates/openhuman-core/src/core/runtime/context_agent.rs
+++ b/crates/openhuman-core/src/core/runtime/context_agent.rs
@@ -3,8 +3,9 @@
use super::*;
-#[derive(Clone, Default)]
+#[derive(Clone)]
pub(super) struct AgentParts {
+ host_overrides: Option<Arc<crate::agent::host_overrides::HostOverrides>>,
/// `None` for booted contexts, which read the process live policy.
policy: Option<Arc<crate::security::SecurityPolicy>>,
approvals_disabled: bool,
@@ -14,11 +15,29 @@ pub(super) struct AgentParts {
state: Arc<super::super::agent_scope::AgentScopedState>,
}
+impl Default for AgentParts {
+ fn default() -> Self {
+ Self {
+ host_overrides: Some(Arc::new(
+ crate::agent::host_overrides::HostOverrides::default(),
+ )),
+ policy: None,
+ approvals_disabled: false,
+ definitions: None,
+ state: Default::default(),
+ }
+ }
+}
+
impl AgentParts {
/// The parts of a context derived from one owning `self` with `overlay`.
/// An overlay that names an agent gets state slots of its own.
pub(super) fn derive(&self, overlay: &mut ContextOverlay) -> Self {
Self {
+ host_overrides: overlay
+ .host_overrides
+ .take()
+ .or_else(|| self.host_overrides.clone()),
policy: overlay.agent_policy.take().or_else(|| self.policy.clone()),
approvals_disabled: overlay.approvals_disabled || self.approvals_disabled,
definitions: overlay
@@ -35,6 +54,16 @@ impl AgentParts {
}
impl CoreContext {
+ /// Agent-local host adapters inherited by this derived context.
+ pub fn host_overrides(&self) -> Option<Arc<crate::agent::host_overrides::HostOverrides>> {
+ self.agent.host_overrides.clone()
+ }
+
+ /// Host adapters of the ambient agent, without changing process globals.
+ pub fn current_host_overrides() -> Option<Arc<crate::agent::host_overrides::HostOverrides>> {
+ Self::current().and_then(|ctx| ctx.host_overrides())
+ }
+
/// The security policy of the agent this context was derived for.
pub fn agent_policy(&self) -> Option<Arc<crate::security::SecurityPolicy>> {
self.agent.policy.clone()
diff --git a/crates/openhuman-core/src/core/runtime/context_overlay.rs b/crates/openhuman-core/src/core/runtime/context_overlay.rs
index bfe186a1c0..b760baef11 100644
--- a/crates/openhuman-core/src/core/runtime/context_overlay.rs
+++ b/crates/openhuman-core/src/core/runtime/context_overlay.rs
@@ -15,6 +15,8 @@ use std::sync::Arc;
/// context it derives from.
#[derive(Debug, Clone)]
pub struct ContextOverlay {
+ /// Host adapters local to this agent; absent inherits the parent.
+ pub host_overrides: Option<Arc<crate::agent::host_overrides::HostOverrides>>,
/// The config every handler dispatched under the derived context reads
/// through `config::ops::load_config_with_timeout()`. Keep `config_path`
/// equal to the parent's: credentials, auth profiles and the keyring file
@@ -54,6 +56,7 @@ impl ContextOverlay {
tool_groups: crate::tools::toolpacks::ToolGroups,
) -> Self {
Self {
+ host_overrides: None,
config,
domains,
tool_groups,
@@ -66,6 +69,15 @@ impl ContextOverlay {
}
}
+ /// Bind agent-local hooks, native inference and session storage.
+ pub fn host_overrides(
+ mut self,
+ overrides: Arc<crate::agent::host_overrides::HostOverrides>,
+ ) -> Self {
+ self.host_overrides = Some(overrides);
+ self
+ }
+
/// Hide the operator's `~/.openhuman/skills` / `~/.agents/skills` from
/// skill discovery under the derived context.
pub fn without_user_skill_roots(mut self) -> Self {
diff --git a/crates/openhuman-core/src/core/runtime/domain_set.rs b/crates/openhuman-core/src/core/runtime/domain_set.rs
index a8be6bac43..375fd1dcb3 100644
--- a/crates/openhuman-core/src/core/runtime/domain_set.rs
+++ b/crates/openhuman-core/src/core/runtime/domain_set.rs
@@ -10,7 +10,7 @@ use crate::core::all::DomainGroup;
/// the common hosts:
/// [`DomainSet::full`] (every family — today's behavior, the default),
/// [`DomainSet::harness`] (agent + memory + threads + config + security only —
-/// the embeddable agent core used by `examples/embed_headless.rs`), and
+/// the embeddable agent core used by `crates/openhuman-embed/examples/lean_headless.rs`), and
/// [`DomainSet::none`] (all domain families disabled; transport built-ins and
/// always-on core infrastructure still run).
///
@@ -102,7 +102,7 @@ impl DomainSet {
/// The embeddable agent core: agent + memory + threads + config + security.
/// Every gate family AND `platform` are off. Used by
- /// `examples/embed_headless.rs`.
+ /// `crates/openhuman-embed/examples/lean_headless.rs`.
pub fn harness() -> Self {
Self {
agent: true,
@@ -183,7 +183,7 @@ impl DomainSet {
/// are OFF on purpose: they are the two largest subsystems and the ones an
/// alternative driver would replace, so a host that wants them says so.
///
- /// See `examples/embed_kernel.rs`.
+ /// See `crates/openhuman-embed/examples/capability_report.rs`.
pub fn kernel() -> Self {
Self {
agent: false,
diff --git a/crates/openhuman-core/src/core/runtime/features.rs b/crates/openhuman-core/src/core/runtime/features.rs
new file mode 100644
index 0000000000..3422c51ca3
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/features.rs
@@ -0,0 +1,34 @@
+//! Compile-time capabilities of the core, independent of facade feature forwarding.
+
+/// Every Cargo feature gate and whether this core artifact includes it.
+pub fn compiled_features() -> std::collections::BTreeMap<String, bool> {
+ [
+ ("storage-sqlite", cfg!(feature = "storage-sqlite")),
+ ("storage-mongodb", cfg!(feature = "storage-mongodb")),
+ ("storage-file", cfg!(feature = "storage-file")),
+ ("default", cfg!(feature = "default")),
+ ("http-server", cfg!(feature = "http-server")),
+ ("inference", cfg!(feature = "inference")),
+ ("documents", cfg!(feature = "documents")),
+ ("hosting", cfg!(feature = "hosting")),
+ ("tinymemes", cfg!(feature = "tinymemes")),
+ ("modules", cfg!(feature = "modules")),
+ ("voice", cfg!(feature = "voice")),
+ ("web3", cfg!(feature = "web3")),
+ ("runtime-node", cfg!(feature = "runtime-node")),
+ ("media", cfg!(feature = "media")),
+ ("flows", cfg!(feature = "flows")),
+ ("skills", cfg!(feature = "skills")),
+ ("mcp", cfg!(feature = "mcp")),
+ ("crash-reporting", cfg!(feature = "crash-reporting")),
+ ("channels", cfg!(feature = "channels")),
+ ("whatsapp-web", cfg!(feature = "whatsapp-web")),
+ ("e2e-test-support", cfg!(feature = "e2e-test-support")),
+ ("rss-bench", cfg!(feature = "rss-bench")),
+ ("file-logging", cfg!(feature = "file-logging")),
+ ("scheduler-gate", cfg!(feature = "scheduler-gate")),
+ ]
+ .into_iter()
+ .map(|(name, enabled)| (name.to_owned(), enabled))
+ .collect()
+}
diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rs
index 45e471a611..e001bcd9ac 100644
--- a/crates/openhuman-core/src/core/runtime/mod.rs
+++ b/crates/openhuman-core/src/core/runtime/mod.rs
@@ -49,6 +49,8 @@ mod bootstrap;
pub mod builder;
pub mod context;
pub mod domain_set;
+mod features;
+pub use features::compiled_features;
pub mod mode;
pub mod saas;
pub mod services;
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
index badc1321be..2a92ebaa89 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs
@@ -204,10 +204,27 @@ impl std::fmt::Debug for AgentChatTarget<'_> {
}
}
+// Definitions are reusable snapshots. A turn override belongs only to the
+// definition passed to this call's factory, which otherwise wins over Config.
+fn definition_for_turn(
+ definition: &crate::agent::harness::definition::AgentDefinition,
+ temperature: Option<f64>,
+) -> std::borrow::Cow<'_, crate::agent::harness::definition::AgentDefinition> {
+ match temperature {
+ Some(temperature) => {
+ let mut scoped = definition.clone();
+ scoped.temperature = temperature;
+ std::borrow::Cow::Owned(scoped)
+ }
+ None => std::borrow::Cow::Borrowed(definition),
+ }
+}
+
fn build_turn_agent(
config: &Config,
target: &AgentChatTarget<'_>,
session_id: Option<&str>,
+ temperature: Option<f64>,
) -> Result<OpenHumanSessionHost, String> {
match target {
AgentChatTarget::Orchestrator => OpenHumanSessionHost::from_config(config),
@@ -220,15 +237,24 @@ fn build_turn_agent(
host,
host_only: true,
..
- } => OpenHumanSessionHost::from_config_host_only(config, definition, *host, session_id),
+ } => {
+ let definition = definition_for_turn(definition, temperature);
+ OpenHumanSessionHost::from_config_host_only(config, &definition, *host, session_id)
+ }
AgentChatTarget::Definition {
definition, host, ..
- } => match host {
- Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
- config, definition, host, session_id,
- ),
- None => OpenHumanSessionHost::from_config_with_definition(config, definition),
- },
+ } => {
+ let definition = definition_for_turn(definition, temperature);
+ match host {
+ Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
+ config,
+ &definition,
+ host,
+ session_id,
+ ),
+ None => OpenHumanSessionHost::from_config_with_definition(config, &definition),
+ }
+ }
}
.map_err(|e| e.to_string())
}
@@ -367,14 +393,14 @@ pub async fn agent_chat_reply_for(
"[inference] agent_chat rooting turn tools at cwd={}",
root.display()
);
- let mut agent = build_turn_agent(&scoped, &target, turn_session_id)?;
+ let mut agent = build_turn_agent(&scoped, &target, turn_session_id, temperature)?;
// Also thread it as the turn's workspace descriptor so acting tools
// that read `ToolExecutionContext::workspace` (shell) resolve their
// default cwd here, and so spawned sub-agents inherit the same root.
agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(root.clone())));
agent
}
- None => build_turn_agent(config, &target, turn_session_id)?,
+ None => build_turn_agent(config, &target, turn_session_id, temperature)?,
};
// Thread-correct resume. `OpenHumanSessionHost::turn` would otherwise auto-load the
// newest transcript for the agent *name*, which is another thread's
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs
index a85d1dbb5f..816bbfddab 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs
@@ -68,3 +68,17 @@ fn the_outcome_keeps_its_historical_shape() {
assert_eq!(outcome.value, "hi");
assert_eq!(outcome.logs, vec!["agent chat completed".to_string()]);
}
+
+#[test]
+fn explicit_turn_temperature_overrides_the_definition_without_mutating_it() {
+ let mut definition = crate::agent::harness::builtin_definitions::test_main_def();
+ definition.temperature = 0.6;
+ let effective = definition_for_turn(&definition, Some(0.9));
+ assert_eq!(effective.temperature, 0.9);
+ assert_eq!(definition.temperature, 0.6);
+ assert!(matches!(
+ definition_for_turn(&definition, None),
+ std::borrow::Cow::Borrowed(_)
+ ));
+ assert_eq!(definition_for_turn(&definition, None).temperature, 0.6);
+}
diff --git a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs
index 51f6975f9f..b8e87bf5e8 100644
--- a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs
@@ -37,6 +37,17 @@ pub(super) fn create_chat_model_with_model_id_inner(
role: &str,
config: &Config,
) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String)> {
+ if let Some(model) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.model_for(role))
+ {
+ return Ok((
+ model,
+ config
+ .default_model
+ .clone()
+ .unwrap_or_else(|| "host-model".into()),
+ ));
+ }
#[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
if let Some(model) = test_provider_override::current() {
return Ok((model, "mock-model".to_string()));
diff --git a/crates/openhuman-core/src/inference/provider/factory/turn_model.rs b/crates/openhuman-core/src/inference/provider/factory/turn_model.rs
index 7bc5509647..89b88b4aea 100644
--- a/crates/openhuman-core/src/inference/provider/factory/turn_model.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/turn_model.rs
@@ -77,6 +77,11 @@ pub(super) fn create_turn_chat_model_with_native_tools_and_route_inner(
model: &str,
native_tool_calling: bool,
) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
+ if let Some(chat) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.model_for(role))
+ {
+ return Ok((chat, "host".into(), model.to_owned()));
+ }
#[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
if let Some(chat) = test_provider_override::current() {
let provider = chat
@@ -215,6 +220,11 @@ pub(crate) fn create_turn_chat_model_from_string_with_native_tools_and_route(
temperature: f64,
native_tool_calling: bool,
) -> anyhow::Result<(Arc<dyn ChatModel<()>>, String, String)> {
+ if let Some(chat) = crate::core::runtime::CoreContext::current_host_overrides()
+ .and_then(|local| local.model_for(role))
+ {
+ return Ok((chat, "host".into(), model.to_owned()));
+ }
#[cfg(any(test, feature = "e2e-test-support", feature = "rss-bench"))]
if let Some(chat) = test_provider_override::current() {
let provider = chat
diff --git a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
index 81740bc9c2..1237479f56 100644
--- a/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
+++ b/crates/openhuman-core/src/security/keyring/encrypted_file_backend.rs
@@ -593,7 +593,7 @@ impl EncryptedFileBackend {
key,
legacy_path,
destination_lock,
- |path, lock| file_store::sync_parent_dir(path, lock),
+ file_store::sync_parent_dir,
)
}
diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rs
index dac45cb3c8..5f4b65ca2a 100644
--- a/crates/openhuman-core/src/storage/mod.rs
+++ b/crates/openhuman-core/src/storage/mod.rs
@@ -31,8 +31,8 @@ use std::future::Future;
use std::sync::{Arc, LazyLock, OnceLock, RwLock};
pub use tinystoragedrivers::{
- Blocking, DocumentStore, DocumentStoreExt, MemoryStorage, Scope, ScopedStorage, StorageBackend,
- StorageConfig as StorageUrl, StorageError,
+ Blocking, CollectionSpec, DocumentStore, DocumentStoreExt, MemoryStorage, Precondition, Scope,
+ ScopedStorage, StorageBackend, StorageConfig as StorageUrl, StorageError,
};
use crate::config::schema::storage::redact_url;
diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml
index d93d0e3b99..ffc3ca2e72 100644
--- a/crates/openhuman-embed/Cargo.toml
+++ b/crates/openhuman-embed/Cargo.toml
@@ -41,6 +41,8 @@ scheduler-gate = ["openhuman-core/scheduler-gate"]
e2e-test-support = ["openhuman-core/e2e-test-support"]
[dependencies]
+futures-core = "0.3"
+tokio-stream = { version = "0.1", features = ["sync"] }
async-trait = "0.1"
openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false }
anyhow = "1"
@@ -96,3 +98,23 @@ wiremock = "0.6"
sentry = { version = "0.47.0", default-features = false, features = ["test"] }
tokio = { version = "1", features = ["full", "test-util"] }
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
+
+[[example]]
+name = "mcp"
+required-features = ["mcp"]
+
+[[example]]
+name = "skills"
+required-features = ["skills"]
+
+[[example]]
+name = "telegram"
+required-features = ["channels"]
+
+[[example]]
+name = "storage"
+required-features = ["storage-sqlite"]
diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.md
index c342b18199..7e6c1979f1 100644
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@ -1,749 +1,9 @@
-# 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.
-## How it works
+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).
-The crate has two entry points, and they sit at different heights over the
-core.
+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.
-```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.
-
-## Using it
-
-Add the dependency with the default contributor features, or pick a narrow
-host build:
-
-```toml
-[dependencies]
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed" }
-
-# or
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed", default-features = false, features = ["inference", "mcp"] }
-```
-
-### 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.
+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.
diff --git a/crates/openhuman-embed/examples/README.md b/crates/openhuman-embed/examples/README.md
index d5e8ade1bf..c24342786b 100644
--- a/crates/openhuman-embed/examples/README.md
+++ b/crates/openhuman-embed/examples/README.md
@@ -1,80 +1,28 @@
-# examples
-
-Runnable programs that use `openhuman-embed` the way a host product would.
-Cargo discovers them, so they run with `cargo run -p openhuman-embed
---example <name>`. Each builds its tokio runtime by hand with
-`AGENT_WORKER_STACK_BYTES` and `MAX_BLOCKING_THREADS` instead of
-`#[tokio::main]`, because a turn overflows tokio's default worker stack. Set
-`RUST_LOG=debug` to see the `[embed]` log lines around each turn.
-
-## run_turn
-
-One turn on a `Harness`, read-only, with live progress printed to stderr.
-By default it builds an ephemeral workspace, points the agent's `action_dir`
-at the current directory, and sends inference to the endpoint you name:
-
-```bash
-OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-OPENHUMAN_EXAMPLE_API_KEY=sk-... \
-OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
- cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"
-```
-
-`OPENHUMAN_EXAMPLE_MODEL` defaults to `gpt-4o-mini`. With
-`OPENHUMAN_EXAMPLE_INHERIT=1` it uses `Workspace::Inherit` and
-`Provider::inherit()` instead: the machine's real OpenHuman workspace and
-whatever inference it is configured with.
-
-```bash
-OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."
-```
-
-## two_agents
-
-A read-only reviewer and a full-access fixer on one `Runtime`, each with its
-own access tier, working directory and model. Run it BYOK with the same three
-variables as `run_turn`, or on managed inference with a TinyHumans API key:
-
-```bash
-OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_... \
- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-```
-
-The example uses the plain `openhuman_embed::Runtime::builder()`, which
-installs no backend transport. Without one the core has no default backend
-URL, so on the managed path also set `OPENHUMAN_EXAMPLE_BACKEND_URL` to the
-backend's inference base, or managed calls answer `BACKEND_UNAVAILABLE:`. A
-real host would build with `openhuman_tinyhumans::RuntimeBuilder` instead.
-
-## profiles
-
-Two users, alice and bob, each with their own SaaS profile in one process,
-both chatting on a thread they call `t1`. Each reads `t1` back and sees only
-their own messages: a thread id is unique per profile. It builds a
-`ProfileRuntime` on a temporary root and runs fully offline, against a local
-mock that answers `echo: <your message>` through a stub backend transport:
-
-```bash
-cargo run -p openhuman-embed --example profiles
-```
-
-Building a `ProfileRuntime` locks the process into SaaS mode, so this example
-cannot share a process with the other two.
-
-## Optional settings
-
-| Variable | Effect |
-| --- | --- |
-| `OPENHUMAN_EXAMPLE_BACKEND_URL` | Points the core's non-inference backend calls at your own backend. |
-| `OPENHUMAN_EXAMPLE_SKILLS_DIR` | Skill bundles to copy in (the reviewer only, in `two_agents`). Ignored without the `skills` feature. |
-
-`run_turn` and `two_agents` make real network calls to the endpoint you configure; `profiles` makes none. The
-tests in [`../tests/`](../tests/README.md) cover the same paths against mocks.
-The repository-root [`examples/embed_headless.rs`](../../../examples/embed_headless.rs) and [`examples/embed_kernel.rs`](../../../examples/embed_kernel.rs)
-use `CoreBuilder` directly, without this crate; run them with
-`cargo run -p openhuman-cli --example embed_headless`.
-
-## Further reading
-
-- [`gitbooks/developing/embedding.md`](../../../gitbooks/developing/embedding.md): embedding the core in another product.
-- [`crates/openhuman-embed/README.md`](../README.md): the openhuman-embed crate README.
+# Embed examples
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+[Cookbook](../../../gitbooks/developing/embed/cookbook.md)
+
+- [Polling and callback approvals with cancellation](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs): Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request. (offline with loopback stubs; no live path.)
+- [Stable capability metadata before and after boot](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs): Stable capability metadata before and after boot. (offline with loopback stubs; no live path.)
+- [Stateless completion without booting an agent runtime](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs): Stateless completion without booting an agent runtime. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Run and inspect an agent cron job](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs): Run and inspect an agent cron job. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Native custom providers, fallback and workload role pins](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs): Inject deterministic native models and prove fallback and role selection without inference HTTP. (offline; no live inference path.)
+- [Runtime defaults and per-agent overrides](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs): Runtime defaults and per-agent overrides. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [A per-agent post-turn hook observes completed turns](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs): A per-agent post-turn hook observes completed turns. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Host tools and HostOnly keep the advertised tool catalog exact](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs): Host tools and HostOnly keep the advertised tool catalog exact. (offline with loopback stubs; no live path.)
+- [Lean runtime without background services](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs): Lean runtime without background services. (offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.)
+- [Connect an actual MCP protocol stub over loopback](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs): Connect an actual MCP protocol stub over loopback. (offline with loopback stubs; no live path.; feature: mcp)
+- [Tenant scoped memory facade with an in-memory engine](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs): Tenant scoped memory facade with an in-memory engine. (offline with loopback stubs; no live path.)
+- [SaaS profiles isolate conversation history](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs): SaaS profiles isolate conversation history. (offline with loopback stubs; no live path.)
+- [Hello agent: a prompt in and a reply out](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs): Hello agent: a prompt in and a reply out. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Runtime lifecycle events and live hook registration](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs): Observe ordered metadata and add/remove a runtime-wide hook while agents keep running. (offline with a loopback provider; no live path.)
+- [Access tiers and explicit sandbox choices](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs): Access tiers and explicit sandbox choices. (offline with loopback stubs; no live path.)
+- [Embed an agent behind a host-owned HTTP server](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs): Embed an agent behind a host-owned HTTP server. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Copy a skill bundle into its agent workspace](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs): Copy a skill bundle into its agent workspace. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.; feature: skills)
+- [SQLite writes and MongoDB configuration through Embed](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs): Open a real local SQLite backend and describe a MongoDB deployment without connecting. (offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb.; feature: storage-sqlite)
+- [Streaming progress with a draining receiver](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs): Streaming progress with a draining receiver. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Structured output parsed and checked against the request](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/structured_output.rs): Structured output parsed and checked against the request. (offline with loopback stubs; no live path.)
+- [Telegram channel answered by its bound agent via a local Bot API](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs): Telegram channel answered by its bound agent via a local Bot API. (offline with loopback stubs; no live path.; feature: channels)
+- [Two agents with independent prompts and working folders](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs): Two agents with independent prompts and working folders. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
diff --git a/crates/openhuman-embed/examples/approvals.rs b/crates/openhuman-embed/examples/approvals.rs
new file mode 100644
index 0000000000..6e21560539
--- /dev/null
+++ b/crates/openhuman-embed/examples/approvals.rs
@@ -0,0 +1,257 @@
+//! Title: Polling and callback approvals with cancellation
+//! Summary: Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let mut config = support::offline_config();
+ config.autonomy.enabled = true;
+ let runtime = Runtime::builder()
+ .config(config)
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: approvals
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("approved-marker");
+ let write_provider = support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", marker.display())}).to_string(),
+ )],
+ "approved",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("supervised")
+ .provider(support::route(&write_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: "demo".into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.path().display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(
+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ ),
+ )?;
+ let pending_agent = agent.clone();
+ let turn = tokio::spawn(async move { pending_agent.run("Create a marker").await });
+ let pending = support::eventually("approval", || {
+ agent.approvals().pending().ok()?.into_iter().next()
+ })
+ .await;
+ assert!(!marker.exists(), "execution waits for the host decision");
+ assert_eq!(pending.agent_id.as_deref(), Some("supervised"));
+ agent.approvals().decide(
+ &pending.request_id,
+ openhuman_embed::ApprovalDecision::ApproveOnce,
+ )?;
+ assert_eq!(turn.await??.reply, "approved");
+ assert!(marker.exists());
+ assert!(agent.approvals().pending()?.is_empty());
+ println!("parked write executed only after approval");
+ // ANCHOR_END: approvals
+ // ANCHOR: approval_callback
+ let denied_marker = scratch.path().join("denied-marker");
+ let denied_provider = support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", denied_marker.display())})
+ .to_string(),
+ )],
+ "denied",
+ )
+ .await;
+ let decisions = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let callback_agent = runtime.agent(
+ AgentSpec::new("callback")
+ .provider(support::route(&denied_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: "callback".into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.path().display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(
+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ )
+ .approval_handler(std::sync::Arc::new(DenyWrites(decisions.clone()))),
+ )?;
+ let outcome = tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ callback_agent.run("Create a marker"),
+ )
+ .await??;
+ assert_eq!(outcome.reply, "denied");
+ assert_eq!(decisions.load(std::sync::atomic::Ordering::SeqCst), 1);
+ assert!(!denied_marker.exists());
+ // Callback allowance uses the same gate and executes the real write.
+ let allowed_marker = scratch.path().join("callback-allowed");
+ let allowed_provider = writing_provider(&allowed_marker, "callback approved").await;
+ let allowed_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let allowed = runtime.agent(
+ supervised_spec("allowed", scratch.path(), &allowed_provider)
+ .approval_handler(std::sync::Arc::new(AllowWrites(allowed_calls.clone()))),
+ )?;
+ assert_eq!(
+ tokio::time::timeout(
+ std::time::Duration::from_secs(10),
+ allowed.run("Create a marker")
+ )
+ .await??
+ .reply,
+ "callback approved"
+ );
+ assert!(allowed_marker.exists());
+ assert_eq!(allowed_calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+
+ // A temporary callback may be removed while its decision is in flight.
+ // Channels prove both startup and future destruction without timing sleeps.
+ let cancelled_marker = scratch.path().join("callback-cancelled");
+ let cancelled_provider = writing_provider(&cancelled_marker, "cancelled decision").await;
+ let cancel_agent = runtime.agent(supervised_spec(
+ "cancel-callback",
+ scratch.path(),
+ &cancelled_provider,
+ ))?;
+ let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (dropped_tx, mut dropped_rx) = tokio::sync::mpsc::unbounded_channel();
+ let subscription = cancel_agent.handle_approvals(std::sync::Arc::new(HangingDecision {
+ started: started_tx,
+ dropped: dropped_tx,
+ }));
+ let turning = cancel_agent.clone();
+ let cancelled_turn = tokio::spawn(async move { turning.run("Create a marker").await });
+ let request_id = tokio::time::timeout(std::time::Duration::from_secs(10), started_rx.recv())
+ .await?
+ .expect("callback started");
+ drop(subscription);
+ tokio::time::timeout(std::time::Duration::from_secs(10), dropped_rx.recv())
+ .await?
+ .expect("decision future dropped");
+ assert!(!cancelled_marker.exists());
+ assert!(cancel_agent
+ .approvals()
+ .pending()?
+ .iter()
+ .any(|request| request.request_id == request_id));
+ cancel_agent
+ .approvals()
+ .decide(&request_id, openhuman_embed::ApprovalDecision::Deny)?;
+ assert_eq!(cancelled_turn.await??.reply, "cancelled decision");
+ assert!(!cancelled_marker.exists());
+ // ANCHOR_END: approval_callback
+ support::passed("approvals");
+ Ok(())
+}
+
+struct DenyWrites(std::sync::Arc<std::sync::atomic::AtomicUsize>);
+#[async_trait::async_trait]
+impl openhuman_embed::ApprovalHandler for DenyWrites {
+ async fn decide(
+ &self,
+ request: &openhuman_embed::PendingApproval,
+ ) -> openhuman_embed::ApprovalDecision {
+ assert_eq!(request.agent_id.as_deref(), Some("callback"));
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ openhuman_embed::ApprovalDecision::Deny
+ }
+}
+
+async fn writing_provider(marker: &std::path::Path, reply: &str) -> wiremock::MockServer {
+ support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command":format!("touch {}", marker.display())}).to_string(),
+ )],
+ reply,
+ )
+ .await
+}
+fn supervised_spec(
+ id: &str,
+ scratch: &std::path::Path,
+ provider: &wiremock::MockServer,
+) -> AgentSpec {
+ AgentSpec::new(id)
+ .provider(support::route(provider, "fixture"))
+ .action_dir(scratch)
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: id.into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])))
+}
+struct AllowWrites(std::sync::Arc<std::sync::atomic::AtomicUsize>);
+#[async_trait::async_trait]
+impl openhuman_embed::ApprovalHandler for AllowWrites {
+ async fn decide(
+ &self,
+ request: &openhuman_embed::PendingApproval,
+ ) -> openhuman_embed::ApprovalDecision {
+ assert_eq!(request.agent_id.as_deref(), Some("allowed"));
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ openhuman_embed::ApprovalDecision::ApproveOnce
+ }
+}
+struct HangingDecision {
+ started: tokio::sync::mpsc::UnboundedSender<String>,
+ dropped: tokio::sync::mpsc::UnboundedSender<()>,
+}
+struct OnDecisionDrop(tokio::sync::mpsc::UnboundedSender<()>);
+impl Drop for OnDecisionDrop {
+ fn drop(&mut self) {
+ let _ = self.0.send(());
+ }
+}
+#[async_trait::async_trait]
+impl openhuman_embed::ApprovalHandler for HangingDecision {
+ async fn decide(
+ &self,
+ request: &openhuman_embed::PendingApproval,
+ ) -> openhuman_embed::ApprovalDecision {
+ let _guard = OnDecisionDrop(self.dropped.clone());
+ let _ = self.started.send(request.request_id.clone());
+ std::future::pending().await
+ }
+}
diff --git a/crates/openhuman-embed/examples/capability_report.rs b/crates/openhuman-embed/examples/capability_report.rs
new file mode 100644
index 0000000000..d2fef8f905
--- /dev/null
+++ b/crates/openhuman-embed/examples/capability_report.rs
@@ -0,0 +1,42 @@
+//! Title: Stable capability metadata before and after boot
+//! Summary: Stable capability metadata before and after boot.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ if std::env::args().any(|argument| argument == "--json") {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&openhuman_embed::RuntimeBuilder::library().describe())?
+ );
+ return Ok(());
+ }
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: capability_report
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+ // ANCHOR_END: capability_report
+ support::passed("capability_report");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/completer.rs b/crates/openhuman-embed/examples/completer.rs
new file mode 100644
index 0000000000..d85eaff329
--- /dev/null
+++ b/crates/openhuman-embed/examples/completer.rs
@@ -0,0 +1,30 @@
+//! Title: Stateless completion without booting an agent runtime
+//! Summary: Stateless completion without booting an agent runtime.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+async fn run() -> anyhow::Result<()> {
+ let provider = support::provider("completion reply").await;
+ // ANCHOR: completer
+ let route = support::example_provider(&provider)?;
+ let completer = openhuman_embed::Completer::new(route.route().expect("explicit route").clone());
+ let response = completer
+ .complete(openhuman_embed::CompletionRequest::new(
+ route.model_id().expect("explicit model"),
+ vec![openhuman_embed::ChatMessage::user("Say hello")],
+ ))
+ .await?;
+ assert!(!response.text.is_empty());
+ if support::offline() {
+ assert_eq!(response.text, "completion reply");
+ assert_eq!(support::chat_requests(&provider).await.len(), 1);
+ }
+ println!("{}", response.text);
+ // ANCHOR_END: completer
+ support::passed("completer");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/cron.rs b/crates/openhuman-embed/examples/cron.rs
new file mode 100644
index 0000000000..c6f5c96a45
--- /dev/null
+++ b/crates/openhuman-embed/examples/cron.rs
@@ -0,0 +1,49 @@
+//! Title: Run and inspect an agent cron job
+//! Summary: Run and inspect an agent cron job.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: cron
+ let agent = runtime.agent(AgentSpec::new("scheduled"))?;
+ let cron = runtime.cron();
+ let spec = openhuman_embed::JobSpec::agent(
+ "daily",
+ agent.id(),
+ "Say hello",
+ openhuman_embed::JobSchedule::Cron {
+ expr: "0 0 * * *".into(),
+ tz: None,
+ },
+ );
+ let first = cron.upsert(spec.clone())?;
+ assert_eq!(cron.upsert(spec)?.id, first.id);
+ let run = cron.run_now("daily").await?;
+ assert!(run.success, "{}", run.output);
+ if support::offline() {
+ assert!(run.output.contains("hello from the stub"));
+ }
+ assert_eq!(cron.runs("daily", 1)?[0].status, "ok");
+ assert!(cron.remove("daily")?);
+ assert!(cron.list()?.is_empty());
+ println!("cron execution and history verified");
+ // ANCHOR_END: cron
+ support::passed("cron");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/custom_provider.rs b/crates/openhuman-embed/examples/custom_provider.rs
new file mode 100644
index 0000000000..c2ae5c5c35
--- /dev/null
+++ b/crates/openhuman-embed/examples/custom_provider.rs
@@ -0,0 +1,97 @@
+//! Title: Native custom providers, fallback and workload role pins
+//! Summary: Inject deterministic native models and prove fallback and role selection without inference HTTP.
+//! Run: offline; no live inference path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::providers::{ChatModel, ModelRequest, ModelResponse};
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Provider, Runtime, ToolScopeSpec};
+use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc,
+};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let failed = Arc::new(AtomicUsize::new(0));
+ let fallback = Arc::new(AtomicUsize::new(0));
+ let pinned = Arc::new(AtomicUsize::new(0));
+ // ANCHOR: custom_provider
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+ // ANCHOR_END: custom_provider
+ println!("native fallback and coding role pin verified");
+ support::passed("custom_provider");
+ Ok(())
+}
+
+struct LocalModel {
+ reply: Option<&'static str>,
+ calls: Arc<AtomicUsize>,
+}
+#[async_trait::async_trait]
+impl ChatModel<()> for LocalModel {
+ async fn invoke(
+ &self,
+ _: &(),
+ _: ModelRequest,
+ ) -> openhuman_embed::providers::Result<ModelResponse> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ match self.reply {
+ Some(reply) => Ok(ModelResponse::assistant(reply)),
+ None => Err(openhuman_embed::providers::Error::Model(
+ "local primary unavailable".into(),
+ )),
+ }
+ }
+}
diff --git a/crates/openhuman-embed/examples/defaults_overrides.rs b/crates/openhuman-embed/examples/defaults_overrides.rs
new file mode 100644
index 0000000000..a77decae3e
--- /dev/null
+++ b/crates/openhuman-embed/examples/defaults_overrides.rs
@@ -0,0 +1,62 @@
+//! Title: Runtime defaults and per-agent overrides
+//! Summary: Runtime defaults and per-agent overrides.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.4),
+ max_tokens: Some(256),
+ ..Default::default()
+ })
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: defaults_overrides
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+ // ANCHOR_END: defaults_overrides
+ support::passed("defaults_overrides");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/hooks.rs b/crates/openhuman-embed/examples/hooks.rs
new file mode 100644
index 0000000000..3606fd8c3f
--- /dev/null
+++ b/crates/openhuman-embed/examples/hooks.rs
@@ -0,0 +1,55 @@
+//! Title: A per-agent post-turn hook observes completed turns
+//! Summary: A per-agent post-turn hook observes completed turns.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: hooks
+ let count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let agent = runtime.agent(
+ AgentSpec::new("hooked").post_turn_hook(std::sync::Arc::new(Counter(count.clone()))),
+ )?;
+ let sibling = runtime.agent(AgentSpec::new("sibling"))?;
+ assert!(!agent.run("Hello hook").await?.reply.is_empty());
+ support::eventually("post-turn hook", || {
+ (count.load(std::sync::atomic::Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ assert!(!sibling.run("Hello sibling").await?.reply.is_empty());
+ assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
+ println!("post-turn hook isolated to its agent");
+ // ANCHOR_END: hooks
+ support::passed("hooks");
+ Ok(())
+}
+
+struct Counter(std::sync::Arc<std::sync::atomic::AtomicUsize>);
+#[async_trait::async_trait]
+impl openhuman_embed::seams::PostTurnHook for Counter {
+ fn name(&self) -> &str {
+ "example-counter"
+ }
+ async fn on_turn_complete(
+ &self,
+ _: &openhuman_embed::seams::TurnContext,
+ ) -> anyhow::Result<()> {
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(())
+ }
+}
diff --git a/crates/openhuman-embed/examples/host_tools.rs b/crates/openhuman-embed/examples/host_tools.rs
new file mode 100644
index 0000000000..f550054ae6
--- /dev/null
+++ b/crates/openhuman-embed/examples/host_tools.rs
@@ -0,0 +1,72 @@
+//! Title: Host tools and HostOnly keep the advertised tool catalog exact
+//! Summary: Host tools and HostOnly keep the advertised tool catalog exact.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: host_tools
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+ // ANCHOR_END: host_tools
+ support::passed("host_tools");
+ Ok(())
+}
+
+struct Ping(std::sync::Arc<std::sync::atomic::AtomicUsize>);
+#[async_trait::async_trait]
+impl openhuman_embed::Tool for Ping {
+ fn name(&self) -> &str {
+ "host_ping"
+ }
+ fn description(&self) -> &str {
+ "Read a host supplied value"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type":"object","properties":{}})
+ }
+ async fn execute(&self, _: serde_json::Value) -> anyhow::Result<openhuman_embed::ToolResult> {
+ self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(openhuman_embed::ToolResult::success("pong"))
+ }
+}
diff --git a/crates/openhuman-embed/examples/lean_headless.rs b/crates/openhuman-embed/examples/lean_headless.rs
new file mode 100644
index 0000000000..5e2f694fe5
--- /dev/null
+++ b/crates/openhuman-embed/examples/lean_headless.rs
@@ -0,0 +1,40 @@
+//! Title: Lean runtime without background services
+//! Summary: Lean runtime without background services.
+//! Run: offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = openhuman_embed::RuntimeBuilder::lean()
+ .config(support::offline_config())
+ .services(openhuman_embed::ServiceSet::none())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: lean_headless
+ let info = runtime.capabilities();
+ assert_eq!(info.weight, openhuman_embed::WeightClass::Lean);
+ assert!(info.services.is_empty());
+ let agent = runtime.agent(
+ AgentSpec::new("lean").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ assert!(!agent.run("Hello lean runtime").await?.reply.is_empty());
+ println!("lean runtime runs a turn without background services");
+ // ANCHOR_END: lean_headless
+ support::passed("lean_headless");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/mcp.rs b/crates/openhuman-embed/examples/mcp.rs
new file mode 100644
index 0000000000..2937ec4e24
--- /dev/null
+++ b/crates/openhuman-embed/examples/mcp.rs
@@ -0,0 +1,118 @@
+//! Title: Connect an actual MCP protocol stub over loopback
+//! Summary: Connect an actual MCP protocol stub over loopback.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: mcp
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: mcp
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+ // ANCHOR_END: mcp
+ support::passed("mcp");
+ Ok(())
+}
+
+struct McpStub;
+impl wiremock::Respond for McpStub {
+ fn respond(&self, request: &wiremock::Request) -> wiremock::ResponseTemplate {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ let result = match body["method"].as_str().unwrap_or_default() {
+ "initialize" => {
+ serde_json::json!({"protocolVersion":"2025-06-18","capabilities":{"tools":{}},"serverInfo":{"name":"forecast","version":"1"}})
+ }
+ "notifications/initialized" => return wiremock::ResponseTemplate::new(202),
+ "tools/list" => {
+ serde_json::json!({"tools":[{"name":"forecast","description":"Local forecast","inputSchema":{"type":"object"}}]})
+ }
+ "tools/call" => serde_json::json!({"content":[{"type":"text","text":"sunny"}]}),
+ _ => serde_json::json!({}),
+ };
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"jsonrpc":"2.0","id":body["id"],"result":result}))
+ }
+}
+
+/// The fixture follows the immediately available MCP bridge and verifies results.
+struct ForecastModel(std::sync::atomic::AtomicUsize);
+impl wiremock::Respond for ForecastModel {
+ fn respond(&self, request: &wiremock::Request) -> wiremock::ResponseTemplate {
+ let step = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let reply = match step {
+ 0 => support::tool_call_completion("mcp_list_tools", r#"{"server":"forecast"}"#),
+ 1 => {
+ assert!(
+ support::tool_results(request).contains("forecast"),
+ "remote tools were listed successfully"
+ );
+ support::tool_call_completion(
+ "mcp_call_tool",
+ r#"{"server":"forecast","tool":"forecast","arguments":{}}"#,
+ )
+ }
+ _ => {
+ assert!(
+ support::tool_results(request).contains("sunny"),
+ "remote execution returned its result"
+ );
+ support::chat_completion("sunny verified")
+ }
+ };
+ wiremock::ResponseTemplate::new(200).set_body_json(reply)
+ }
+}
diff --git a/crates/openhuman-embed/examples/memory.rs b/crates/openhuman-embed/examples/memory.rs
new file mode 100644
index 0000000000..93b93bdb85
--- /dev/null
+++ b/crates/openhuman-embed/examples/memory.rs
@@ -0,0 +1,37 @@
+//! Title: Tenant scoped memory facade with an in-memory engine
+//! Summary: Tenant scoped memory facade with an in-memory engine.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{Runtime, Workspace};
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let engine =
+ std::sync::Arc::new(openhuman_embed::memory::api::conformance::ReferenceEngine::new());
+ let runtime = Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .memory_engine(engine)
+ .build()
+ .await?;
+ // ANCHOR: memory
+ let acme = runtime.memory("team:acme")?;
+ let other = runtime.memory("team:other")?;
+ let params = serde_json::from_value(serde_json::json!({"text":"Acme ships on Fridays"}))?;
+ let learned = acme.learn(params).await?;
+ let hits = acme.get(vec![learned.id.clone()]).await?;
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].meta.namespace.to_string(), "team:acme");
+ assert!(other.get(vec![learned.id.clone()]).await?.is_empty());
+ assert_eq!(other.forget(vec![learned.id.clone()]).await?.forgotten, 0);
+ assert_eq!(acme.forget(vec![learned.id]).await?.forgotten, 1);
+ println!("memory learning, tenant isolation and deletion verified");
+ // ANCHOR_END: memory
+ support::passed("memory");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/profiles.rs b/crates/openhuman-embed/examples/profiles.rs
index dfd1ecc2e5..64d48c99f0 100644
--- a/crates/openhuman-embed/examples/profiles.rs
+++ b/crates/openhuman-embed/examples/profiles.rs
@@ -1,180 +1,49 @@
-//! Two users, one thread id, two conversations: SaaS profiles in-process.
-//!
-//! [`ProfileRuntime`] boots a core in SaaS mode on a scratch root, provisions
-//! a profile for `alice` and one for `bob`, and has each say something on a
-//! thread both call `t1`. Each then reads `t1` back and sees only their own
-//! messages: a thread id is unique per profile, never per process.
-//!
-//! It runs offline. Managed inference goes to a local mock that answers
-//! `echo: <your message>`, reached through a stub backend transport, because
-//! a profile's config names no inference endpoint of its own; a real host
-//! installs the TinyHumans transport (`openhuman_tinyhumans::install`) and
-//! hands each profile its user's credential instead.
-//!
-//! ```bash
-//! cargo run -p openhuman-embed --example profiles
-//! ```
-//!
-//! Building a `ProfileRuntime` locks the process into SaaS mode: no
-//! `Runtime::builder()` core can boot beside it.
-
-use std::sync::Arc;
-
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
-use openhuman_embed::profiles::ProfileCredentialKind;
-use openhuman_embed::{
- BackendRequest, BackendTransport, BackendTransportError, BaseUrlPurpose, ProfileRuntime,
- SaasConfig, TransportProfile,
-};
-use serde_json::{json, Value};
-use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
+//! Title: SaaS profiles isolate conversation history
+//! Summary: SaaS profiles isolate conversation history.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+mod support;
fn main() -> anyhow::Result<()> {
- let _ = env_logger::builder().is_test(false).try_init();
- // A turn's async state machine overflows tokio's default worker stack;
- // see `run_turn.rs`.
- let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()?;
- // Run on a worker thread, whose stack is the tuned one.
- runtime.block_on(async { tokio::spawn(run()).await? })
-}
-
-async fn run() -> anyhow::Result<()> {
- // ── offline inference ────────────────────────────────────────────────
- let inference = MockServer::start().await;
- Mock::given(wiremock::matchers::path_regex(r"chat/completions$"))
- .respond_with(Echo)
- .mount(&inference)
- .await;
- Mock::given(wiremock::matchers::any())
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "data": [] })))
- .with_priority(10)
- .mount(&inference)
- .await;
- openhuman_embed::install_backend_transport(Arc::new(MockTransport(inference.uri())));
-
- // ── the SaaS core ────────────────────────────────────────────────────
- // The root must be absolute, existing and not world-writable; a temp
- // directory is all three. `build` writes a service token there, since
- // nothing serves a gateway here.
let root = tempfile::tempdir()?;
- let profiles = ProfileRuntime::build(SaasConfig::new(root.path())).await?;
- println!("SaaS root: {}", root.path().display());
-
- // ── one profile per user ─────────────────────────────────────────────
+ let config = openhuman_embed::SaasConfig::new(root.path());
+ let workspace = config.operator_config().workspace_dir;
+ support::run_with_workspace(run(config), &workspace)
+}
+async fn run(config: openhuman_embed::SaasConfig) -> anyhow::Result<()> {
+ let provider = support::echo_inference().await;
+ support::PointedTransport::install(&provider.uri());
+ // ANCHOR: profiles
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
let mut handles = Vec::new();
- for (user, said) in [
- ("alice", "Remind me to water the ferns."),
- ("bob", "What rhymes with orange?"),
- ] {
- let provisioned = profiles.provision(user).await?;
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
profiles
.set_credential(
- &provisioned.profile_id,
- ProfileCredentialKind::ApiKey,
- &format!("{user}-demo-key"),
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
)
.await?;
let handle = profiles.open(user).await?;
- let reply = handle.chat("t1", said).await?;
- println!(
- "\n[{user}] sent message to t1; got reply ({} bytes)",
- reply.text.len()
- );
- handles.push((user, handle));
- }
-
- // ── each sees only their own t1 ──────────────────────────────────────
- for (user, handle) in &handles {
- let messages = handle.messages("t1").await?;
- println!(
- "\n{user}'s t1 ({}) has {} messages",
- handle.workspace_dir().display(),
- messages.len()
- );
- for (i, message) in messages.iter().enumerate() {
- println!(" [{i}] {}", message.sender);
- }
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
}
- println!("\nprofiles: {:?}", profiles.list().await?);
-
drop(handles);
profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+ // ANCHOR_END: profiles
+ support::passed("profiles");
Ok(())
}
-
-/// Answers every chat completion with `echo: <the last user message>`,
-/// streamed when the request asks for it.
-struct Echo;
-
-impl Respond for Echo {
- fn respond(&self, request: &Request) -> ResponseTemplate {
- let body: Value = serde_json::from_slice(&request.body).unwrap_or_default();
- let said = body["messages"]
- .as_array()
- .and_then(|m| m.iter().rev().find(|m| m["role"] == "user"))
- .and_then(|m| m["content"].as_str())
- .unwrap_or_default();
- // The core prefixes the turn's message with context lines (the date);
- // the user's own text is the last line.
- let said = said
- .lines()
- .rev()
- .find(|l| !l.trim().is_empty())
- .unwrap_or_default();
- let reply = format!("echo: {said}");
- if body["stream"] == true {
- let chunk = json!({ "id": "c", "object": "chat.completion.chunk", "created": 0,
- "model": "echo", "choices": [{ "index": 0,
- "delta": { "role": "assistant", "content": reply }, "finish_reason": null }] });
- let done = json!({ "id": "c", "object": "chat.completion.chunk", "created": 0,
- "model": "echo", "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }] });
- return ResponseTemplate::new(200).set_body_raw(
- format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n"),
- "text/event-stream",
- );
- }
- ResponseTemplate::new(200).set_body_json(json!({
- "id": "c", "object": "chat.completion", "created": 0, "model": "echo",
- "choices": [{ "index": 0, "finish_reason": "stop",
- "message": { "role": "assistant", "content": reply } }],
- "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
- }))
- }
-}
-
-/// Sends managed inference to the mock; every other backend call answers
-/// "no backend".
-struct MockTransport(String);
-
-#[async_trait::async_trait]
-impl BackendTransport for MockTransport {
- async fn send_json(&self, _req: BackendRequest<'_>) -> Result<Value, BackendTransportError> {
- Err(BackendTransportError::Unavailable)
- }
- async fn send_multipart(
- &self,
- _req: BackendRequest<'_>,
- _form: reqwest::multipart::Form,
- ) -> Result<Value, BackendTransportError> {
- Err(BackendTransportError::Unavailable)
- }
- fn http_client(&self, _profile: TransportProfile) -> reqwest::Client {
- reqwest::Client::new()
- }
- fn base_url(&self, _configured: Option<&str>, _purpose: BaseUrlPurpose) -> String {
- self.0.clone()
- }
- fn product_identity(&self) -> String {
- "openhuman-embed-example".to_string()
- }
- fn attribution_headers(&self) -> reqwest::header::HeaderMap {
- reqwest::header::HeaderMap::new()
- }
- fn name(&self) -> &'static str {
- "example-mock"
- }
-}
diff --git a/crates/openhuman-embed/examples/run_turn.rs b/crates/openhuman-embed/examples/run_turn.rs
index 19014d4d34..f3177f2dad 100644
--- a/crates/openhuman-embed/examples/run_turn.rs
+++ b/crates/openhuman-embed/examples/run_turn.rs
@@ -1,144 +1,40 @@
-//! Run one OpenHuman agent turn as a library call.
-//!
-//! The counterpart to `embed_headless.rs`: that one shows how to *build* a core
-//! and dispatch plumbing methods, this one shows the thing an embedder actually
-//! wants — a prompt in, a reply out, with the model, the workspace and the
-//! access tier chosen in code rather than discovered from the environment.
-//!
-//! ```bash
-//! # Against any OpenAI-compatible endpoint:
-//! OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-//! OPENHUMAN_EXAMPLE_API_KEY=sk-… \
-//! OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
-//! cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"
-//!
-//! # Or against the machine's own configured inference, in its real workspace:
-//! OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."
-//! ```
-//!
-//! Optional: `OPENHUMAN_EXAMPLE_BACKEND_URL` points the core's non-inference
-//! backend calls somewhere, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill
-//! bundles.
-//!
-//! Note the runtime is built by hand rather than with `#[tokio::main]`. That is
-//! not incidental — see [`main`].
+//! Title: Hello agent: a prompt in and a reply out
+//! Summary: Hello agent: a prompt in and a reply out.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
-use std::path::PathBuf;
-
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
-use openhuman_embed::{Access, Harness, Provider, Workspace};
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
fn main() -> anyhow::Result<()> {
- // Library embedders own logging. `RUST_LOG=debug` shows the `[embed]` and
- // `[embed][harness]` lines this crate emits around a turn.
- let _ = env_logger::builder().is_test(false).try_init();
-
- // A turn is a very large async state machine, and delegating to a sub-agent
- // nests another inside it. tokio's default 2 MiB worker stack overflows and
- // aborts the process — `#[tokio::main]` gives you that default, which is why
- // this example does not use it. Every host that runs a turn must set these.
- let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()?;
-
- runtime.block_on(run())
+ support::run(run())
}
async fn run() -> anyhow::Result<()> {
- let prompt = std::env::args()
- .nth(1)
- .unwrap_or_else(|| "Introduce yourself in one sentence.".to_string());
-
- let inherit = std::env::var_os("OPENHUMAN_EXAMPLE_INHERIT").is_some();
-
- let mut builder = Harness::builder()
- // Read-only by default: this example should be safe to point at any
- // directory. Swap for `Access::full()` to let the agent actually act —
- // and read that method's docs first, because it means real shell
- // commands and real file edits under `action_dir`.
- .access(Access::readonly());
-
- builder = if inherit {
- // Reuse the machine's real workspace and whatever inference it is
- // already configured with — sessions persist, and the agent sees the
- // memory the desktop app wrote.
- builder
- .workspace(Workspace::Inherit)
- .provider(Provider::inherit())
- } else {
- // A throwaway workspace, removed when the harness drops, and an
- // explicitly named endpoint. Nothing here touches ~/.openhuman.
- let base_url = std::env::var("OPENHUMAN_EXAMPLE_BASE_URL").map_err(|_| {
- anyhow::anyhow!(
- "set OPENHUMAN_EXAMPLE_BASE_URL + OPENHUMAN_EXAMPLE_API_KEY, \
- or set OPENHUMAN_EXAMPLE_INHERIT=1 to use this machine's own \
- configured inference"
- )
- })?;
- let api_key = std::env::var("OPENHUMAN_EXAMPLE_API_KEY").map_err(|_| {
- anyhow::anyhow!("OPENHUMAN_EXAMPLE_API_KEY is required with a base URL")
- })?;
- let model =
- std::env::var("OPENHUMAN_EXAMPLE_MODEL").unwrap_or_else(|_| "gpt-4o-mini".to_string());
-
- let mut builder = builder
- .workspace(Workspace::Ephemeral)
- .provider(Provider::openai_compatible(base_url, api_key).model(model))
- // Let the agent's file tools look at the current directory.
- .action_dir(std::env::current_dir()?);
-
- // The core still makes non-inference backend calls. Signed out of the
- // real one, those are rejected — and a rejection publishes
- // Point them at your own backend if you have one. Authenticated
- // backend features additionally need a real Session::backend value;
- // caller-supplied inference itself does not.
- if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_BACKEND_URL") {
- builder = builder.backend_url(url);
- }
- builder
- };
-
- // Skills are opt-in and copied into the harness's workspace; see the
- // builder method's docs for why they are copied rather than linked.
- if let Some(dir) = std::env::var_os("OPENHUMAN_EXAMPLE_SKILLS_DIR") {
- #[cfg(feature = "skills")]
- {
- builder = builder.skills_dir(PathBuf::from(dir));
- }
- #[cfg(not(feature = "skills"))]
- {
- let _ = PathBuf::from(dir);
- eprintln!("this build has no `skills` feature; ignoring the skills directory");
- }
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: run_turn
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
}
-
- let harness = builder.build().await?;
- println!("workspace: {}", harness.workspace_dir().display());
- println!("action dir: {}", harness.action_dir().display());
-
- // Stream the turn as it runs. Without a sink the call resolves to one final
- // string and shows nothing in between. The core *awaits* its sends, so this
- // channel is real backpressure — a receiver that stops draining stalls the
- // turn.
- let (tx, mut rx) = tokio::sync::mpsc::channel(256);
- let printer = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- eprintln!("[progress] {progress:?}");
- }
- });
-
- let outcome = harness.turn(&prompt).on_progress(tx).send().await?;
- // Wait for the printer to drain, but bound it. A detached async sub-agent
- // (`spawn_async_subagent`) can carry a clone of the sender past `send()`
- // returning, so waiting on sender-drop alone could hang indefinitely.
- let _ = tokio::time::timeout(std::time::Duration::from_secs(30), printer).await;
-
- println!("\nsession: {}", outcome.session_id);
println!("{}", outcome.reply);
-
- // Pass `outcome.session_id` to `.session(..)` on a later turn to continue
- // this conversation.
+ // ANCHOR_END: run_turn
+ support::passed("run_turn");
Ok(())
}
diff --git a/crates/openhuman-embed/examples/runtime_events.rs b/crates/openhuman-embed/examples/runtime_events.rs
new file mode 100644
index 0000000000..7bfc21afc1
--- /dev/null
+++ b/crates/openhuman-embed/examples/runtime_events.rs
@@ -0,0 +1,86 @@
+//! Title: Runtime lifecycle events and live hook registration
+//! Summary: Observe ordered metadata and add/remove a runtime-wide hook while agents keep running.
+//! Run: offline with a loopback provider; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, RuntimeEventKind};
+use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc,
+};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("event reply").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: runtime_events
+ let mut events = runtime.events();
+ let count = Arc::new(AtomicUsize::new(0));
+ runtime.post_turn_hook("live-counter", Some(Arc::new(Counter(count.clone()))));
+ let agent = runtime.agent(AgentSpec::new("observed"))?;
+ assert_eq!(agent.run("private payload one").await?.reply, "event reply");
+ support::eventually("runtime hook", || {
+ (count.load(Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ runtime.post_turn_hook("live-counter", None);
+ assert_eq!(agent.run("private payload two").await?.reply, "event reply");
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 1,
+ "removed hook stops observing turns"
+ );
+ runtime.remove_agent(agent.id()).await?;
+ let mut previous = 0;
+ let (mut added, mut started, mut ended) = (0, 0, 0);
+ loop {
+ let event =
+ tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()).await??;
+ assert!(event.sequence > previous);
+ previous = event.sequence;
+ assert_eq!(event.agent_id.as_deref(), Some("observed"));
+ assert!(!serde_json::to_string(&event)?.contains("private payload"));
+ match event.kind {
+ RuntimeEventKind::AgentAdded => added += 1,
+ RuntimeEventKind::TurnStarted => {
+ assert!(event.turn_id.is_some());
+ started += 1;
+ }
+ RuntimeEventKind::TurnEnded { success } => {
+ assert!(success);
+ ended += 1;
+ }
+ RuntimeEventKind::AgentRemoved => break,
+ _ => {}
+ }
+ }
+ assert_eq!((added, started, ended), (1, 2, 2));
+ // ANCHOR_END: runtime_events
+ println!("ordered content-free lifecycle events and live hook removal verified");
+ support::passed("runtime_events");
+ Ok(())
+}
+struct Counter(Arc<AtomicUsize>);
+#[async_trait::async_trait]
+impl openhuman_embed::seams::PostTurnHook for Counter {
+ fn name(&self) -> &str {
+ "live-counter"
+ }
+ async fn on_turn_complete(
+ &self,
+ _: &openhuman_embed::seams::TurnContext,
+ ) -> anyhow::Result<()> {
+ self.0.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+}
diff --git a/crates/openhuman-embed/examples/sandbox_access.rs b/crates/openhuman-embed/examples/sandbox_access.rs
new file mode 100644
index 0000000000..da498822ba
--- /dev/null
+++ b/crates/openhuman-embed/examples/sandbox_access.rs
@@ -0,0 +1,56 @@
+//! Title: Access tiers and explicit sandbox choices
+//! Summary: Access tiers and explicit sandbox choices.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: sandbox_access
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("attempted-write");
+ let attempted_write = support::tool_call_completion(
+ "write_file",
+ &serde_json::json!({
+ "path": marker.display().to_string(), "content": "example"
+ })
+ .to_string(),
+ );
+ let read_provider = support::scripted_provider(vec![attempted_write], "write refused").await;
+ let read = runtime.agent(
+ AgentSpec::new("read")
+ .provider(support::route(&read_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(openhuman_embed::Access::readonly())
+ .definition(
+ AgentDefinitionSpec::new().sandbox(openhuman_embed::SandboxModeSpec::ReadOnly),
+ ),
+ )?;
+ let full = runtime.agent(AgentSpec::new("full").access(openhuman_embed::Access::full()))?;
+ assert_ne!(read.config().autonomy.level, full.config().autonomy.level);
+ assert!(!read.run("Write a marker").await?.reply.is_empty());
+ assert!(
+ !marker.exists(),
+ "readonly sandbox must refuse the attempted write"
+ );
+ let requests = support::chat_requests(&read_provider).await;
+ assert!(!support::tool_names(&requests[0]).contains(&"write_file".to_string()));
+ println!("readonly sandbox refused a model-requested write");
+ // ANCHOR_END: sandbox_access
+ support::passed("sandbox_access");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/server.rs b/crates/openhuman-embed/examples/server.rs
new file mode 100644
index 0000000000..3b500dfef6
--- /dev/null
+++ b/crates/openhuman-embed/examples/server.rs
@@ -0,0 +1,64 @@
+//! Title: Embed an agent behind a host-owned HTTP server
+//! Summary: Embed an agent behind a host-owned HTTP server.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: server
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let agent = runtime.agent(
+ AgentSpec::new("http-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let address = listener.local_addr()?;
+ // A real host should use its HTTP framework and authenticate requests.
+ // This single-request fixture keeps the library dependency direction intact.
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await?;
+ let mut request = vec![0; 4096];
+ let length = socket.read(&mut request).await?;
+ assert!(String::from_utf8_lossy(&request[..length]).starts_with("GET /hello "));
+ let reply = agent.run("Say hello").await?.reply;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ reply.len(),
+ reply
+ );
+ socket.write_all(response.as_bytes()).await?;
+ Ok::<_, anyhow::Error>(())
+ });
+ let reply = reqwest::get(format!("http://{address}/hello"))
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ assert!(!reply.is_empty());
+ if support::offline() {
+ assert_eq!(reply, "hello from the stub");
+ }
+ server.await??;
+ println!("host HTTP request reached the in-process agent");
+ // ANCHOR_END: server
+ support::passed("server");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/skills.rs b/crates/openhuman-embed/examples/skills.rs
new file mode 100644
index 0000000000..927e8d54c7
--- /dev/null
+++ b/crates/openhuman-embed/examples/skills.rs
@@ -0,0 +1,42 @@
+//! Title: Copy a skill bundle into its agent workspace
+//! Summary: Copy a skill bundle into its agent workspace.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: skills
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: skills
+ let skills = tempfile::tempdir()?;
+ std::fs::create_dir(skills.path().join("review"))?;
+ std::fs::write(skills.path().join("review/SKILL.md"),
+ "---\nname: review\ndescription: Review Rust functions carefully.\n---\nCheck error paths.\n")?;
+ let agent = runtime.agent(AgentSpec::new("skilled").skills_dir(skills.path()))?;
+ let copied = agent
+ .workspace_dir()
+ .join("agents/skilled/skills/review/SKILL.md");
+ assert_eq!(
+ std::fs::read_to_string(&copied)?,
+ std::fs::read_to_string(skills.path().join("review/SKILL.md"))?
+ );
+ assert!(!std::fs::symlink_metadata(copied)?.file_type().is_symlink());
+ assert!(!agent.run("Hello").await?.reply.is_empty());
+ println!("skill bundle copied without symlinks");
+ // ANCHOR_END: skills
+ support::passed("skills");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/storage.rs b/crates/openhuman-embed/examples/storage.rs
new file mode 100644
index 0000000000..0d6523bf8d
--- /dev/null
+++ b/crates/openhuman-embed/examples/storage.rs
@@ -0,0 +1,82 @@
+//! Title: SQLite writes and MongoDB configuration through Embed
+//! Summary: Open a real local SQLite backend and describe a MongoDB deployment without connecting.
+//! Run: offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb.
+//! Feature: storage-sqlite
+
+mod support;
+use openhuman_embed::seams::{CollectionSpec, Precondition, Scope};
+use openhuman_embed::{Runtime, RuntimeBuilder, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let directory = tempfile::tempdir()?;
+ // ANCHOR: storage_sqlite
+ let mut config = support::offline_config();
+ config.storage.url = Some(format!(
+ "sqlite:{}",
+ directory.path().join("storage").display()
+ ));
+ let runtime = Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .config(config)
+ .backend_url(backend.uri())
+ .build()
+ .await?;
+ let storage = runtime.storage().expect("configured SQLite backend");
+ assert_eq!(storage.driver(), "sqlite");
+ let scoped = storage.for_scope(&Scope::local())?;
+ let documents = scoped.documents();
+ documents
+ .ensure_collection(&CollectionSpec::new("settings"))
+ .await?;
+ let value = serde_json::json!({"theme":"dark"});
+ documents
+ .put("settings", "demo", value.clone(), Precondition::Absent)
+ .await?;
+ assert_eq!(
+ documents
+ .get("settings", "demo")
+ .await?
+ .expect("stored value")
+ .doc,
+ value
+ );
+ assert!(
+ documents
+ .delete("settings", "demo", Precondition::None)
+ .await?
+ );
+ assert!(documents.get("settings", "demo").await?.is_none());
+ assert_eq!(
+ runtime.capabilities().storage.driver.as_deref(),
+ Some("sqlite")
+ );
+ // ANCHOR_END: storage_sqlite
+ drop(scoped);
+ drop(storage);
+ drop(runtime);
+
+ // ANCHOR: storage_mongodb
+ // Enable `storage-mongodb` for a deployment that builds this config.
+ // Describing it does not contact MongoDB and never exposes credentials.
+ let mut mongo = support::offline_config();
+ mongo.storage.url = Some("mongodb://app:[email protected]:27017/openhuman".into());
+ let builder = RuntimeBuilder::library().config(mongo);
+ let description = builder.describe();
+ assert_eq!(description.storage.driver.as_deref(), Some("mongodb"));
+ assert!(description.storage.configured);
+ assert!(!serde_json::to_string(&description)?.contains("example-password"));
+ // An explicit environment variable is the only path to a live database.
+ if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_MONGODB_URL") {
+ let live = RuntimeBuilder::library().storage(url).build().await?;
+ assert_eq!(live.storage().expect("MongoDB backend").driver(), "mongodb");
+ }
+ // ANCHOR_END: storage_mongodb
+ println!("SQLite put/get/delete and credential-safe MongoDB configuration verified");
+ support::passed("storage");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/streaming.rs b/crates/openhuman-embed/examples/streaming.rs
new file mode 100644
index 0000000000..20b89832f1
--- /dev/null
+++ b/crates/openhuman-embed/examples/streaming.rs
@@ -0,0 +1,60 @@
+//! Title: Streaming progress with a draining receiver
+//! Summary: Streaming progress with a draining receiver.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::streaming_provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: streaming
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+ // ANCHOR_END: streaming
+ support::passed("streaming");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/structured_output.rs b/crates/openhuman-embed/examples/structured_output.rs
new file mode 100644
index 0000000000..675a7752b6
--- /dev/null
+++ b/crates/openhuman-embed/examples/structured_output.rs
@@ -0,0 +1,50 @@
+//! Title: Structured output parsed and checked against the request
+//! Summary: Structured output parsed and checked against the request.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: default
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: structured_output
+ let json_provider = support::provider(r#"{"verdict":"approve"}"#).await;
+ let agent = runtime.agent(
+ AgentSpec::new("structured")
+ .provider(support::route(&json_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.turn("Review").response_format(openhuman_embed::complete::ResponseFormat::JsonSchema {
+ name: "review".into(),
+ schema: serde_json::json!({"type":"object","properties":{"verdict":{"type":"string"}},"required":["verdict"]}),
+ }).max_tokens(128).send().await?;
+ assert_eq!(
+ outcome.structured,
+ Some(serde_json::json!({"verdict":"approve"}))
+ );
+ let requests = support::chat_requests(&json_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["response_format"]["type"], "json_schema");
+ assert_eq!(body["max_tokens"], 128);
+ println!("validated verdict: approve");
+ // ANCHOR_END: structured_output
+ support::passed("structured_output");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/support/mod.rs b/crates/openhuman-embed/examples/support/mod.rs
new file mode 100644
index 0000000000..ac8c39d19e
--- /dev/null
+++ b/crates/openhuman-embed/examples/support/mod.rs
@@ -0,0 +1,454 @@
+//! Helpers shared by the embed crate's end-to-end tests.
+//!
+//! Each test file owns its process: a runtime claims a process-wide slot, so
+//! the files split by scenario rather than by assertion.
+
+#![allow(dead_code)]
+
+use openhuman_embed::process::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
+use openhuman_embed::RuntimeConfig as Config;
+use serde_json::json;
+use wiremock::{MockServer, Request};
+
+/// Requests that represent model inference, excluding the new `/models` discovery call.
+pub async fn chat_requests(server: &MockServer) -> Vec<Request> {
+ server
+ .received_requests()
+ .await
+ .expect("provider recorded requests")
+ .into_iter()
+ .filter(|request| request.url.path().ends_with("/chat/completions"))
+ .collect()
+}
+
+/// An OpenAI-compatible chat completion carrying `content`.
+pub fn chat_completion(content: &str) -> serde_json::Value {
+ json!({
+ "id": "chatcmpl-embed-test",
+ "object": "chat.completion",
+ "created": 1_700_000_000_u64,
+ "model": "embed-test-model",
+ "choices": [{
+ "index": 0,
+ "message": { "role": "assistant", "content": content },
+ "finish_reason": "stop"
+ }],
+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
+ })
+}
+
+/// A config that keeps the turn offline: no local runtimes and no
+/// conversation memory. Mirrors `profile/src/bin/library_profile/harness.rs::fixture()` in openhuman-benchmarks,
+/// which is the recipe already proven against real turns.
+pub fn offline_config() -> Config {
+ let mut config = Config::default();
+ config.local_ai.runtime_enabled = false;
+ config.runtime_python.enabled = false;
+ // Conversation memory ingest is intentionally fire-and-forget. It can
+ // still be buffering after a turn returns, which is useful in the product
+ // but unrelated to these tests' contracts and would race the final
+ // ephemeral-workspace cleanup assertion.
+ config.memory.conversations.enabled = false;
+ // Session-store dual writes and shadow reads are also deliberately
+ // fire-and-forget; leaving them on makes their detached filesystem work
+ // race the synchronous ephemeral cleanup.
+ config.agent.session_dual_write = false;
+ config.agent.session_shadow_reads = false;
+ config.default_temperature = 0.0;
+ config
+}
+
+/// The tuned runtime the harness documents as the caller's responsibility.
+///
+/// A default 2 MiB worker stack overflows on a turn that delegates to a
+/// sub-agent and aborts the whole process, so building it the documented way is
+/// both what the test needs and a check that the documented way works.
+pub fn runtime() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .thread_stack_size(AGENT_WORKER_STACK_BYTES)
+ .max_blocking_threads(MAX_BLOCKING_THREADS)
+ .build()
+ .expect("tokio runtime")
+}
+
+/// A stub backend that answers every incidental non-inference call.
+pub async fn stub_backend() -> wiremock::MockServer {
+ let backend = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(json!({
+ "success": true,
+ "data": { "id": "embed-test", "email": "[email protected]" }
+ })))
+ .mount(&backend)
+ .await;
+ backend
+}
+
+/// An OpenAI-compatible chat completion asking the harness to call `tool`.
+pub fn tool_call_completion(tool: &str, arguments: &str) -> serde_json::Value {
+ json!({
+ "id": "chatcmpl-embed-test-tool",
+ "object": "chat.completion",
+ "created": 1_700_000_000_u64,
+ "model": "embed-test-model",
+ "choices": [{
+ "index": 0,
+ "message": {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [{
+ "id": "call_embed_test_1",
+ "type": "function",
+ "function": { "name": tool, "arguments": arguments }
+ }]
+ },
+ "finish_reason": "tool_calls"
+ }],
+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
+ })
+}
+
+/// Prefix of the user message that carries tool results in the prompt-guided
+/// (text) tool-call dialect, which the harness uses for models it does not
+/// know to support native tool calling.
+const PROMPT_TOOL_RESULTS_PREFIX: &str = "[Tool results]";
+
+/// The concatenated tool results of a recorded request, in either dialect:
+/// `tool`-role messages (native tool calling) or the `[Tool results]` user
+/// message (prompt-guided tool calling).
+pub fn tool_results(request: &wiremock::Request) -> String {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ body.get("messages")
+ .and_then(|m| m.as_array())
+ .map(|messages| {
+ messages
+ .iter()
+ .filter_map(|m| {
+ let content = match m.get("content")? {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ match m.get("role").and_then(|r| r.as_str()) {
+ Some("tool") => Some(content),
+ // The harness may prepend continuation guidance and
+ // the active user request before the tool-result block.
+ Some("user") if content.contains(PROMPT_TOOL_RESULTS_PREFIX) => Some(
+ content
+ .split_once(PROMPT_TOOL_RESULTS_PREFIX)?
+ .1
+ .to_string(),
+ ),
+ _ => None,
+ }
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ })
+ .unwrap_or_default()
+}
+
+/// An OpenAI-compatible provider answering `/v1/chat/completions` with `reply`.
+pub async fn provider(reply: &str) -> wiremock::MockServer {
+ let server = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(chat_completion(reply)))
+ .mount(&server)
+ .await;
+ server
+}
+
+/// The tool names a recorded chat-completion request advertised.
+pub fn tool_names(request: &wiremock::Request) -> Vec<String> {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ body.get("tools")
+ .and_then(|t| t.as_array())
+ .map(|tools| {
+ tools
+ .iter()
+ .filter_map(|t| {
+ t.pointer("/function/name")
+ .or_else(|| t.get("name"))
+ .and_then(|n| n.as_str())
+ .map(str::to_string)
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// A provider that answers its first chat requests with `steps`, in order,
+/// then every later one with `fallback`.
+pub async fn scripted_provider(
+ steps: Vec<serde_json::Value>,
+ fallback: &str,
+) -> wiremock::MockServer {
+ let server = wiremock::MockServer::start().await;
+ for (index, step) in steps.into_iter().enumerate() {
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(step))
+ .up_to_n_times(1)
+ .with_priority(u8::try_from(index + 1).unwrap_or(u8::MAX))
+ .mount(&server)
+ .await;
+ }
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .and(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(chat_completion(fallback)))
+ .with_priority(u8::MAX)
+ .mount(&server)
+ .await;
+ server
+}
+
+/// A routed provider on `server` with a fixed model.
+pub fn route(server: &wiremock::MockServer, model: &str) -> openhuman_embed::Provider {
+ openhuman_embed::Provider::openai_compatible(format!("{}/v1", server.uri()), "sk-test")
+ .model(model)
+}
+
+/// Polls `check` until it yields `Some` or about ten seconds pass.
+pub async fn eventually<T>(what: &str, mut check: impl FnMut() -> Option<T>) -> T {
+ for _ in 0..1000 {
+ if let Some(value) = check() {
+ return value;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ panic!("timed out waiting for {what}");
+}
+
+/// A backend transport that sends managed inference to `base_url` (a mock)
+/// and answers every control-plane call as "no backend". For suites that run
+/// turns through the core's managed-inference path, such as SaaS profiles,
+/// whose configs name no inference endpoint of their own.
+pub struct PointedTransport {
+ base_url: String,
+ client: reqwest::Client,
+}
+
+impl PointedTransport {
+ pub fn install(base_url: &str) {
+ openhuman_embed::install_backend_transport(std::sync::Arc::new(Self {
+ base_url: base_url.trim_end_matches('/').to_string(),
+ client: reqwest::Client::new(),
+ }));
+ }
+}
+
+#[async_trait::async_trait]
+impl openhuman_embed::BackendTransport for PointedTransport {
+ async fn send_json(
+ &self,
+ req: openhuman_embed::BackendRequest<'_>,
+ ) -> Result<serde_json::Value, openhuman_embed::BackendTransportError> {
+ // Forward inference requests to the pointed mock endpoint.
+ // This uses the same HTTP client as a real transport would.
+ let url = format!("{}/{}", self.base_url, req.path.trim_start_matches('/'));
+ let resp = self
+ .client
+ .post(&url)
+ .json(&req.body)
+ .send()
+ .await
+ .map_err(|_| openhuman_embed::BackendTransportError::Unavailable)?;
+ resp.json()
+ .await
+ .map_err(|_| openhuman_embed::BackendTransportError::Unavailable)
+ }
+
+ async fn send_multipart(
+ &self,
+ _req: openhuman_embed::BackendRequest<'_>,
+ _form: reqwest::multipart::Form,
+ ) -> Result<serde_json::Value, openhuman_embed::BackendTransportError> {
+ Err(openhuman_embed::BackendTransportError::Unavailable)
+ }
+
+ fn http_client(&self, _profile: openhuman_embed::TransportProfile) -> reqwest::Client {
+ reqwest::Client::new()
+ }
+
+ fn base_url(
+ &self,
+ _configured: Option<&str>,
+ _purpose: openhuman_embed::BaseUrlPurpose,
+ ) -> String {
+ self.base_url.clone()
+ }
+
+ fn product_identity(&self) -> String {
+ "openhuman-embed-test".to_string()
+ }
+
+ fn attribution_headers(&self) -> reqwest::header::HeaderMap {
+ reqwest::header::HeaderMap::new()
+ }
+
+ fn name(&self) -> &'static str {
+ "embed-test-pointed"
+ }
+}
+
+/// A mock OpenAI-compatible endpoint that answers every chat completion with
+/// `echo: <the last user message>`, streamed when the request asks for it,
+/// and every other request with an empty success.
+pub async fn echo_inference() -> MockServer {
+ let server = MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path_regex(r"chat/completions$"))
+ .respond_with(EchoCompletion)
+ .with_priority(1)
+ .mount(&server)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(json!({ "success": true, "data": [] })),
+ )
+ .with_priority(10)
+ .mount(&server)
+ .await;
+ server
+}
+
+/// The last user message of a chat-completion request body.
+pub fn last_user_message(body: &serde_json::Value) -> String {
+ body.get("messages")
+ .and_then(|m| m.as_array())
+ .and_then(|messages| {
+ messages
+ .iter()
+ .rev()
+ .find(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
+ })
+ .and_then(|m| match m.get("content")? {
+ serde_json::Value::String(s) => Some(s.clone()),
+ other => Some(other.to_string()),
+ })
+ .unwrap_or_default()
+}
+
+struct EchoCompletion;
+
+impl wiremock::Respond for EchoCompletion {
+ fn respond(&self, request: &Request) -> wiremock::ResponseTemplate {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ let reply = format!("echo: {}", last_user_message(&body));
+ if body.get("stream").and_then(|s| s.as_bool()) == Some(true) {
+ let chunk = json!({
+ "id": "chatcmpl-embed-test",
+ "object": "chat.completion.chunk",
+ "created": 1_700_000_000_u64,
+ "model": "embed-test-model",
+ "choices": [{ "index": 0, "delta": { "role": "assistant", "content": reply }, "finish_reason": null }]
+ });
+ let done = json!({
+ "id": "chatcmpl-embed-test",
+ "object": "chat.completion.chunk",
+ "created": 1_700_000_000_u64,
+ "model": "embed-test-model",
+ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }],
+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }
+ });
+ wiremock::ResponseTemplate::new(200).set_body_raw(
+ format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n"),
+ "text/event-stream",
+ )
+ } else {
+ wiremock::ResponseTemplate::new(200).set_body_json(chat_completion(&reply))
+ }
+ }
+}
+
+/// Run each scenario on a worker with an isolated keyring workspace.
+pub fn run<F>(future: F) -> anyhow::Result<()>
+where
+ F: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
+{
+ let keyring_workspace = tempfile::tempdir()?;
+ run_with_workspace(future, keyring_workspace.path())
+}
+
+/// SaaS hosts initialize their keyring at the operator workspace before boot.
+pub fn run_with_workspace<F>(future: F, workspace: &std::path::Path) -> anyhow::Result<()>
+where
+ F: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
+{
+ if offline() {
+ // Set before starting any worker; fixtures never use operator credentials.
+ std::env::set_var("OPENHUMAN_WORKSPACE", workspace);
+ std::env::remove_var("OPENHUMAN_KEYRING_MASTER_KEY_FILE");
+ std::env::remove_var("OPENHUMAN_KEYRING_BACKEND");
+ let key = format!(
+ "{}{}",
+ uuid::Uuid::new_v4().simple(),
+ uuid::Uuid::new_v4().simple()
+ );
+ std::env::set_var("OPENHUMAN_KEYRING_MASTER_KEY", key);
+ }
+ openhuman_embed::process::init_master_key()?;
+ if offline() {
+ // The root is cached; SaaS rejects a process-wide workspace override.
+ std::env::remove_var("OPENHUMAN_WORKSPACE");
+ }
+ runtime().block_on(async { tokio::spawn(future).await? })
+}
+
+/// Offline by default; choosing a live endpoint requires an explicit opt-in.
+pub fn example_provider(server: &MockServer) -> anyhow::Result<openhuman_embed::Provider> {
+ if std::env::var("OPENHUMAN_EXAMPLE_LIVE").as_deref() == Ok("1") {
+ Ok(openhuman_embed::Provider::openai_compatible(
+ std::env::var("OPENHUMAN_EXAMPLE_BASE_URL")?,
+ std::env::var("OPENHUMAN_EXAMPLE_API_KEY")?,
+ )
+ .model(std::env::var("OPENHUMAN_EXAMPLE_MODEL")?))
+ } else {
+ Ok(route(server, "fixture"))
+ }
+}
+
+pub fn offline() -> bool {
+ std::env::var("OPENHUMAN_EXAMPLE_LIVE").as_deref() != Ok("1")
+}
+
+/// All examples emit this only after their behavioral assertions pass.
+pub fn passed(name: &str) {
+ println!("EXAMPLE_OK {name}");
+}
+
+/// A deterministic provider that supports both JSON completion and token streaming.
+pub async fn streaming_provider(reply: &str) -> MockServer {
+ struct Completion(String);
+ impl wiremock::Respond for Completion {
+ fn respond(&self, request: &Request) -> wiremock::ResponseTemplate {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap_or_default();
+ if body["stream"] != true {
+ return wiremock::ResponseTemplate::new(200)
+ .set_body_json(chat_completion(&self.0));
+ }
+ let midpoint = self.0.chars().count() / 2;
+ let chunks = [
+ self.0.chars().take(midpoint).collect::<String>(),
+ self.0.chars().skip(midpoint).collect::<String>(),
+ ];
+ let mut events = String::new();
+ for chunk in chunks {
+ let body = json!({"id":"example-stream","object":"chat.completion.chunk","created":0,"model":"fixture",
+ "choices":[{"index":0,"delta":{"content":chunk},"finish_reason":null}]});
+ events.push_str(&format!("data: {body}\n\n"));
+ }
+ let done = json!({"id":"example-stream","object":"chat.completion.chunk","created":0,"model":"fixture",
+ "choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}});
+ events.push_str(&format!("data: {done}\n\ndata: [DONE]\n\n"));
+ wiremock::ResponseTemplate::new(200).set_body_raw(events, "text/event-stream")
+ }
+ }
+ let server = MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(Completion(reply.into()))
+ .mount(&server)
+ .await;
+ server
+}
diff --git a/crates/openhuman-embed/examples/telegram.rs b/crates/openhuman-embed/examples/telegram.rs
new file mode 100644
index 0000000000..17bf862ac3
--- /dev/null
+++ b/crates/openhuman-embed/examples/telegram.rs
@@ -0,0 +1,88 @@
+//! Title: Telegram channel answered by its bound agent via a local Bot API
+//! Summary: Telegram channel answered by its bound agent via a local Bot API.
+//! Run: offline with loopback stubs; no live path.
+//! Feature: channels
+
+mod support;
+use openhuman_embed::{AgentDefinitionSpec, AgentSpec, Runtime, ToolScopeSpec, Workspace};
+
+fn main() -> anyhow::Result<()> {
+ support::run(run())
+}
+
+async fn run() -> anyhow::Result<()> {
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::route(&provider, "fixture"))
+ .build()
+ .await?;
+ // ANCHOR: telegram
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+ // ANCHOR_END: telegram
+ support::passed("telegram");
+ Ok(())
+}
diff --git a/crates/openhuman-embed/examples/two_agents.rs b/crates/openhuman-embed/examples/two_agents.rs
index e2a0b869a1..43a98d5197 100644
--- a/crates/openhuman-embed/examples/two_agents.rs
+++ b/crates/openhuman-embed/examples/two_agents.rs
@@ -1,131 +1,54 @@
-//! Two independently configured agents on one runtime.
-//!
-//! The two-step library API: initialise a [`Runtime`] once, then instantiate
-//! agents on it. Here a read-only *reviewer* and a full-autonomy *fixer*
-//! share a runtime but nothing else — each has its own access tier, working
-//! directory, model and (optionally) skills.
-//!
-//! ```bash
-//! # BYOK: both agents run on the endpoint you name.
-//! OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-//! OPENHUMAN_EXAMPLE_API_KEY=sk-… \
-//! OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
-//! cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-//!
-//! # Managed: the runtime holds a TinyHumans API key and agents that name no
-//! # provider run on the managed backend.
-//! OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_… \
-//! cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-//! ```
-//!
-//! Optional: `OPENHUMAN_EXAMPLE_BACKEND_URL` for non-inference backend calls,
-//! `OPENHUMAN_EXAMPLE_SKILLS_DIR` for skill bundles given to the reviewer only.
+//! Title: Two agents with independent prompts and working folders
+//! Summary: Two agents with independent prompts and working folders.
+//! Run: offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+//! Feature: default
-use std::path::PathBuf;
-
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
-use openhuman_embed::{Access, AgentSpec, Provider, Runtime, Workspace};
+mod support;
+use openhuman_embed::{AgentSpec, Runtime, Workspace};
fn main() -> anyhow::Result<()> {
- let _ = env_logger::builder().is_test(false).try_init();
-
- // See `run_turn.rs` for why the runtime is built by hand: a turn's async
- // state machine overflows tokio's default worker stack.
- let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()?;
-
- runtime.block_on(run())
+ support::run(run())
}
async fn run() -> anyhow::Result<()> {
- let prompt = std::env::args()
- .nth(1)
- .unwrap_or_else(|| "Describe this directory in one paragraph.".to_string());
-
- // ── step 1: the runtime ──────────────────────────────────────────────
- let mut builder = Runtime::builder().workspace(Workspace::Ephemeral);
- if let Ok(key) = std::env::var("OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY") {
- builder = builder.api_key(key);
- }
- if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_BACKEND_URL") {
- builder = builder.backend_url(url);
- }
- let runtime = builder.build().await?;
- println!("runtime root: {}", runtime.root_dir().display());
-
- // A BYOK route when the caller named one; otherwise the agents inherit
- // the runtime's default (managed inference on the API key).
- let provider = match (
- std::env::var("OPENHUMAN_EXAMPLE_BASE_URL"),
- std::env::var("OPENHUMAN_EXAMPLE_API_KEY"),
- ) {
- (Ok(base_url), Ok(api_key)) => {
- let model = std::env::var("OPENHUMAN_EXAMPLE_MODEL")
- .unwrap_or_else(|_| "gpt-4o-mini".to_string());
- Provider::openai_compatible(base_url, api_key).model(model)
- }
- _ if runtime.has_api_key() => Provider::inherit(),
- _ => anyhow::bail!(
- "set OPENHUMAN_EXAMPLE_BASE_URL + OPENHUMAN_EXAMPLE_API_KEY for BYOK, or \
- OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY for managed inference"
- ),
- };
-
- // ── step 2: the agents ───────────────────────────────────────────────
- let cwd = std::env::current_dir()?;
-
- #[cfg_attr(not(feature = "skills"), allow(unused_mut))]
- let mut reviewer = AgentSpec::new("reviewer")
- .system_prompt("You are a careful code reviewer. You read; you never change files.")
- .provider(provider.clone())
- .access(Access::readonly())
- .action_dir(&cwd);
- if let Some(dir) = std::env::var_os("OPENHUMAN_EXAMPLE_SKILLS_DIR") {
- #[cfg(feature = "skills")]
- {
- reviewer = reviewer.skills_dir(PathBuf::from(dir));
- }
- #[cfg(not(feature = "skills"))]
- {
- let _ = PathBuf::from(dir);
- eprintln!("this build has no `skills` feature; ignoring the skills directory");
- }
- }
- let reviewer = runtime.agent(reviewer)?;
-
- // `Access::full()` means real shell commands and real file edits under
- // `action_dir`. It is pointed at a scratch directory here on purpose.
- let scratch = runtime.root_dir().join("fixer-scratch");
- std::fs::create_dir_all(&scratch)?;
+ let backend = support::stub_backend().await;
+ let provider = support::provider("hello from the stub").await;
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .workspace(Workspace::Ephemeral)
+ .backend_url(backend.uri())
+ .provider(support::example_provider(&provider)?)
+ .build()
+ .await?;
+ // ANCHOR: two_agents
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
let fixer = runtime.agent(
AgentSpec::new("fixer")
- .system_prompt("You act on review findings inside your working directory.")
- .provider(provider)
- .access(Access::full())
- .action_dir(&scratch),
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
)?;
-
- println!("agents: {:?}", runtime.agent_ids());
- println!("reviewer action dir: {}", reviewer.action_dir().display());
- println!("fixer action dir: {}", fixer.action_dir().display());
-
- let review = reviewer.run(&prompt).await?;
- println!(
- "\n[reviewer] session {}\n{}",
- review.session_id, review.reply
- );
-
- let fix = fixer
- .turn(format!(
- "A reviewer said:\n\n{}\n\nWrite a short NOTES.md in your working directory summarising it.",
- review.reply
- ))
- .send()
- .await?;
- println!("\n[fixer] session {}\n{}", fix.session_id, fix.reply);
-
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+ // ANCHOR_END: two_agents
+ support::passed("two_agents");
Ok(())
}
diff --git a/crates/openhuman-embed/src/agent/README.md b/crates/openhuman-embed/src/agent/README.md
index 155d3455c0..ea6e12ed1c 100644
--- a/crates/openhuman-embed/src/agent/README.md
+++ b/crates/openhuman-embed/src/agent/README.md
@@ -144,16 +144,7 @@ Use `runtime_id()` to check that supplied agents belong to one runtime and
conflicting id. Runtime ids are opaque and valid only for that runtime's
lifetime; they are not persistence keys.
-```rust,no_run
-use std::sync::Arc;
-use openhuman_embed::{Agent, HostTools, HostTurnTools, Tool};
-# fn connect(agent: &Agent, make_tools: impl Fn() -> Vec<Box<dyn Tool>> + Send + Sync + 'static) -> Result<(), openhuman_embed::ToolAttachmentError> {
-let source: HostTools = Arc::new(move |_| HostTurnTools::advertised(make_tools()));
-agent.attach_tools("tinyhivemind", source.clone())?;
-agent.clone().attach_tools("tinyhivemind", source)?; // idempotent
-# Ok(())
-# }
-```
+See the runnable [host_tools example](../../examples/host_tools.rs), region `host_tools`. It uses the public facade and asserts its behavior against an offline stub.
## Boundaries
diff --git a/crates/openhuman-embed/src/agent/approval_handler.rs b/crates/openhuman-embed/src/agent/approval_handler.rs
new file mode 100644
index 0000000000..1f888de68c
--- /dev/null
+++ b/crates/openhuman-embed/src/agent/approval_handler.rs
@@ -0,0 +1,90 @@
+//! Callback-based approvals, using the same agent-scoped gate as polling.
+use crate::{ApprovalDecision, Approvals, CancellationToken, PendingApproval};
+use openhuman_core::core::bus::{EventHandler, SubscriptionHandle, BUS};
+use openhuman_core::core::events::DomainEvent;
+use std::sync::Arc;
+
+/// Decide an agent's sanitized pending permission request asynchronously.
+#[async_trait::async_trait]
+pub trait ApprovalHandler: Send + Sync {
+ /// Return a decision; removing the agent or subscription cancels an in-flight callback.
+ async fn decide(&self, request: &PendingApproval) -> ApprovalDecision;
+}
+
+/// Owns a live callback subscription; dropping it or removing its agent cancels callbacks.
+pub struct ApprovalSubscription {
+ _subscription: Option<SubscriptionHandle>,
+ cancellation: CancellationToken,
+}
+impl Drop for ApprovalSubscription {
+ fn drop(&mut self) {
+ self.cancellation.cancel();
+ }
+}
+impl ApprovalSubscription {
+ pub(crate) fn new(
+ agent_id: &str,
+ handler: Arc<dyn ApprovalHandler>,
+ removed: tokio::sync::watch::Receiver<bool>,
+ ) -> Self {
+ let cancellation = CancellationToken::new();
+ let subscriber = Arc::new(Handler {
+ agent_id: agent_id.to_owned(),
+ handler,
+ cancellation: cancellation.clone(),
+ removed,
+ });
+ Self {
+ _subscription: BUS.subscribe(subscriber),
+ cancellation,
+ }
+ }
+}
+struct Handler {
+ agent_id: String,
+ handler: Arc<dyn ApprovalHandler>,
+ cancellation: CancellationToken,
+ removed: tokio::sync::watch::Receiver<bool>,
+}
+#[async_trait::async_trait]
+impl EventHandler<DomainEvent> for Handler {
+ fn name(&self) -> &str {
+ "embed.agent.approval_handler"
+ }
+ async fn handle(&self, event: &DomainEvent) {
+ let DomainEvent::ApprovalRequested {
+ request_id,
+ agent_id,
+ ..
+ } = event
+ else {
+ return;
+ };
+ if agent_id.as_deref() != Some(&self.agent_id) || *self.removed.borrow() {
+ return;
+ }
+ let approvals = Approvals::new(&self.agent_id, self.removed.clone());
+ let Ok(pending) = approvals.pending() else {
+ return;
+ };
+ let Some(request) = pending
+ .into_iter()
+ .find(|request| request.request_id == *request_id)
+ else {
+ return;
+ };
+ let mut removed = self.removed.clone();
+ let decision = tokio::select! {
+ biased;
+ _ = self.cancellation.cancelled() => return,
+ _ = removed.wait_for(|removed| *removed) => return,
+ decision = self.handler.decide(&request) => decision,
+ };
+ if self.cancellation.is_cancelled() || *self.removed.borrow() {
+ return;
+ }
+ // The gate atomically refuses a request that expired/was removed while
+ // the callback ran, so a late answer never revives a cancelled tool.
+ let _ = approvals.decide(request_id, decision);
+ }
+}
diff --git a/crates/openhuman-embed/src/agent/approvals.rs b/crates/openhuman-embed/src/agent/approvals.rs
index 23542db1ed..8816fcde74 100644
--- a/crates/openhuman-embed/src/agent/approvals.rs
+++ b/crates/openhuman-embed/src/agent/approvals.rs
@@ -31,18 +31,28 @@ pub enum ApprovalsError {
#[derive(Debug, Clone)]
pub struct Approvals {
agent_id: String,
+ removed: tokio::sync::watch::Receiver<bool>,
}
impl Approvals {
- pub(crate) fn new(agent_id: &str) -> Self {
+ pub(crate) fn new(agent_id: &str, removed: tokio::sync::watch::Receiver<bool>) -> Self {
Self {
agent_id: agent_id.to_string(),
+ removed,
}
}
/// The agent's undecided requests, oldest first. Empty when the runtime
- /// has no approval gate.
+ /// has no approval gate or this agent has been removed. Reusing the id
+ /// does not make a removed agent's handle observe the replacement.
pub fn pending(&self) -> Result<Vec<PendingApproval>, ApprovalsError> {
+ // Hold the lifecycle read through the gate access. Removal must finish
+ // before the id can be reused, so a concurrent old handle cannot cross
+ // from its lifecycle check into the replacement's approval store.
+ let removed = self.removed.borrow();
+ if *removed {
+ return Ok(Vec::new());
+ }
let Some(gate) = ApprovalGate::try_global() else {
return Ok(Vec::new());
};
@@ -60,6 +70,10 @@ impl Approvals {
request_id: &str,
decision: ApprovalDecision,
) -> Result<PendingApproval, ApprovalsError> {
+ let removed = self.removed.borrow();
+ if *removed {
+ return Err(ApprovalsError::NotFound(request_id.to_owned()));
+ }
let gate = ApprovalGate::try_global().ok_or(ApprovalsError::GateNotInstalled)?;
log::debug!(
"[embed][approvals] agent={} decide request_id={request_id} decision={}",
diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rs
index bda026f01a..42e995d34b 100644
--- a/crates/openhuman-embed/src/agent/build.rs
+++ b/crates/openhuman-embed/src/agent/build.rs
@@ -19,7 +19,51 @@ use crate::harness::Access;
use crate::runtime::Runtime;
pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInner, AgentError> {
- let parts = spec.into_parts();
+ let mut parts = spec.into_parts();
+ let defaults = runtime.defaults();
+ let mut runtime_definition = defaults.definition.clone();
+ if defaults.sandbox != crate::SandboxModeSpec::None {
+ runtime_definition = runtime_definition.sandbox(defaults.sandbox);
+ }
+ if let Some(v) = defaults.model.temperature {
+ runtime_definition = runtime_definition.temperature(v);
+ }
+ if let Some(v) = defaults.model.max_iterations {
+ runtime_definition = runtime_definition.max_iterations(v);
+ }
+ let mut inherited = if let Some(name) = parts.template.take() {
+ defaults
+ .templates
+ .get(&name)
+ .cloned()
+ .ok_or(AgentError::UnknownTemplate(name))?
+ .inherit(runtime_definition)?
+ } else {
+ runtime_definition
+ };
+ let mut model_defaults = defaults.model.overlay(&parts.model_defaults);
+ model_defaults.validate().map_err(AgentError::Invalid)?;
+ if let Some(v) = parts.model_defaults.temperature {
+ inherited = inherited.temperature(v);
+ }
+ if let Some(v) = parts.model_defaults.max_iterations {
+ inherited = inherited.max_iterations(v);
+ }
+ parts.definition = parts.definition.inherit(inherited)?;
+ let include_user_skills = parts
+ .include_user_skills
+ .unwrap_or(defaults.skills.include_user_skills);
+ #[cfg(feature = "skills")]
+ {
+ parts.skills_dir = parts.skills_dir.or(defaults.skills.root.clone());
+ }
+ #[cfg(feature = "mcp")]
+ {
+ let mut servers = defaults.mcp_baseline.clone();
+ servers.extend(parts.mcp_servers);
+ parts.mcp_servers = servers;
+ }
+
let id = parts.id;
validate_agent_id(&id).map_err(|reason| AgentError::InvalidId {
id: id.clone(),
@@ -73,9 +117,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
)
});
- let mut access = parts
- .access
- .unwrap_or_else(|| runtime.default_access().clone());
+ let mut access = parts.access.unwrap_or_else(|| defaults.access.clone());
for (path, grant) in parts.trusted {
access = access.trust(path, grant);
}
@@ -87,10 +129,21 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
}
access.apply(&mut config);
- let provider = parts
- .provider
- .unwrap_or_else(|| runtime.default_provider().clone());
+ let provider = if parts.inherit_provider_route {
+ match parts.provider.as_ref().and_then(crate::Provider::model_id) {
+ Some(model) => defaults.provider.clone().model(model),
+ None => defaults.provider.clone(),
+ }
+ } else {
+ parts.provider.unwrap_or_else(|| defaults.provider.clone())
+ };
crate::runtime::builder::apply_provider(&mut config, &provider);
+ if let Some(v) = parts.model_defaults.temperature {
+ config.default_temperature = v;
+ }
+ if let Some(v) = parts.model_defaults.max_iterations {
+ config.agent.max_tool_iterations_override = Some(v);
+ }
#[cfg(feature = "mcp")]
if !parts.mcp_servers.is_empty() {
@@ -168,6 +221,12 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
// ── definition ───────────────────────────────────────────────────────
let mut definition = parts.definition.into_core(&id)?;
+ model_defaults.temperature = Some(definition.temperature);
+ model_defaults.max_iterations = Some(definition.max_iterations);
+ if config.agent.max_tool_iterations_override.is_some() {
+ config.agent.max_tool_iterations_override = Some(definition.max_iterations);
+ }
+
// Every declared server's tools are registered as their own
// `mcp_<server>_<tool>`, deferred by default. A wildcard belt reaches them
// through `tool_search` already; a named belt reaches deferred tools only
@@ -203,11 +262,28 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
Some(route.api_key.clone()),
)
});
+ let mut overrides = openhuman_core::agent::host_overrides::HostOverrides::default();
+ overrides.parent = runtime.core_runtime().context().host_overrides();
+ overrides.model = provider.custom_model();
+ overrides.role_models = provider.role_models().clone();
+ overrides.session_store = parts.session_store;
+ let overrides = std::sync::Arc::new(overrides);
+ for hook in parts.post_turn_hooks {
+ overrides.post_turn_hook(hook.name(), Some(hook.clone()));
+ }
+ for hook in parts.tool_hooks {
+ overrides.tool_hook(hook.name(), Some(hook.clone()));
+ }
+ let lifecycle = super::lifecycle::Lifecycle::new();
+ let approval_subscription = parts.approval_handler.map(|handler| {
+ super::approval_handler::ApprovalSubscription::new(&id, handler, lifecycle.removed())
+ });
let overlay = ContextOverlay {
+ host_overrides: Some(overrides.clone()),
config: context_config,
domains,
tool_groups,
- user_skill_roots: parts.include_user_skills,
+ user_skill_roots: include_user_skills,
// A host session store keeps each agent's conversations apart by id.
session_agent: Some(id.to_string()),
profile: None,
@@ -231,12 +307,15 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
config.action_dir.display(),
provider.is_routed(),
access.turn_origin().is_some(),
- parts.include_user_skills,
+ include_user_skills,
config.autonomy.level,
access.approval_gate_enabled()
);
Ok(AgentInner {
+ registry: runtime.agent_registry(),
+ overrides,
+ _approval_subscription: approval_subscription,
id,
runtime_id: runtime.runtime_id().to_owned(),
attachments: Default::default(),
@@ -246,10 +325,11 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInn
config,
definition,
provider,
+ model_defaults,
access,
layout,
host_tools: parts.host_tools,
- lifecycle: super::lifecycle::Lifecycle::new(),
+ lifecycle,
host_only,
})
}
diff --git a/crates/openhuman-embed/src/agent/definition.rs b/crates/openhuman-embed/src/agent/definition.rs
index dd820d6f83..ada845ace3 100644
--- a/crates/openhuman-embed/src/agent/definition.rs
+++ b/crates/openhuman-embed/src/agent/definition.rs
@@ -51,16 +51,41 @@ pub enum SandboxModeSpec {
Sandboxed,
}
+/// Starting definition: a named built-in or a complete host-supplied definition.
+#[derive(Debug, Clone)]
+pub enum DefinitionBase {
+ /// Clone the named built-in definition.
+ Builtin(String),
+ /// Clone a complete host-supplied definition.
+ Custom(Box<AgentDefinition>),
+}
+impl From<&str> for DefinitionBase {
+ fn from(value: &str) -> Self {
+ Self::Builtin(value.into())
+ }
+}
+impl From<String> for DefinitionBase {
+ fn from(value: String) -> Self {
+ Self::Builtin(value)
+ }
+}
+impl From<AgentDefinition> for DefinitionBase {
+ fn from(value: AgentDefinition) -> Self {
+ Self::Custom(Box::new(value))
+ }
+}
+
/// Builder for an agent's definition. See the module docs for the default.
#[derive(Debug, Clone, Default)]
pub struct AgentDefinitionSpec {
+ base: Option<DefinitionBase>,
system_prompt: Option<String>,
/// The prompt is the whole system prompt, with nothing composed around it.
bare_prompt: bool,
tools: Option<ToolScopeSpec>,
disallowed_tools: Vec<String>,
tool_rules: Option<tinytools::ToolRules>,
- sandbox: SandboxModeSpec,
+ sandbox: Option<SandboxModeSpec>,
max_iterations: Option<usize>,
temperature: Option<f64>,
display_name: Option<String>,
@@ -73,6 +98,77 @@ impl AgentDefinitionSpec {
Self::default()
}
+ /// Start from a named built-in or a complete custom core definition.
+ pub fn from_base(base: impl Into<DefinitionBase>) -> Self {
+ Self {
+ base: Some(base.into()),
+ ..Self::default()
+ }
+ }
+
+ pub(crate) fn explicit_model_defaults(&self) -> crate::ModelDefaults {
+ let base = match &self.base {
+ Some(DefinitionBase::Custom(definition)) => Some((**definition).clone()),
+ Some(DefinitionBase::Builtin(name)) => {
+ AgentDefinitionRegistry::builtins_only().get(name).cloned()
+ }
+ None => None,
+ };
+ crate::ModelDefaults {
+ temperature: self
+ .temperature
+ .or_else(|| base.as_ref().map(|d| d.temperature)),
+ max_iterations: self
+ .max_iterations
+ .or_else(|| base.as_ref().map(|d| d.max_iterations)),
+ ..Default::default()
+ }
+ }
+
+ /// Resolve unspecified fields from the runtime or a template. Tools only narrow.
+ pub(crate) fn inherit(mut self, lower: Self) -> Result<Self, AgentError> {
+ if let (Some(requested), Some(base)) = (&self.tools, &lower.tools) {
+ let allowed = match (requested, base) {
+ (_, ToolScopeSpec::Wildcard) | (ToolScopeSpec::HostOnly, _) => true,
+ (ToolScopeSpec::Named(a), ToolScopeSpec::Named(b)) => {
+ a.iter().all(|n| b.contains(n))
+ }
+ _ => false,
+ };
+ if !allowed {
+ return Err(AgentError::WidensRuntime(
+ "definition tool scope widens its base template".into(),
+ ));
+ }
+ }
+ self.base = self.base.or(lower.base);
+ if self.system_prompt.is_none() {
+ self.system_prompt = lower.system_prompt;
+ self.bare_prompt = lower.bare_prompt;
+ }
+ self.tools = self.tools.or(lower.tools);
+ self.disallowed_tools.extend(lower.disallowed_tools);
+ // Tool rules must retain both layers' restrictions; core also enforces config rules.
+ self.tool_rules = match (self.tool_rules, lower.tool_rules) {
+ (Some(a), Some(b)) => {
+ if a != b {
+ return Err(AgentError::WidensRuntime(
+ "cannot replace inherited template tool rules; narrow tool scope instead"
+ .into(),
+ ));
+ }
+ Some(a)
+ }
+ (a, b) => a.or(b),
+ };
+ self.sandbox = self.sandbox.or(lower.sandbox);
+ self.max_iterations = self.max_iterations.or(lower.max_iterations);
+ self.temperature = self.temperature.or(lower.temperature);
+ self.display_name = self.display_name.or(lower.display_name);
+ self.when_to_use = self.when_to_use.or(lower.when_to_use);
+ Ok(self)
+ }
+
/// Replace the dynamic system prompt with this fixed text.
///
/// The identity, memory and safety sections the orchestrator prompt
@@ -129,7 +225,7 @@ impl AgentDefinitionSpec {
/// Confine the agent's shell and file tools.
pub fn sandbox(mut self, mode: SandboxModeSpec) -> Self {
- self.sandbox = mode;
+ self.sandbox = Some(mode);
self
}
@@ -161,9 +257,17 @@ impl AgentDefinitionSpec {
pub(crate) fn into_core(self, id: &str) -> Result<AgentDefinition, AgentError> {
let host_only = self.is_host_only();
let registry = AgentDefinitionRegistry::builtins_only();
- let mut def = registry.get(ORCHESTRATOR_ID).cloned().ok_or_else(|| {
- AgentError::Invalid("built-in orchestrator definition is missing".to_string())
- })?;
+ let custom_base = self.base.is_some();
+ let mut def = match self.base {
+ Some(DefinitionBase::Custom(def)) => *def,
+ Some(DefinitionBase::Builtin(name)) => registry
+ .get(&name)
+ .cloned()
+ .ok_or(AgentError::UnknownDefinition(name))?,
+ None => registry.get(ORCHESTRATOR_ID).cloned().ok_or_else(|| {
+ AgentError::Invalid("built-in orchestrator definition is missing".into())
+ })?,
+ };
def.id = id.to_string();
def.display_name = Some(self.display_name.unwrap_or_else(|| id.to_string()));
if let Some(text) = self.when_to_use {
@@ -187,7 +291,32 @@ impl AgentDefinitionSpec {
}
None => {}
}
- def.tools = match self.tools.unwrap_or(ToolScopeSpec::Wildcard) {
+ if custom_base {
+ if let Some(requested) = &self.tools {
+ let narrows = match (requested, &def.tools) {
+ (_, ToolScope::Wildcard) | (ToolScopeSpec::HostOnly, _) => true,
+ (ToolScopeSpec::Named(a), ToolScope::Named(b)) => {
+ a.iter().all(|name| b.contains(name))
+ }
+ _ => false,
+ };
+ if !narrows {
+ return Err(AgentError::WidensRuntime(
+ "tool scope widens the chosen base definition".into(),
+ ));
+ }
+ }
+ }
+ def.tools = match self.tools.unwrap_or_else(|| {
+ if custom_base {
+ match &def.tools {
+ ToolScope::Wildcard => ToolScopeSpec::Wildcard,
+ ToolScope::Named(names) => ToolScopeSpec::Named(names.clone()),
+ }
+ } else {
+ ToolScopeSpec::Wildcard
+ }
+ }) {
ToolScopeSpec::Wildcard => ToolScope::Wildcard,
ToolScopeSpec::Named(names) => ToolScope::Named(names),
// Zero tools; the host's names join at session build.
@@ -197,7 +326,17 @@ impl AgentDefinitionSpec {
if let Some(rules) = self.tool_rules {
def.tool_rules = Some(rules);
}
- def.sandbox_mode = match self.sandbox {
+ def.sandbox_mode = match self.sandbox.unwrap_or({
+ if custom_base {
+ match def.sandbox_mode {
+ SandboxMode::None => SandboxModeSpec::None,
+ SandboxMode::ReadOnly => SandboxModeSpec::ReadOnly,
+ SandboxMode::Sandboxed => SandboxModeSpec::Sandboxed,
+ }
+ } else {
+ SandboxModeSpec::None
+ }
+ }) {
_ if host_only => SandboxMode::ReadOnly,
SandboxModeSpec::None => SandboxMode::None,
SandboxModeSpec::ReadOnly => SandboxMode::ReadOnly,
diff --git a/crates/openhuman-embed/src/agent/definition_tests.rs b/crates/openhuman-embed/src/agent/definition_tests.rs
index 4459156ca5..1d823bed56 100644
--- a/crates/openhuman-embed/src/agent/definition_tests.rs
+++ b/crates/openhuman-embed/src/agent/definition_tests.rs
@@ -91,3 +91,79 @@ fn tool_rules_reach_the_core_definition() {
.tool_rules
.is_none());
}
+
+#[test]
+fn template_overrides_are_independent_and_keep_restrictions() {
+ let template = AgentDefinitionSpec::new()
+ .system_prompt("shared")
+ .temperature(0.3)
+ .max_iterations(7)
+ .tools(ToolScopeSpec::Named(vec![
+ "read_file".into(),
+ "shell".into(),
+ ]));
+ let first = AgentDefinitionSpec::new()
+ .system_prompt("first")
+ .tools(ToolScopeSpec::Named(vec!["read_file".into()]))
+ .inherit(template.clone())
+ .unwrap()
+ .into_core("first")
+ .unwrap();
+ let second = AgentDefinitionSpec::new()
+ .temperature(0.8)
+ .inherit(template.clone())
+ .unwrap()
+ .into_core("second")
+ .unwrap();
+ assert!(matches!(first.system_prompt,PromptSource::Inline(ref p) if p=="first"));
+ assert!(matches!(second.system_prompt,PromptSource::Inline(ref p) if p=="shared"));
+ assert_eq!(first.temperature, 0.3);
+ assert_eq!(second.temperature, 0.8);
+ assert_eq!(second.max_iterations, 7);
+ assert!(AgentDefinitionSpec::new()
+ .tools(ToolScopeSpec::Wildcard)
+ .inherit(template)
+ .is_err());
+}
+#[test]
+fn base_can_be_named_or_custom_and_unknown_names_are_typed() {
+ let original = AgentDefinitionRegistry::builtins_only()
+ .get("planner")
+ .unwrap()
+ .clone();
+ let named = AgentDefinitionSpec::from_base("planner")
+ .into_core("my-planner")
+ .unwrap();
+ assert_eq!(named.agent_tier, original.agent_tier);
+ let custom = AgentDefinitionSpec::from_base(original.clone())
+ .into_core("my-custom")
+ .unwrap();
+ assert_eq!(
+ format!("{:?}", custom.tools),
+ format!("{:?}", original.tools)
+ );
+ assert_eq!(custom.max_iterations, original.max_iterations);
+ assert!(matches!(
+ AgentDefinitionSpec::from_base("does-not-exist").into_core("bad"),
+ Err(AgentError::UnknownDefinition(_))
+ ));
+}
+
+#[test]
+fn a_custom_base_does_not_allow_a_wider_tool_scope() {
+ let mut base = AgentDefinitionSpec::new()
+ .tools(ToolScopeSpec::Named(vec!["read_file".into()]))
+ .into_core("custom-base")
+ .unwrap();
+ base.sandbox_mode = SandboxMode::ReadOnly;
+ let def = AgentDefinitionSpec::from_base(base.clone())
+ .into_core("keeps-base")
+ .unwrap();
+ assert_eq!(def.sandbox_mode, SandboxMode::ReadOnly);
+ assert!(matches!(
+ AgentDefinitionSpec::from_base(base)
+ .tools(ToolScopeSpec::Wildcard)
+ .into_core("widens"),
+ Err(AgentError::WidensRuntime(_))
+ ));
+}
diff --git a/crates/openhuman-embed/src/agent/lifecycle.rs b/crates/openhuman-embed/src/agent/lifecycle.rs
index f1d3253b29..7d89b3c869 100644
--- a/crates/openhuman-embed/src/agent/lifecycle.rs
+++ b/crates/openhuman-embed/src/agent/lifecycle.rs
@@ -11,6 +11,7 @@ use crate::CoreError;
/// Turn admission and in-flight accounting for one agent.
pub(crate) struct Lifecycle {
removed: watch::Sender<bool>,
+ removal_claimed: AtomicBool,
in_flight: AtomicUsize,
idle: Notify,
torn_down: AtomicBool,
@@ -20,15 +21,28 @@ impl Lifecycle {
pub(crate) fn new() -> Self {
Self {
removed: watch::Sender::new(false),
+ removal_claimed: AtomicBool::new(false),
in_flight: AtomicUsize::new(0),
idle: Notify::new(),
torn_down: AtomicBool::new(false),
}
}
- /// Stops admitting turns and ends the ones in flight.
- pub(crate) fn mark_removed(&self) {
+ /// Stops admitting turns and ends the ones in flight; returns whether this
+ /// caller claimed removal before another caller.
+ pub(crate) fn mark_removed(&self) -> bool {
+ if self.removal_claimed.swap(true, Ordering::SeqCst) {
+ return false;
+ }
+ // A cancelled turn can retain the watch read while its future drops.
+ // Only the first claimant writes; repeated teardown never waits on it.
self.removed.send_replace(true);
+ true
+ }
+
+ /// Bind handles to this agent instance, even after its public id is reused.
+ pub(crate) fn removed(&self) -> watch::Receiver<bool> {
+ self.removed.subscribe()
}
/// Runs `turn` unless the agent was removed, ending it early with
diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rs
index 94ac25e200..e28a55ea4d 100644
--- a/crates/openhuman-embed/src/agent/mod.rs
+++ b/crates/openhuman-embed/src/agent/mod.rs
@@ -14,7 +14,9 @@
//! loader, DomainSet gate, tool-group filter and skill discovery all read
//! the ambient context.
+mod approval_handler;
mod approvals;
+pub use approval_handler::{ApprovalHandler, ApprovalSubscription};
mod attachments;
pub(crate) mod lifecycle;
pub use approvals::{ApprovalDecision, Approvals, ApprovalsError, PendingApproval};
@@ -24,7 +26,7 @@ mod definition;
mod layout;
pub(crate) mod spec;
-pub use definition::{AgentDefinitionSpec, SandboxModeSpec, ToolScopeSpec};
+pub use definition::{AgentDefinitionSpec, DefinitionBase, SandboxModeSpec, ToolScopeSpec};
pub use layout::AgentLayout;
pub use spec::{AgentSpec, MemoryBinding};
@@ -94,24 +96,35 @@ pub enum AgentError {
/// No live agent with this id is registered on the runtime.
#[error("no agent {0:?} is registered on this runtime")]
UnknownId(String),
+ /// A named template was not registered on this runtime.
+ #[error("unknown agent template {0:?}")]
+ UnknownTemplate(String),
+ /// A named built-in definition does not exist.
+ #[error("unknown built-in agent definition {0:?}")]
+ UnknownDefinition(String),
}
/// The assembled state behind an [`Agent`], shared by every clone of it and
/// by every [`Turn`] it issues.
pub(crate) struct AgentInner {
pub(crate) id: String,
+ /// A dead weak entry remains reserved until this instance finishes teardown.
+ registry: Arc<crate::runtime::AgentMap>,
+ pub(crate) overrides: Arc<openhuman_core::agent::host_overrides::HostOverrides>,
+ _approval_subscription: Option<ApprovalSubscription>,
pub(crate) runtime_id: String,
pub(crate) attachments: attachments::Attachments,
/// Keeps the runtime's core and (for an ephemeral workspace) its
/// directory alive for as long as this agent is, even after the host
/// drops its `Runtime` handle. See
/// [`CoreGuard`](crate::runtime::CoreGuard).
- _runtime_guard: Arc<crate::runtime::CoreGuard>,
+ pub(crate) _runtime_guard: Arc<crate::runtime::CoreGuard>,
pub(crate) runtime: Arc<CoreRuntime>,
pub(crate) ctx: Arc<CoreContext>,
pub(crate) config: Config,
pub(crate) definition: AgentDefinition,
pub(crate) provider: Provider,
+ pub(crate) model_defaults: crate::ModelDefaults,
pub(crate) access: Access,
pub(crate) layout: AgentLayout,
/// The agent's own in-process tools, rebuilt per turn. See
@@ -131,6 +144,12 @@ impl AgentInner {
if !self.lifecycle.begin_teardown() {
return;
}
+ self.lifecycle.mark_removed();
+ self._runtime_guard.events.emit(
+ Some(self.id.clone()),
+ None,
+ crate::RuntimeEventKind::AgentRemoved,
+ );
self.deny_approvals(resolution);
self.ctx.agent_state().clear();
if openhuman_core::mcp::host::take_agent_host(&self.config.workspace_dir, &self.id)
@@ -166,6 +185,13 @@ impl AgentInner {
impl Drop for AgentInner {
fn drop(&mut self) {
self.teardown("agent_dropped");
+ let mut agents = self.registry.lock().unwrap_or_else(|e| e.into_inner());
+ if agents
+ .get(&self.id)
+ .is_some_and(|current| std::ptr::eq(current.as_ptr(), self))
+ {
+ agents.remove(&self.id);
+ }
}
}
@@ -216,13 +242,40 @@ impl Agent {
if let Some(origin) = self.inner.access.turn_origin() {
turn = turn.origin(origin.clone());
}
+ if let Some(value) = self.inner.model_defaults.max_tokens {
+ turn = turn.max_tokens(value);
+ }
+ if let Some(value) = self.inner.model_defaults.top_p {
+ turn = turn.top_p(value);
+ }
turn
}
+ /// Start a streaming turn; dropping the stream requests cooperative cancellation.
+ pub fn stream(&self, message: impl Into<String>) -> crate::TurnStream {
+ self.turn(message).stream()
+ }
+
+ /// Subscribe a host callback to this agent’s pending approvals.
+ /// Removing the agent cancels its callbacks, even if its id is reused.
+ pub fn handle_approvals(&self, handler: Arc<dyn ApprovalHandler>) -> ApprovalSubscription {
+ ApprovalSubscription::new(self.id(), handler, self.inner.lifecycle.removed())
+ }
+
+ /// Add, replace, or remove an agent-local post-turn hook by name.
+ pub fn post_turn_hook(&self, name: &str, hook: Option<Arc<dyn crate::seams::PostTurnHook>>) {
+ self.inner.overrides.post_turn_hook(name, hook);
+ }
+
+ /// Add, replace, or remove an agent-local tool hook by name.
+ pub fn tool_hook(&self, name: &str, hook: Option<Arc<dyn crate::seams::ToolHook>>) {
+ self.inner.overrides.tool_hook(name, hook);
+ }
+
/// This agent's pending approvals: the requests its turns parked, and
/// only those.
pub fn approvals(&self) -> Approvals {
- Approvals::new(&self.inner.id)
+ Approvals::new(&self.inner.id, self.inner.lifecycle.removed())
}
/// The agent's read/write root for acting tools.
diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rs
index edc1d3c512..bcf21b2c19 100644
--- a/crates/openhuman-embed/src/agent/spec.rs
+++ b/crates/openhuman-embed/src/agent/spec.rs
@@ -34,8 +34,15 @@ pub(crate) enum SkillsDest {
/// Description of an agent to instantiate on a [`Runtime`](crate::Runtime).
pub struct AgentSpec {
id: String,
+ post_turn_hooks: Vec<std::sync::Arc<dyn crate::seams::PostTurnHook>>,
+ tool_hooks: Vec<std::sync::Arc<dyn crate::seams::ToolHook>>,
+ session_store: Option<std::sync::Arc<dyn crate::SessionStoreProvider>>,
+ approval_handler: Option<std::sync::Arc<dyn crate::ApprovalHandler>>,
definition: AgentDefinitionSpec,
+ template: Option<String>,
+ model_defaults: crate::ModelDefaults,
provider: Option<Provider>,
+ inherit_provider_route: bool,
access: Option<Access>,
tool_groups: Option<ToolGroups>,
domains: Option<DomainSet>,
@@ -45,7 +52,7 @@ pub struct AgentSpec {
skills_dir: Option<PathBuf>,
#[cfg(feature = "skills")]
skills_dest: SkillsDest,
- include_user_skills: bool,
+ include_user_skills: Option<bool>,
action_dir: Option<PathBuf>,
trusted: Vec<(String, TrustedAccess)>,
composio: Option<ComposioHostCredential>,
@@ -108,8 +115,15 @@ impl AgentSpec {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
+ post_turn_hooks: Vec::new(),
+ tool_hooks: Vec::new(),
+ session_store: None,
+ approval_handler: None,
definition: AgentDefinitionSpec::new(),
+ template: None,
+ model_defaults: crate::ModelDefaults::default(),
provider: None,
+ inherit_provider_route: false,
access: None,
tool_groups: None,
domains: None,
@@ -119,7 +133,7 @@ impl AgentSpec {
skills_dir: None,
#[cfg(feature = "skills")]
skills_dest: SkillsDest::AgentLocal,
- include_user_skills: false,
+ include_user_skills: None,
action_dir: None,
trusted: Vec::new(),
composio: None,
@@ -130,11 +144,46 @@ impl AgentSpec {
}
}
+ /// Register a post-turn hook local to this agent, in addition to runtime hooks.
+ pub fn post_turn_hook(mut self, hook: std::sync::Arc<dyn crate::seams::PostTurnHook>) -> Self {
+ self.post_turn_hooks.push(hook);
+ self
+ }
+
+ /// Register a tool hook local to this agent, in addition to runtime hooks.
+ pub fn tool_hook(mut self, hook: std::sync::Arc<dyn crate::seams::ToolHook>) -> Self {
+ self.tool_hooks.push(hook);
+ self
+ }
+
+ /// Override session storage for this agent; credentials and the bus remain shared.
+ pub fn session_store(mut self, store: std::sync::Arc<dyn crate::SessionStoreProvider>) -> Self {
+ self.session_store = Some(store);
+ self
+ }
+
+ /// Decide permissions through a callback rather than polling.
+ pub fn approval_handler(mut self, handler: std::sync::Arc<dyn crate::ApprovalHandler>) -> Self {
+ self.approval_handler = Some(handler);
+ self
+ }
+
/// The id given to [`new`](Self::new).
pub fn id(&self) -> &str {
&self.id
}
+ /// Extend a definition template registered on this runtime.
+ pub fn extends(mut self, template: impl Into<String>) -> Self {
+ self.template = Some(template.into());
+ self
+ }
+ /// Sampling defaults overriding the runtime; turn parameters override these.
+ pub fn model_defaults(mut self, defaults: crate::ModelDefaults) -> Self {
+ self.model_defaults = defaults;
+ self
+ }
+
/// What the agent is: prompt, tool scope, sandbox, iteration cap.
pub fn definition(mut self, definition: AgentDefinitionSpec) -> Self {
self.definition = definition;
@@ -152,11 +201,15 @@ impl AgentSpec {
/// runtime's API key when no route was given.
pub fn provider(mut self, provider: Provider) -> Self {
self.provider = Some(provider);
+ self.inherit_provider_route = false;
self
}
/// Pin the model without changing the route.
pub fn model(mut self, model: impl Into<String>) -> Self {
+ if self.provider.is_none() {
+ self.inherit_provider_route = true;
+ }
let provider = self.provider.take().unwrap_or_else(Provider::inherit);
self.provider = Some(provider.model(model));
self
@@ -215,7 +268,7 @@ impl AgentSpec {
/// embedded agent sees what its host installed, not what the machine's
/// user did.
pub fn include_user_skills(mut self, include: bool) -> Self {
- self.include_user_skills = include;
+ self.include_user_skills = Some(include);
self
}
@@ -358,8 +411,15 @@ impl AgentSpec {
pub(crate) fn into_parts(self) -> AgentSpecParts {
AgentSpecParts {
id: self.id,
+ post_turn_hooks: self.post_turn_hooks,
+ tool_hooks: self.tool_hooks,
+ session_store: self.session_store,
+ approval_handler: self.approval_handler,
definition: self.definition,
+ template: self.template,
+ model_defaults: self.model_defaults,
provider: self.provider,
+ inherit_provider_route: self.inherit_provider_route,
access: self.access,
tool_groups: self.tool_groups,
domains: self.domains,
@@ -384,8 +444,15 @@ impl AgentSpec {
/// The spec's fields, destructured for [`super::build::instantiate`].
pub(crate) struct AgentSpecParts {
pub(crate) id: String,
+ pub(crate) post_turn_hooks: Vec<std::sync::Arc<dyn crate::seams::PostTurnHook>>,
+ pub(crate) tool_hooks: Vec<std::sync::Arc<dyn crate::seams::ToolHook>>,
+ pub(crate) session_store: Option<std::sync::Arc<dyn crate::SessionStoreProvider>>,
+ pub(crate) approval_handler: Option<std::sync::Arc<dyn crate::ApprovalHandler>>,
pub(crate) definition: AgentDefinitionSpec,
+ pub(crate) template: Option<String>,
+ pub(crate) model_defaults: crate::ModelDefaults,
pub(crate) provider: Option<Provider>,
+ pub(crate) inherit_provider_route: bool,
pub(crate) access: Option<Access>,
pub(crate) tool_groups: Option<ToolGroups>,
pub(crate) domains: Option<DomainSet>,
@@ -395,7 +462,7 @@ pub(crate) struct AgentSpecParts {
pub(crate) skills_dir: Option<PathBuf>,
#[cfg(feature = "skills")]
pub(crate) skills_dest: SkillsDest,
- pub(crate) include_user_skills: bool,
+ pub(crate) include_user_skills: Option<bool>,
pub(crate) action_dir: Option<PathBuf>,
pub(crate) trusted: Vec<(String, TrustedAccess)>,
pub(crate) composio: Option<ComposioHostCredential>,
diff --git a/crates/openhuman-embed/src/config.rs b/crates/openhuman-embed/src/config.rs
index bdd7538914..6990e17108 100644
--- a/crates/openhuman-embed/src/config.rs
+++ b/crates/openhuman-embed/src/config.rs
@@ -6,7 +6,7 @@
//! 1. A borrowed newtype over `&Arc<CoreRuntime>` — zero-cost, no state.
//! 2. Facade-owned serde types, so hosts never name a domain's internal type
//! and never touch `serde_json::Value`.
-//! 3. Two-line methods delegating to [`call`](super::call::call).
+//! 3. Two-line methods delegating to `call`.
//!
//! Config is deliberately first because it is registered under
//! `DomainGroup::Platform`, which every preset enables — so a failure here is
@@ -53,7 +53,7 @@ impl Config<'_> {
///
/// Note this method always travels wrapped in the `{"result", "logs"}`
/// envelope, because its handler emits a log unconditionally. That is
- /// handled in [`call`](super::call::call) and is invisible here — which is
+ /// handled in `call` and is invisible here — which is
/// the entire point of routing every method through one helper.
pub async fn runtime_flags(&self) -> Result<RuntimeFlags, CoreError> {
call(
@@ -65,6 +65,15 @@ impl Config<'_> {
}
}
+/// Shared declarative tool-rule vocabulary used by the typed runtime builder.
+pub use tinytools::{
+ DefaultEffect, Patterns, RuleEffect, Surface, ToolMatcher, ToolRule, ToolRules,
+};
+
+/// Typed runtime builder policy groups from the core configuration contract.
+pub use openhuman_core::config::schema::{
+ AutonomyConfig, CronConfig, PrivacyConfig, PrivacyMode, SecretsConfig,
+};
/// The core's config type, as [`crate::RuntimeConfig`].
pub use openhuman_core::config::Config as RuntimeConfig;
diff --git a/crates/openhuman-embed/src/error.rs b/crates/openhuman-embed/src/error.rs
index ad42eb1e55..e695cacb2f 100644
--- a/crates/openhuman-embed/src/error.rs
+++ b/crates/openhuman-embed/src/error.rs
@@ -88,7 +88,7 @@ pub enum CoreError {
/// The route would transmit a bearer credential over a non-TLS channel.
///
- /// A [`super::agent::Route`] that names an `http://` (or other non-HTTPS)
+ /// A [`crate::Route`] that names an `http://` (or other non-HTTPS)
/// endpoint while carrying an `api_key` is refused before any request is
/// sent, so the credential can never ride cleartext on the wire.
#[error("{method}: refusing to send a bearer credential over a non-HTTPS route ({endpoint})")]
diff --git a/crates/openhuman-embed/src/events.rs b/crates/openhuman-embed/src/events.rs
new file mode 100644
index 0000000000..5a2dd8162e
--- /dev/null
+++ b/crates/openhuman-embed/src/events.rs
@@ -0,0 +1,318 @@
+//! Content-free runtime observations with bounded, explicit backpressure.
+
+use futures_core::Stream;
+use openhuman_core::core::bus::{EventHandler, SubscriptionHandle, BUS};
+use openhuman_core::core::events::DomainEvent;
+use serde::{Deserialize, Serialize};
+use std::collections::{BTreeMap, BTreeSet};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex, Weak};
+use std::task::{Context, Poll};
+use tokio::sync::broadcast;
+use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream};
+
+/// Metadata about one runtime transition; never includes user/tool payloads.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct RuntimeEvent {
+ /// Monotonically increasing sequence within this runtime.
+ pub sequence: u64,
+ /// The agent responsible for the transition, when one is known.
+ pub agent_id: Option<String>,
+ /// Unique id for this call, separate from its durable conversation id.
+ pub turn_id: Option<String>,
+ /// The transition being observed.
+ pub kind: RuntimeEventKind,
+}
+
+/// Content-free transitions published by the embedding runtime.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum RuntimeEventKind {
+ /// An agent was registered.
+ AgentAdded,
+ /// An agent was removed or its final handle dropped.
+ AgentRemoved,
+ /// A host turn started.
+ TurnStarted,
+ /// A host turn ended, including errors and cancellation.
+ TurnEnded {
+ /// Whether the turn returned a successful outcome.
+ success: bool,
+ },
+ /// A tool started, without its arguments.
+ ToolStarted {
+ /// The declared tool name.
+ tool_name: String,
+ },
+ /// A tool ended, without its result.
+ ToolEnded {
+ /// The declared tool name.
+ tool_name: String,
+ /// Whether execution succeeded.
+ success: bool,
+ },
+ /// A tool is waiting for the host's permission.
+ ApprovalRequested {
+ /// Opaque approval request identifier.
+ request_id: String,
+ },
+ /// A pending permission was decided.
+ ApprovalDecided {
+ /// Opaque approval request identifier.
+ request_id: String,
+ /// Stable decision classification.
+ decision: String,
+ },
+ /// Background services were started or stopped.
+ ServicesChanged {
+ /// Whether the selected services are running.
+ running: bool,
+ },
+}
+
+/// A subscriber fell behind the runtime's bounded event buffer.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+pub enum EventStreamError {
+ /// These events were overwritten; resynchronise using runtime inspection.
+ #[error("runtime event subscriber missed {0} events")]
+ Lagged(u64),
+ /// The runtime and all of its agents have been dropped.
+ #[error("runtime event stream closed")]
+ Closed,
+}
+
+/// A runtime event subscription; lag is reported rather than hidden.
+pub struct RuntimeEvents {
+ inner: BroadcastStream<RuntimeEvent>,
+}
+impl RuntimeEvents {
+ /// Receive the next event, or an explicit lag/closure error.
+ pub async fn recv(&mut self) -> Result<RuntimeEvent, EventStreamError> {
+ std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx))
+ .await
+ .unwrap_or(Err(EventStreamError::Closed))
+ }
+}
+impl Stream for RuntimeEvents {
+ type Item = Result<RuntimeEvent, EventStreamError>;
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
+ Pin::new(&mut self.inner).poll_next(cx).map(|item| {
+ item.map(|result| {
+ result.map_err(|BroadcastStreamRecvError::Lagged(n)| EventStreamError::Lagged(n))
+ })
+ })
+ }
+}
+
+#[derive(Default)]
+struct HubState {
+ sequence: u64,
+ agents: BTreeSet<String>,
+ active: BTreeMap<(String, String), BTreeSet<String>>,
+ // Retain correlation until the decision arrives, even if the turn already
+ // ended: the core bus delivers events asynchronously.
+ approvals: BTreeMap<String, (String, Option<String>)>,
+}
+
+pub(crate) struct EventHub {
+ sender: broadcast::Sender<RuntimeEvent>,
+ state: Mutex<HubState>,
+ subscription: Mutex<Option<SubscriptionHandle>>,
+}
+impl EventHub {
+ pub(crate) fn new(capacity: usize) -> Arc<Self> {
+ let (sender, _) = broadcast::channel(capacity.max(1));
+ let hub = Arc::new(Self {
+ sender,
+ state: Mutex::new(HubState::default()),
+ subscription: Mutex::new(None),
+ });
+ *hub.subscription
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) =
+ BUS.subscribe(Arc::new(ApprovalEvents(Arc::downgrade(&hub))));
+ hub
+ }
+ pub(crate) fn subscribe(&self) -> RuntimeEvents {
+ RuntimeEvents {
+ inner: BroadcastStream::new(self.sender.subscribe()),
+ }
+ }
+ fn publish(
+ &self,
+ state: &mut HubState,
+ agent_id: Option<String>,
+ turn_id: Option<String>,
+ kind: RuntimeEventKind,
+ ) {
+ state.sequence += 1;
+ let _ = self.sender.send(RuntimeEvent {
+ sequence: state.sequence,
+ agent_id,
+ turn_id,
+ kind,
+ });
+ }
+ pub(crate) fn emit(
+ &self,
+ agent_id: Option<String>,
+ turn_id: Option<String>,
+ kind: RuntimeEventKind,
+ ) {
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(agent) = &agent_id {
+ match kind {
+ RuntimeEventKind::AgentAdded => {
+ state.agents.insert(agent.clone());
+ }
+ RuntimeEventKind::AgentRemoved => {
+ state.agents.remove(agent);
+ state.active.retain(|(owner, _), _| owner != agent);
+ state.approvals.retain(|_, (owner, _)| owner != agent);
+ }
+ _ => {}
+ }
+ }
+ self.publish(&mut state, agent_id, turn_id, kind);
+ }
+ pub(crate) fn begin_turn(&self, agent_id: Option<String>, thread_id: &str) -> String {
+ let turn_id = format!("turn-{}", uuid::Uuid::new_v4());
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(agent) = &agent_id {
+ state
+ .active
+ .entry((agent.clone(), thread_id.to_owned()))
+ .or_default()
+ .insert(turn_id.clone());
+ }
+ self.publish(
+ &mut state,
+ agent_id,
+ Some(turn_id.clone()),
+ RuntimeEventKind::TurnStarted,
+ );
+ turn_id
+ }
+ pub(crate) fn end_turn(
+ &self,
+ agent_id: Option<String>,
+ thread_id: &str,
+ turn_id: &str,
+ success: bool,
+ ) {
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(agent) = &agent_id {
+ let key = (agent.clone(), thread_id.to_owned());
+ if let Some(turns) = state.active.get_mut(&key) {
+ turns.remove(turn_id);
+ if turns.is_empty() {
+ state.active.remove(&key);
+ }
+ }
+ }
+ self.publish(
+ &mut state,
+ agent_id,
+ Some(turn_id.to_owned()),
+ RuntimeEventKind::TurnEnded { success },
+ );
+ }
+ fn approval(
+ &self,
+ agent_id: &Option<String>,
+ thread_id: &Option<String>,
+ request_id: &str,
+ decision: Option<&str>,
+ ) {
+ let Some(agent) = agent_id else {
+ return;
+ };
+ let mut state = self
+ .state
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !state.agents.contains(agent) {
+ return;
+ }
+ let active = thread_id
+ .as_ref()
+ .and_then(|thread| state.active.get(&(agent.clone(), thread.clone())))
+ .and_then(|turns| {
+ // The wire event names a conversation, not a call. Concurrent calls
+ // in one conversation cannot be distinguished safely.
+ (turns.len() == 1)
+ .then(|| turns.iter().next().cloned())
+ .flatten()
+ });
+ let (turn_id, kind) = match decision {
+ Some(decision) => {
+ let turn = state
+ .approvals
+ .remove(request_id)
+ .filter(|(owner, _)| owner == agent)
+ .map(|(_, turn)| turn)
+ .unwrap_or(active);
+ (
+ turn,
+ RuntimeEventKind::ApprovalDecided {
+ request_id: request_id.to_owned(),
+ decision: decision.to_owned(),
+ },
+ )
+ }
+ None => {
+ state
+ .approvals
+ .insert(request_id.to_owned(), (agent.clone(), active.clone()));
+ (
+ active,
+ RuntimeEventKind::ApprovalRequested {
+ request_id: request_id.to_owned(),
+ },
+ )
+ }
+ };
+ self.publish(&mut state, Some(agent.clone()), turn_id, kind);
+ }
+}
+struct ApprovalEvents(Weak<EventHub>);
+#[async_trait::async_trait]
+impl EventHandler<DomainEvent> for ApprovalEvents {
+ fn name(&self) -> &str {
+ "embed.runtime.approvals"
+ }
+ async fn handle(&self, event: &DomainEvent) {
+ let Some(hub) = self.0.upgrade() else {
+ return;
+ };
+ match event {
+ DomainEvent::ApprovalRequested {
+ request_id,
+ agent_id,
+ thread_id,
+ ..
+ } => hub.approval(agent_id, thread_id, request_id, None),
+ DomainEvent::ApprovalDecided {
+ request_id,
+ decision,
+ agent_id,
+ thread_id,
+ ..
+ } => hub.approval(agent_id, thread_id, request_id, Some(decision)),
+ _ => {}
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "events_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-embed/src/events_tests.rs b/crates/openhuman-embed/src/events_tests.rs
new file mode 100644
index 0000000000..6088b105d9
--- /dev/null
+++ b/crates/openhuman-embed/src/events_tests.rs
@@ -0,0 +1,169 @@
+use super::*;
+
+#[tokio::test]
+async fn event_order_is_stable_and_lag_is_visible() {
+ let hub = EventHub::new(2);
+ let mut events = hub.subscribe();
+ for _ in 0..4 {
+ hub.emit(
+ Some("a".into()),
+ Some("t".into()),
+ RuntimeEventKind::TurnStarted,
+ );
+ }
+ assert_eq!(events.recv().await, Err(EventStreamError::Lagged(2)));
+ assert_eq!(events.recv().await.unwrap().sequence, 3);
+ assert_eq!(events.recv().await.unwrap().sequence, 4);
+ drop(hub);
+ assert_eq!(events.recv().await, Err(EventStreamError::Closed));
+}
+
+#[test]
+fn observations_serialize_only_metadata() {
+ let event = RuntimeEvent {
+ sequence: 1,
+ agent_id: Some("a".into()),
+ turn_id: Some("t".into()),
+ kind: RuntimeEventKind::ToolStarted {
+ tool_name: "read".into(),
+ },
+ };
+ let value = serde_json::to_value(event).unwrap();
+ assert_eq!(value["kind"]["kind"], "tool_started");
+ assert!(value.get("arguments").is_none());
+ assert!(value.get("message").is_none());
+}
+
+fn requested(agent: Option<&str>, thread: Option<&str>, id: &str) -> DomainEvent {
+ DomainEvent::ApprovalRequested {
+ request_id: id.into(),
+ tool_name: "write".into(),
+ action_summary: "safe summary".into(),
+ args_redacted: serde_json::Value::Null,
+ thread_id: thread.map(str::to_owned),
+ client_id: None,
+ tool_call_id: None,
+ expires_at: None,
+ agent_id: agent.map(str::to_owned),
+ }
+}
+
+fn no_event(events: &mut RuntimeEvents) {
+ let mut context = Context::from_waker(std::task::Waker::noop());
+ assert!(Pin::new(events).poll_next(&mut context).is_pending());
+}
+
+#[tokio::test]
+async fn global_approvals_are_visible_only_for_this_runtimes_registered_agents() {
+ let hub = EventHub::new(16);
+ hub.emit(Some("local".into()), None, RuntimeEventKind::AgentAdded);
+ let mut events = hub.subscribe();
+ let handler = ApprovalEvents(Arc::downgrade(&hub));
+ handler
+ .handle(&requested(
+ Some("foreign"),
+ Some("thread"),
+ "foreign-request",
+ ))
+ .await;
+ handler
+ .handle(&requested(None, Some("thread"), "operator-request"))
+ .await;
+ no_event(&mut events);
+ handler
+ .handle(&requested(Some("local"), Some("thread"), "local-request"))
+ .await;
+ assert!(
+ matches!(events.recv().await.unwrap().kind, RuntimeEventKind::ApprovalRequested { request_id } if request_id == "local-request")
+ );
+}
+
+fn decided(agent: &str, thread: &str, id: &str) -> DomainEvent {
+ DomainEvent::ApprovalDecided {
+ request_id: id.into(),
+ tool_name: "write".into(),
+ decision: "approve_once".into(),
+ thread_id: Some(thread.into()),
+ client_id: None,
+ tool_call_id: None,
+ resolution: None,
+ agent_id: Some(agent.into()),
+ }
+}
+
+#[tokio::test]
+async fn repeated_conversation_calls_have_unique_turn_ids_and_approvals_keep_origin() {
+ let hub = EventHub::new(16);
+ hub.emit(Some("a".into()), None, RuntimeEventKind::AgentAdded);
+ let mut events = hub.subscribe();
+ let handler = ApprovalEvents(Arc::downgrade(&hub));
+ let first = hub.begin_turn(Some("a".into()), "thread");
+ assert_ne!(first, "thread");
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(first.as_str())
+ );
+ handler
+ .handle(&requested(Some("a"), Some("thread"), "approval-1"))
+ .await;
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(first.as_str())
+ );
+ hub.end_turn(Some("a".into()), "thread", &first, true);
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(first.as_str())
+ );
+ let second = hub.begin_turn(Some("a".into()), "thread");
+ assert_ne!(first, second);
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(second.as_str())
+ );
+ // A delayed decision for the first call must not be attributed to the second.
+ handler.handle(&decided("a", "thread", "approval-1")).await;
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(first.as_str())
+ );
+ handler
+ .handle(&requested(Some("a"), Some("thread"), "approval-2"))
+ .await;
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(second.as_str())
+ );
+}
+
+#[tokio::test]
+async fn concurrent_calls_in_one_thread_are_not_misattributed_and_removed_agents_are_filtered() {
+ let hub = EventHub::new(16);
+ hub.emit(Some("a".into()), None, RuntimeEventKind::AgentAdded);
+ let first = hub.begin_turn(Some("a".into()), "thread");
+ let second = hub.begin_turn(Some("a".into()), "thread");
+ let mut events = hub.subscribe();
+ let handler = ApprovalEvents(Arc::downgrade(&hub));
+ handler
+ .handle(&requested(Some("a"), Some("thread"), "ambiguous"))
+ .await;
+ assert_eq!(events.recv().await.unwrap().turn_id, None);
+ hub.end_turn(Some("a".into()), "thread", &second, false);
+ events.recv().await.unwrap();
+ handler
+ .handle(&requested(Some("a"), Some("thread"), "unique"))
+ .await;
+ assert_eq!(
+ events.recv().await.unwrap().turn_id.as_deref(),
+ Some(first.as_str())
+ );
+ hub.emit(Some("a".into()), None, RuntimeEventKind::AgentRemoved);
+ events.recv().await.unwrap();
+ handler
+ .handle(&requested(Some("a"), Some("thread"), "removed"))
+ .await;
+ handler.handle(&decided("a", "thread", "unique")).await;
+ no_event(&mut events);
+ assert!(hub.state.lock().unwrap().active.is_empty());
+ assert!(hub.state.lock().unwrap().approvals.is_empty());
+}
diff --git a/crates/openhuman-embed/src/harness/builder.rs b/crates/openhuman-embed/src/harness/builder.rs
index 00cd4e0c6d..5da75a5a80 100644
--- a/crates/openhuman-embed/src/harness/builder.rs
+++ b/crates/openhuman-embed/src/harness/builder.rs
@@ -102,7 +102,7 @@ impl HarnessBuilder {
/// Make the skill bundles in `dir` available to the agent.
///
/// The bundles are **copied** into the workspace's skills root — see the
- /// [`skills`](super::skills) module docs for why linking cannot work. Not
+ /// internal skill-copy module docs for why linking cannot work. Not
/// permitted with [`Workspace::Inherit`], which would leave them in the
/// operator's own install.
#[cfg(feature = "skills")]
@@ -171,7 +171,7 @@ impl HarnessBuilder {
/// Defaults to every group withheld, matching the desktop app. Reach for
/// [`ToolGroups::advertised`] when the host does its own routing and wants
/// native function calling instead of the `use_skill` envelope, and for
- /// [`ToolGroups::none`] plus [`with`](ToolGroups::with) when the embedding
+ /// [`crate::ToolGroups::none`] plus [`with`](crate::ToolGroups::with) when the embedding
/// product should not carry a family at all.
///
/// ```no_run
@@ -182,7 +182,7 @@ impl HarnessBuilder {
/// ```
///
/// [`ToolGroups::advertised`]: openhuman_core::tools::toolpacks::ToolGroups::advertised
- /// [`ToolGroups::none`]: openhuman_core::tools::toolpacks::ToolGroups::none
+ /// [`crate::ToolGroups::none`]: openhuman_core::tools::toolpacks::ToolGroups::none
/// [`ToolGroups::with`]: openhuman_core::tools::toolpacks::ToolGroups::with
pub fn tool_groups(
mut self,
diff --git a/crates/openhuman-embed/src/harness/error.rs b/crates/openhuman-embed/src/harness/error.rs
index 09df94e90d..3c4a2f2823 100644
--- a/crates/openhuman-embed/src/harness/error.rs
+++ b/crates/openhuman-embed/src/harness/error.rs
@@ -78,6 +78,9 @@ impl From<crate::RuntimeError> for HarnessError {
R::Invalid(msg) => Self::Invalid(msg),
R::BlankApiKey => Self::Invalid(err_text(&R::BlankApiKey)),
R::NoSessionStore => Self::Invalid(err_text(&R::NoSessionStore)),
+ R::MissingFeature { .. } | R::MissingStorageFeature { .. } => {
+ Self::Invalid(err_text(&err))
+ }
}
}
}
@@ -93,7 +96,9 @@ impl From<crate::AgentError> for HarnessError {
| A::WidensRuntime(_)
| A::ReservedId(_)
| A::AgentLimit { .. }
- | A::UnknownId(_) => Self::Invalid(err_text(&err)),
+ | A::UnknownId(_)
+ | A::UnknownTemplate(_)
+ | A::UnknownDefinition(_) => Self::Invalid(err_text(&err)),
A::Invalid(msg) => Self::Invalid(msg),
}
}
diff --git a/crates/openhuman-embed/src/harness/mod.rs b/crates/openhuman-embed/src/harness/mod.rs
index 667b9ce815..4a89a6b1e6 100644
--- a/crates/openhuman-embed/src/harness/mod.rs
+++ b/crates/openhuman-embed/src/harness/mod.rs
@@ -131,10 +131,12 @@ impl<'a> HarnessCore<'a> {
Self { core }
}
+ /// Read and update the runtime configuration.
pub fn config(&self) -> crate::Config<'_> {
self.core.config()
}
+ /// Manage the credential shared by agents on this runtime.
pub fn auth(&self) -> crate::Auth<'_> {
self.core.auth()
}
diff --git a/crates/openhuman-embed/src/harness/provider.rs b/crates/openhuman-embed/src/harness/provider.rs
index 54c1d537af..21ba6f5b85 100644
--- a/crates/openhuman-embed/src/harness/provider.rs
+++ b/crates/openhuman-embed/src/harness/provider.rs
@@ -19,13 +19,61 @@
use crate::turn::Route;
/// Where a harness sends its inference.
-#[derive(Debug, Clone, Default, PartialEq, Eq)]
+#[derive(Clone, Default)]
pub struct Provider {
route: Option<Route>,
model: Option<String>,
+ custom: Option<std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>>,
+ roles: std::collections::BTreeMap<
+ String,
+ std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
+ >,
}
impl Provider {
+ /// Use a native custom provider (including non-OpenAI transports).
+ pub fn custom(model: std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>) -> Self {
+ Self {
+ custom: Some(model),
+ ..Self::default()
+ }
+ }
+
+ /// Try native providers in order when inference fails before any output.
+ /// Validation errors and failures after streamed content never switch providers.
+ pub fn custom_with_fallback(
+ primary: std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
+ fallbacks: Vec<std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>>,
+ ) -> Self {
+ Self::custom(std::sync::Arc::new(
+ tinyinference_llm::model::FallbackModel::new(primary, fallbacks),
+ ))
+ }
+
+ /// Select a native provider for a workload role; unlisted roles keep the primary.
+ pub fn role(
+ mut self,
+ role: impl Into<String>,
+ model: std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
+ ) -> Self {
+ self.roles.insert(role.into(), model);
+ self
+ }
+
+ pub(crate) fn custom_model(
+ &self,
+ ) -> Option<std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>> {
+ self.custom.clone()
+ }
+ pub(crate) fn role_models(
+ &self,
+ ) -> &std::collections::BTreeMap<
+ String,
+ std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,
+ > {
+ &self.roles
+ }
+
/// Run on an OpenAI-compatible endpoint with the given bearer.
///
/// `base_url` is spelled as a provider endpoint would be —
@@ -38,6 +86,8 @@ impl Provider {
Self {
route: Some(Route::openai_compatible(base_url, api_key)),
model: None,
+ custom: None,
+ roles: Default::default(),
}
}
@@ -84,12 +134,43 @@ impl Provider {
/// normalization. Kept separate from [`Self::is_routed`], which describes
/// the caller's syntactic choice for diagnostics.
pub(crate) fn has_usable_route(&self) -> bool {
- self.route.as_ref().is_some_and(|route| {
- !route.base_url.trim().is_empty() && !route.api_key.trim().is_empty()
- })
+ self.custom.is_some()
+ || self.route.as_ref().is_some_and(|route| {
+ !route.base_url.trim().is_empty() && !route.api_key.trim().is_empty()
+ })
}
}
#[cfg(test)]
#[path = "provider_tests.rs"]
mod tests;
+
+impl std::fmt::Debug for Provider {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Provider")
+ .field("route", &self.route)
+ .field("model", &self.model)
+ .field("custom", &self.custom.is_some())
+ .field("roles", &self.roles.keys().collect::<Vec<_>>())
+ .finish()
+ }
+}
+impl PartialEq for Provider {
+ fn eq(&self, other: &Self) -> bool {
+ self.route == other.route
+ && self.model == other.model
+ && match (&self.custom, &other.custom) {
+ (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
+ (None, None) => true,
+ _ => false,
+ }
+ && self.roles.len() == other.roles.len()
+ && self.roles.iter().all(|(k, v)| {
+ other
+ .roles
+ .get(k)
+ .is_some_and(|w| std::sync::Arc::ptr_eq(v, w))
+ })
+ }
+}
+impl Eq for Provider {}
diff --git a/crates/openhuman-embed/src/harness/workspace.rs b/crates/openhuman-embed/src/harness/workspace.rs
index 1062790a0e..6240b9e4bc 100644
--- a/crates/openhuman-embed/src/harness/workspace.rs
+++ b/crates/openhuman-embed/src/harness/workspace.rs
@@ -70,7 +70,7 @@ impl Workspace {
///
/// `true` only for [`Workspace::Inherit`]. Guards the writes the harness
/// would otherwise make on the caller's behalf — see
- /// [`skills`](super::skills).
+ /// the internal skill-copy module.
pub fn is_operator_owned(&self) -> bool {
matches!(self, Self::Inherit)
}
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index 0ff7d09900..a2326ce9a4 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -8,7 +8,7 @@
//! MCP servers, skills, working directory, access tier, provider and
//! prompt. [`Harness`] is the one-agent shorthand over the same two types.
//! * **[`Core`]** — the typed facade over a [`CoreRuntime`] the host built
-//! itself with [`CoreBuilder`](openhuman_core::core::runtime::CoreBuilder).
+//! itself with [`CoreBuilder`].
//! [`CoreRuntime::invoke`] gives it JSON; this facade gives it real Rust
//! types, so a host never writes `serde_json::json!` or matches on an
//! error string.
@@ -54,10 +54,17 @@
//! `core.workflows()` simply does not exist in a build without that feature —
//! a compile error at the call site rather than a runtime surprise. For domains
//! present at compile time but switched off at runtime via
-//! [`DomainSet`](openhuman_core::core::runtime::DomainSet), calls return
+//! [`DomainSet`], calls return
//! [`CoreError::Unavailable`] so a host can hide the surface instead of
//! reporting a failure.
+// The owned streaming task proves Send for the core’s deeply nested turn future.
+#![recursion_limit = "256"]
+#![warn(missing_docs)]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+
+/// Complete definition accepted by [`AgentDefinitionSpec::from_base`].
+pub use openhuman_core::agent::harness::definition::AgentDefinition;
pub use openhuman_core::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
pub use openhuman_core::backend::{
install_backend_transport, installed_backend_transport, BackendRequest, BackendTransport,
@@ -72,7 +79,7 @@ pub use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};
// would build tools of a different, incompatible type.
pub use openhuman_core::agent::tinyagents::host::LastTurnUsage;
pub use openhuman_core::agent::{HostTools, HostTurnTools, TurnContext};
-pub use openhuman_core::tools::{Tool, ToolExposure};
+pub use openhuman_core::tools::{PermissionLevel, Tool, ToolExposure, ToolResult};
pub use openhuman_core::{
CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet, TokenSource,
};
@@ -138,7 +145,7 @@ pub use openhuman_core::voice::VOICE_COMPILED_IN;
pub use agent::ToolAttachmentError;
pub use agent::{
Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, ApprovalDecision, Approvals,
- ApprovalsError, MemoryBinding, PendingApproval, SandboxModeSpec, ToolScopeSpec,
+ ApprovalsError, DefinitionBase, MemoryBinding, PendingApproval, SandboxModeSpec, ToolScopeSpec,
};
pub use auth::{Auth, AuthState, Session};
#[cfg(feature = "channels")]
@@ -166,7 +173,9 @@ pub use runtime::builder::DEFAULT_MAX_AGENTS;
#[doc(hidden)]
pub use runtime::BuilderSummary;
pub use runtime::{
- run_from_args, ApiKey, ConfigSource, RemoveAgent, Runtime, RuntimeBuilder, RuntimeError,
+ run_from_args, AgentDefaults, ApiKey, ConfigSource, ConfigurationInfo, DefaultsInfo,
+ LearningSettings, ModelDefaults, RemoveAgent, Runtime, RuntimeBuilder, RuntimeDefaults,
+ RuntimeError, RuntimeInfo, RuntimeModule, SkillsPolicy, StorageInfo, WeightClass,
};
/// The types the [`RuntimeBuilder`] seam options take: controller
@@ -181,7 +190,7 @@ pub mod seams {
pub use openhuman_core::core::all::{ControllerExtension, DomainGroup};
pub use openhuman_core::core::server_launcher::{HostBoot, ServeRequest, ServerLauncher};
pub use openhuman_core::security::SecurityPolicy;
- pub use openhuman_core::storage::StorageBackend;
+ pub use openhuman_core::storage::{CollectionSpec, Precondition, Scope, StorageBackend};
pub use crate::runtime::StorageSource;
}
@@ -246,7 +255,7 @@ impl Core {
/// Typed access to the session store.
///
/// Use this when the embedded workload calls authenticated TinyHumans
- /// backend services. A [`HostKind::Library`](openhuman_core::core::types::HostKind::Library)
+ /// backend services. A [`HostKind::Library`]
/// runtime does not need an app session for caller-supplied inference.
pub fn auth(&self) -> Auth<'_> {
Auth(&self.rt)
@@ -285,3 +294,22 @@ impl std::fmt::Debug for Core {
f.debug_struct("Core").finish_non_exhaustive()
}
}
+
+/// 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 --git a/crates/openhuman-embed/src/process.rs b/crates/openhuman-embed/src/process.rs
index 25a04c054e..44120705b5 100644
--- a/crates/openhuman-embed/src/process.rs
+++ b/crates/openhuman-embed/src/process.rs
@@ -11,7 +11,9 @@ use std::path::{Path, PathBuf};
pub use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
+/// Sentry options and event scrubbing shared by desktop and terminal hosts.
#[cfg(feature = "crash-reporting")]
+#[cfg_attr(docsrs, doc(cfg(feature = "crash-reporting")))]
#[path = "process_sentry.rs"]
pub mod sentry;
diff --git a/crates/openhuman-embed/src/profiles.rs b/crates/openhuman-embed/src/profiles.rs
index 7c9d9c2ad9..0332e1704b 100644
--- a/crates/openhuman-embed/src/profiles.rs
+++ b/crates/openhuman-embed/src/profiles.rs
@@ -46,7 +46,7 @@
//! is alive the profile counts as **in use**: idle eviction skips it and
//! [`ProfileRuntime::release`] refuses it, exactly as for a gateway request
//! still in flight. Every call on it runs under the profile's own
-//! [`CoreContext`], so the per-user isolation (workspace, session store,
+//! `CoreContext`, so the per-user isolation (workspace, session store,
//! security policy, `/events` stamping, the `USER_METHODS` surface) is the
//! one the gateway gets. Drop the handles to let the profile go idle.
@@ -100,7 +100,9 @@ pub enum ProfileError {
/// channel would show; `error_type` its stable classification.
#[error("turn failed: {message}")]
Turn {
+ /// User-facing explanation of the failed turn.
message: String,
+ /// Optional stable error classification returned by the host.
error_type: Option<String>,
},
/// The turn was cancelled before it answered.
diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs
index c8fb92ca4e..384d525df7 100644
--- a/crates/openhuman-embed/src/runtime/build.rs
+++ b/crates/openhuman-embed/src/runtime/build.rs
@@ -78,10 +78,38 @@ impl RuntimeBuilder {
/// Refuse combinations the chosen [`ConfigSource`] cannot honour.
pub(super) fn validate(&self) -> Result<(), RuntimeError> {
+ self.validate_modules()?;
+ if self.agent_defaults.skills.root.is_some() && !cfg!(feature = "skills") {
+ return Err(RuntimeError::Invalid(
+ "copying runtime skill bundles requires Cargo feature `openhuman-embed/skills`"
+ .into(),
+ ));
+ }
+
+ validate_storage_feature(self.seams.storage.as_ref())?;
+ if self.seams.storage.is_none() {
+ if let Some(config) = &self.config {
+ if let Some(url) = openhuman_core::storage::configured_url(config) {
+ validate_storage_feature(Some(&super::StorageSource::Url(url)))?;
+ }
+ }
+ }
+ self.agent_defaults
+ .model
+ .validate()
+ .map_err(RuntimeError::Invalid)?;
if self.api_key.as_ref().is_some_and(ApiKey::is_blank) {
return Err(RuntimeError::BlankApiKey);
}
- if matches!(self.workspace, Workspace::Stateless) && self.session_store.is_none() {
+ if matches!(self.workspace, Workspace::Stateless)
+ && self.session_store.is_none()
+ && self.seams.storage.is_none()
+ && self
+ .config
+ .as_ref()
+ .and_then(openhuman_core::storage::configured_url)
+ .is_none()
+ {
return Err(RuntimeError::NoSessionStore);
}
if self.config_source == ConfigSource::Discovered {
@@ -98,6 +126,7 @@ impl RuntimeBuilder {
("workspace_dir", self.workspace_dir.is_some()),
("action_dir", self.action_dir.is_some()),
("api_key", self.api_key.is_some()),
+ ("typed configuration", self.config_knobs.is_set()),
];
if let Some((knob, _)) = edits.iter().find(|(_, set)| *set) {
return Err(RuntimeError::Invalid(format!(
@@ -130,11 +159,35 @@ impl RuntimeBuilder {
// build cannot undo (the stored API key, the host memory engine), so
// a refused controller extension leaves neither behind. Restorable
// seams are undone by this guard if the boot below fails.
+ let mut storage_info = super::StorageInfo::describe(
+ self.seams.storage.as_ref(),
+ config.as_ref().unwrap_or(&Config::default()),
+ );
let mut host_seams = std::mem::take(&mut self.seams);
+ if host_seams.storage.is_none() {
+ if let Some(config) = &config {
+ if let Some(url) = openhuman_core::storage::configured_url(config) {
+ host_seams.storage = Some(super::StorageSource::Url(url));
+ }
+ }
+ }
+ validate_storage_feature(host_seams.storage.as_ref())?;
host_seams
.open_storage()
.await
.map_err(RuntimeError::Invalid)?;
+ let storage_backend = match &host_seams.storage {
+ Some(super::StorageSource::Backend(backend)) => Some(backend.clone()),
+ _ => None,
+ };
+ if self.session_store.is_none() {
+ if let Some(backend) = &storage_backend {
+ let stores = tinyagents_session::DriverSessionStores::new(backend.clone())
+ .map_err(|e| RuntimeError::Build(e.into()))?
+ .recover_on_open(!openhuman_core::storage::driver_is_shared(backend.driver()));
+ self.session_store = Some(Arc::new(stores));
+ }
+ }
let mut seams = host_seams.install().map_err(RuntimeError::Invalid)?;
// Before `CoreBuilder::build()`: the scheduler gate reads the credential
@@ -213,6 +266,16 @@ impl RuntimeBuilder {
RuntimeError::Build(error)
})?;
let core = Core::from_runtime(Arc::new(runtime));
+ let storage_backend = storage_backend.or_else(openhuman_core::storage::installed);
+ if !storage_info.configured {
+ if let Some(backend) = &storage_backend {
+ storage_info = super::StorageInfo {
+ source: "backend".into(),
+ driver: Some(backend.driver().into()),
+ configured: true,
+ };
+ }
+ }
// Discovered: agents start from the config the core just loaded.
let (mut base_config, config_unavailable) = match config.take() {
@@ -221,6 +284,13 @@ impl RuntimeBuilder {
};
if discovered {
// Agent defaults only — the core's own config is not edited.
+ self.config_knobs.apply(&mut base_config);
+ if let Some(value) = self.agent_defaults.model.temperature {
+ base_config.default_temperature = value;
+ }
+ if let Some(value) = self.agent_defaults.model.max_iterations {
+ base_config.agent.max_tool_iterations_override = Some(value);
+ }
self.access.apply(&mut base_config);
apply_provider(&mut base_config, &self.provider);
}
@@ -247,6 +317,7 @@ impl RuntimeBuilder {
let previous_session_store = session_store_cleanup.previous.take();
log::debug!("[embed][runtime] built host_kind={host_kind:?}");
+ let defaults = self.resolved_defaults(&base_config, domains, tool_groups.clone());
let runtime = Runtime::new(
core,
resolved,
@@ -258,9 +329,12 @@ impl RuntimeBuilder {
inherit,
domains,
tool_groups,
- self.provider,
- self.access,
self.max_agents,
+ defaults,
+ host_kind,
+ self.selection,
+ storage_info,
+ storage_backend,
);
if requests_background_services(services) {
log::debug!("[embed][runtime] starting background services {services:?}");
@@ -269,6 +343,56 @@ impl RuntimeBuilder {
Ok(runtime)
}
+ pub(super) fn resolved_defaults(
+ &self,
+ config: &Config,
+ domains: crate::DomainSet,
+ tool_groups: crate::ToolGroups,
+ ) -> super::AgentDefaults {
+ let mut defaults = self.agent_defaults.clone();
+ defaults.provider = self.provider.clone();
+ if defaults.provider.model_id().is_none() {
+ if let Some(model) = &config.default_model {
+ defaults.provider = defaults.provider.model(model);
+ }
+ }
+
+ defaults.access = self.access.clone();
+ defaults.domains = domains;
+ defaults.tool_groups = tool_groups;
+ let definition_model = defaults.definition.explicit_model_defaults();
+ defaults.model.temperature = defaults
+ .model
+ .temperature
+ .or(definition_model.temperature)
+ .or(Some(config.default_temperature));
+ defaults.model.max_iterations = defaults
+ .model
+ .max_iterations
+ .or(definition_model.max_iterations)
+ .or(config.agent.max_tool_iterations_override);
+ if let Ok(definition) = defaults.definition.clone().into_core("runtime-defaults") {
+ defaults.model.max_iterations = defaults
+ .model
+ .max_iterations
+ .or(Some(definition.max_iterations));
+ if defaults.sandbox == crate::SandboxModeSpec::None {
+ defaults.sandbox = match definition.sandbox_mode {
+ openhuman_core::agent::harness::definition::SandboxMode::None => {
+ crate::SandboxModeSpec::None
+ }
+ openhuman_core::agent::harness::definition::SandboxMode::ReadOnly => {
+ crate::SandboxModeSpec::ReadOnly
+ }
+ openhuman_core::agent::harness::definition::SandboxMode::Sandboxed => {
+ crate::SandboxModeSpec::Sandboxed
+ }
+ };
+ }
+ }
+ defaults
+ }
+
/// The config a [`ConfigSource::Resolved`] runtime hands the core.
async fn resolve_config(
&mut self,
@@ -304,6 +428,13 @@ impl RuntimeBuilder {
if let Some(url) = self.backend_url.clone() {
config.api_url = Some(url);
}
+ self.config_knobs.apply(&mut config);
+ if let Some(temperature) = self.agent_defaults.model.temperature {
+ config.default_temperature = temperature;
+ }
+ if let Some(iterations) = self.agent_defaults.model.max_iterations {
+ config.agent.max_tool_iterations_override = Some(iterations);
+ }
self.access.apply(&mut config);
apply_provider(&mut config, &self.provider);
Ok(config)
@@ -339,12 +470,13 @@ async fn discovered_base_config() -> (Config, Option<String>) {
/// provider is applied to the agents' base config after boot, so it is judged
/// by the model it carries itself.
pub(crate) fn routed_provider_effective(provider: &Provider, config: Option<&Config>) -> bool {
- provider.has_usable_route()
- && match config {
- Some(config) => config.default_model.as_deref(),
- None => provider.model_id(),
- }
- .is_some_and(|model| !model.trim().is_empty())
+ provider.custom_model().is_some()
+ || (provider.has_usable_route()
+ && match config {
+ Some(config) => config.default_model.as_deref(),
+ None => provider.model_id(),
+ }
+ .is_some_and(|model| !model.trim().is_empty()))
}
fn store_api_key(config: &Config, key: &ApiKey) -> Result<(), RuntimeError> {
@@ -402,3 +534,26 @@ pub(crate) fn apply_provider(config: &mut Config, provider: &Provider) {
config.default_model = Some(model.to_string());
}
}
+
+/// Fail before opening a URL whose driver is absent; credential text never enters the error.
+fn validate_storage_feature(source: Option<&super::StorageSource>) -> Result<(), RuntimeError> {
+ let Some(super::StorageSource::Url(url)) = source else {
+ return Ok(());
+ };
+ let driver = openhuman_core::storage::StorageUrl::parse(url)
+ .map_err(|_| RuntimeError::Invalid("invalid storage URL".into()))?
+ .driver()
+ .to_string();
+ let feature = match driver.as_str() {
+ "sqlite" => Some("storage-sqlite"),
+ "mongodb" => Some("storage-mongodb"),
+ "file" => Some("storage-file"),
+ _ => None,
+ };
+ if let Some(feature) = feature {
+ if !openhuman_core::core::runtime::compiled_features()[feature] {
+ return Err(RuntimeError::MissingStorageFeature { driver, feature });
+ }
+ }
+ Ok(())
+}
diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rs
index 3973965744..3127c514d2 100644
--- a/crates/openhuman-embed/src/runtime/builder.rs
+++ b/crates/openhuman-embed/src/runtime/builder.rs
@@ -66,12 +66,12 @@ pub enum ConfigSource {
/// would edit a config (`config`, `backend_url`, `workspace_dir`,
/// `action_dir`, `api_key`), because there is no config in hand to edit.
/// [`RuntimeBuilder::access`] and [`RuntimeBuilder::provider`] then only
- /// set the defaults of agents created with [`Runtime::agent`](super::Runtime::agent).
+ /// set the defaults of agents created with [`crate::Runtime::agent`](super::Runtime::agent).
Discovered,
}
/// Builder for a [`Runtime`](super::Runtime). Obtain with
-/// [`Runtime::builder`](super::Runtime::builder) or one of the host presets
+/// [`crate::Runtime::builder`](super::Runtime::builder) or one of the host presets
/// ([`RuntimeBuilder::library`], [`desktop`](RuntimeBuilder::desktop),
/// [`cli`](RuntimeBuilder::cli), [`tui`](RuntimeBuilder::tui)).
pub struct RuntimeBuilder {
@@ -97,6 +97,9 @@ pub struct RuntimeBuilder {
pub(super) session_store: Option<Arc<dyn SessionStoreProvider>>,
pub(super) seams: HostSeams,
pub(super) max_agents: usize,
+ pub(super) agent_defaults: super::AgentDefaults,
+ pub(super) config_knobs: super::info::ConfigKnobs,
+ pub(super) selection: Option<super::ModuleSelection>,
}
/// Live agents a runtime hosts unless [`RuntimeBuilder::max_agents`] says
@@ -138,9 +141,78 @@ impl RuntimeBuilder {
session_store: None,
seams: HostSeams::default(),
max_agents: DEFAULT_MAX_AGENTS,
+ agent_defaults: super::AgentDefaults::default(),
+ config_knobs: super::info::ConfigKnobs::default(),
+ selection: None,
}
}
+ /// Replace the runtime-wide agent defaults. Explicit individual setters still win.
+ pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self {
+ self.provider = defaults.provider.clone();
+ self.access = defaults.access.clone();
+ self.domains = Some(defaults.domains);
+ self.tool_groups = Some(defaults.tool_groups.clone());
+ self.agent_defaults = defaults;
+ self
+ }
+ /// Sampling defaults inherited by agents and then overridden per turn.
+ pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self {
+ self.agent_defaults.model = model;
+ self
+ }
+ /// Default confinement for new agents.
+ pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self {
+ self.agent_defaults.sandbox = mode;
+ self
+ }
+ /// Default definition extended by each agent.
+ pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self {
+ self.agent_defaults.definition = definition;
+ self
+ }
+ /// Runtime-wide skill installation and discovery policy.
+ pub fn skills(mut self, policy: super::SkillsPolicy) -> Self {
+ self.agent_defaults.skills = policy;
+ self
+ }
+ /// Servers inherited by every agent, with agent declarations added afterwards.
+ #[cfg(feature = "mcp")]
+ pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self {
+ self.agent_defaults.mcp_baseline = servers.into_iter().collect();
+ self
+ }
+ /// Detailed autonomy settings; access tiers are subsequently applied to each agent.
+ pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self {
+ self.config_knobs.autonomy = Some(value);
+ self
+ }
+ /// Tool rules applied to every agent, which agents may only narrow.
+ pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self {
+ self.config_knobs.tool_rules = Some(value);
+ self
+ }
+ /// Data egress policy for this runtime.
+ pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self {
+ self.config_knobs.privacy = Some(value);
+ self
+ }
+ /// Credential encryption policy.
+ pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self {
+ self.config_knobs.secrets = Some(value);
+ self
+ }
+ /// Background memory learning defaults.
+ pub fn learning(mut self, value: super::LearningSettings) -> Self {
+ self.config_knobs.learning = Some(value);
+ self
+ }
+ /// Cron scheduler configuration; `services` separately controls its lifecycle.
+ pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self {
+ self.config_knobs.cron = Some(value);
+ self
+ }
+
/// The transport the runtime reaches the hosted TinyHumans backend
/// through (see [`BackendTransport`]).
///
@@ -155,7 +227,7 @@ impl RuntimeBuilder {
self
}
- /// The memory engine every agent and [`Runtime::memory`](super::Runtime::memory)
+ /// The memory engine every agent and [`crate::Runtime::memory`](super::Runtime::memory)
/// use, in place of the configured `[memory]` engine (TinyHumans over the
/// backend credential, or CortexDB with a stored key).
///
@@ -184,7 +256,7 @@ impl RuntimeBuilder {
self
}
- /// The most agents this runtime hosts at once; [`Runtime::agent`]
+ /// The most agents this runtime hosts at once; [`crate::Runtime::agent`]
/// returns [`AgentError::AgentLimit`](crate::AgentError::AgentLimit)
/// beyond it. Removed and dropped agents do not count. Defaults to
/// [`DEFAULT_MAX_AGENTS`].
@@ -281,9 +353,9 @@ impl RuntimeBuilder {
/// background process the caller did not ask for.
///
/// A set that selects anything beyond `harness_init` (`cron: true` to let
- /// [`Runtime::cron`] jobs fire on their own, say) is started by
+ /// [`crate::Runtime::cron`] jobs fire on their own, say) is started by
/// [`build`](Self::build) and stopped when the runtime drops; see
- /// [`Runtime::start_services`] / [`Runtime::stop_services`]. Starting is
+ /// [`crate::Runtime::start_services`] / [`crate::Runtime::stop_services`]. Starting is
/// idempotent, so a transport that serves the runtime
/// (`openhuman-rpc`) and calls `start_services` once its listener is
/// bound does not start them twice.
diff --git a/crates/openhuman-embed/src/runtime/defaults.rs b/crates/openhuman-embed/src/runtime/defaults.rs
new file mode 100644
index 0000000000..206cd525f5
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/defaults.rs
@@ -0,0 +1,117 @@
+//! Agent defaults resolve as Config baseline → runtime → AgentSpec → Turn.
+use crate::{Access, AgentDefinitionSpec, DomainSet, Provider, ToolGroups};
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+/// Sampling and iteration defaults. `None` preserves the lower precedence value.
+#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
+pub struct ModelDefaults {
+ /// Sampling temperature; unspecified preserves the lower precedence value.
+ pub temperature: Option<f64>,
+ /// Maximum output tokens; unspecified preserves the lower precedence value.
+ pub max_tokens: Option<u32>,
+ /// Nucleus sampling probability; unspecified preserves the lower precedence value.
+ pub top_p: Option<f64>,
+ /// Maximum model/tool iterations; unspecified preserves the lower precedence value.
+ pub max_iterations: Option<usize>,
+}
+impl ModelDefaults {
+ pub(crate) fn overlay(&self, other: &Self) -> Self {
+ Self {
+ temperature: other.temperature.or(self.temperature),
+ max_tokens: other.max_tokens.or(self.max_tokens),
+ top_p: other.top_p.or(self.top_p),
+ max_iterations: other.max_iterations.or(self.max_iterations),
+ }
+ }
+ pub(crate) fn validate(&self) -> Result<(), String> {
+ if self
+ .temperature
+ .is_some_and(|v| !v.is_finite() || !(0.0..=2.0).contains(&v))
+ {
+ return Err("temperature must be finite and between 0 and 2".into());
+ }
+ if self
+ .top_p
+ .is_some_and(|v| !v.is_finite() || !(0.0..=1.0).contains(&v))
+ {
+ return Err("top_p must be finite and between 0 and 1".into());
+ }
+ if self.max_tokens == Some(0) || self.max_iterations == Some(0) {
+ return Err("model limits must be positive".into());
+ }
+ Ok(())
+ }
+}
+/// Skill bundles copied into each agent and optional operator skill discovery.
+#[derive(Debug, Clone, Default)]
+pub struct SkillsPolicy {
+ /// Directory containing skill bundles to copy into each agent.
+ pub root: Option<PathBuf>,
+ /// Whether operator skill roots are discovered.
+ pub include_user_skills: bool,
+}
+/// Background memory learning policy, expressed using the existing memory recall settings.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct LearningSettings {
+ /// Turns between background belief builds; zero disables builds.
+ pub build_beliefs_every: u32,
+ /// Maximum learning entries included in recalled context.
+ pub learnings_limit: u32,
+}
+impl Default for LearningSettings {
+ fn default() -> Self {
+ Self {
+ build_beliefs_every: 10,
+ learnings_limit: 8,
+ }
+ }
+}
+/// Effective defaults inherited by an agent which leaves its spec silent.
+#[derive(Clone)]
+pub struct AgentDefaults {
+ /// Default inference provider and model route.
+ pub provider: Provider,
+ /// Default acting authority and approval policy.
+ pub access: Access,
+ /// Domain families available to new agents.
+ pub domains: DomainSet,
+ /// Default tool group disclosure ceiling.
+ pub tool_groups: ToolGroups,
+ /// Base definition extended by each agent.
+ pub definition: AgentDefinitionSpec,
+ /// Default shell and file confinement.
+ pub sandbox: crate::SandboxModeSpec,
+ /// Resolved sampling and iteration defaults.
+ pub model: ModelDefaults,
+ /// Skill bundle installation and user discovery policy.
+ pub skills: SkillsPolicy,
+ #[cfg(feature = "mcp")]
+ /// MCP servers inherited by each agent.
+ pub mcp_baseline: Vec<crate::McpServer>,
+ /// Reusable named definition templates.
+ pub templates: BTreeMap<String, AgentDefinitionSpec>,
+}
+impl Default for AgentDefaults {
+ fn default() -> Self {
+ Self {
+ provider: Provider::inherit(),
+ access: Access::default(),
+ domains: super::presets::default_domains(),
+ tool_groups: ToolGroups::default(),
+ definition: AgentDefinitionSpec::default(),
+ sandbox: crate::SandboxModeSpec::None,
+ model: ModelDefaults::default(),
+ skills: SkillsPolicy::default(),
+ #[cfg(feature = "mcp")]
+ mcp_baseline: Vec::new(),
+ templates: BTreeMap::new(),
+ }
+ }
+}
+/// Runtime defaults snapshot. Agent defaults are resolved against the runtime config.
+pub type RuntimeDefaults = AgentDefaults;
+
+#[cfg(test)]
+#[path = "defaults_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-embed/src/runtime/defaults_tests.rs b/crates/openhuman-embed/src/runtime/defaults_tests.rs
new file mode 100644
index 0000000000..66f7d67994
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/defaults_tests.rs
@@ -0,0 +1,44 @@
+use super::*;
+#[test]
+fn sampling_overlays_preserve_unspecified_fields() {
+ let runtime = ModelDefaults {
+ temperature: Some(0.2),
+ top_p: Some(0.8),
+ max_tokens: Some(1000),
+ max_iterations: Some(4),
+ };
+ let spec = ModelDefaults {
+ temperature: Some(0.7),
+ max_tokens: Some(2000),
+ ..Default::default()
+ };
+ let resolved = runtime.overlay(&spec);
+ assert_eq!(resolved.temperature, Some(0.7));
+ assert_eq!(resolved.max_tokens, Some(2000));
+ assert_eq!(resolved.top_p, Some(0.8));
+ assert_eq!(resolved.max_iterations, Some(4));
+ assert_eq!(runtime.temperature, Some(0.2));
+}
+#[test]
+fn invalid_sampling_parameters_are_rejected() {
+ for model in [
+ ModelDefaults {
+ temperature: Some(f64::NAN),
+ ..Default::default()
+ },
+ ModelDefaults {
+ top_p: Some(1.1),
+ ..Default::default()
+ },
+ ModelDefaults {
+ max_tokens: Some(0),
+ ..Default::default()
+ },
+ ModelDefaults {
+ max_iterations: Some(0),
+ ..Default::default()
+ },
+ ] {
+ assert!(model.validate().is_err());
+ }
+}
diff --git a/crates/openhuman-embed/src/runtime/host_agents.rs b/crates/openhuman-embed/src/runtime/host_agents.rs
index fd631dab76..31b3ad0460 100644
--- a/crates/openhuman-embed/src/runtime/host_agents.rs
+++ b/crates/openhuman-embed/src/runtime/host_agents.rs
@@ -37,6 +37,9 @@ impl AgentInner {
/// a remote host): the driver then fails to find the agent rather than
/// sending the credential in the clear.
pub(crate) fn host_agent(self: &Arc<Self>) -> Option<HostAgent> {
+ if *self.lifecycle.removed().borrow() {
+ return None;
+ }
let mut config = self.config.clone();
if let Some(model) = self.provider.model_id() {
config.default_model = Some(model.to_string());
diff --git a/crates/openhuman-embed/src/runtime/info.rs b/crates/openhuman-embed/src/runtime/info.rs
new file mode 100644
index 0000000000..b50bbf984d
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/info.rs
@@ -0,0 +1,299 @@
+//! Versioned, credential-safe runtime capability metadata.
+use super::{LearningSettings, ModelDefaults, Runtime, RuntimeBuilder};
+use openhuman_core::config::{
+ schema::{AutonomyConfig, CronConfig, PrivacyConfig, SecretsConfig},
+ Config,
+};
+use std::collections::BTreeMap;
+
+#[derive(Default)]
+pub(super) struct ConfigKnobs {
+ pub autonomy: Option<AutonomyConfig>,
+ /// Data egress policy name.
+ pub privacy: Option<PrivacyConfig>,
+ pub secrets: Option<SecretsConfig>,
+ pub cron: Option<CronConfig>,
+ /// Background memory learning policy.
+ pub learning: Option<LearningSettings>,
+ pub tool_rules: Option<tinytools::ToolRules>,
+}
+impl ConfigKnobs {
+ pub fn is_set(&self) -> bool {
+ self.autonomy.is_some()
+ || self.privacy.is_some()
+ || self.secrets.is_some()
+ || self.cron.is_some()
+ || self.learning.is_some()
+ || self.tool_rules.is_some()
+ }
+ pub fn apply(&self, config: &mut Config) {
+ if let Some(v) = &self.autonomy {
+ config.autonomy = v.clone();
+ }
+ if let Some(v) = &self.privacy {
+ config.privacy = *v;
+ }
+ if let Some(v) = &self.secrets {
+ config.secrets = v.clone();
+ }
+ if let Some(v) = &self.cron {
+ config.cron = v.clone();
+ }
+ if let Some(v) = &self.tool_rules {
+ config.tool_rules = v.clone();
+ }
+ if let Some(v) = &self.learning {
+ config.memory.recall.build_beliefs_every = v.build_beliefs_every;
+ config.memory.recall.learnings_limit = v.learnings_limit;
+ }
+ }
+}
+/// Stable JSON shape. Secrets, endpoint strings, custom prompts and environment values are excluded.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct RuntimeInfo {
+ /// Capability JSON schema version, currently one.
+ pub schema_version: u32,
+ /// Whether the metadata uses the loaded configuration rather than a pre-build placeholder.
+ pub configuration_resolved: bool,
+ /// Actual Cargo gates compiled into the core artifact.
+ pub compiled_features: BTreeMap<String, bool>,
+ /// Domain families available to new agents.
+ pub domains: Vec<String>,
+ /// Selected background and bootstrap service names.
+ pub services: Vec<String>,
+ /// Default tool group disclosure ceiling.
+ pub tool_groups: BTreeMap<String, String>,
+ /// Effective host identity used by core authentication policy.
+ pub host_kind: String,
+ /// Maximum simultaneously registered agents.
+ pub max_agents: usize,
+ /// Credential-safe summary of agent defaults.
+ pub defaults: DefaultsInfo,
+ /// Selected runtime configuration policies.
+ pub configuration: ConfigurationInfo,
+ /// Credential-safe storage selection.
+ pub storage: StorageInfo,
+ /// Explicitly selected module families.
+ pub modules: Vec<super::RuntimeModule>,
+ /// Approximate runtime activity class.
+ pub weight: super::WeightClass,
+}
+/// Storage source and driver only; the URL and its credentials are never exposed.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct StorageInfo {
+ /// Selection source: workspace, configuration, explicit URL or backend.
+ pub source: String,
+ /// Storage driver identifier, without endpoint or credentials.
+ pub driver: Option<String>,
+ /// Whether a non-classic storage source was selected.
+ pub configured: bool,
+}
+impl StorageInfo {
+ pub(super) fn describe(source: Option<&super::StorageSource>, config: &Config) -> Self {
+ match source {
+ Some(super::StorageSource::Backend(backend)) => Self {
+ source: "backend".into(),
+ driver: Some(backend.driver().into()),
+ configured: true,
+ },
+ Some(super::StorageSource::Url(url)) => Self::url("explicit", url),
+ None => match openhuman_core::storage::configured_url(config) {
+ Some(url) => Self::url("configuration", &url),
+ None => Self {
+ source: "workspace".into(),
+ driver: None,
+ configured: false,
+ },
+ },
+ }
+ }
+ fn url(source: &str, url: &str) -> Self {
+ let driver = openhuman_core::storage::StorageUrl::parse(url)
+ .ok()
+ .map(|u| u.driver().to_string());
+ Self {
+ source: source.into(),
+ driver,
+ configured: true,
+ }
+ }
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+/// Public agent defaults with credentials, prompt text and filesystem paths omitted.
+pub struct DefaultsInfo {
+ /// Resolved sampling and iteration defaults.
+ pub model: ModelDefaults,
+ /// Configured default model identifier.
+ pub provider_model: Option<String>,
+ /// Whether the host supplied a provider route.
+ pub routed_provider: bool,
+ /// Default shell and file confinement.
+ pub sandbox: String,
+ /// Whether interactive approval is enabled by default.
+ pub approval_gate: bool,
+ /// Whether operator skill roots are discovered.
+ pub include_user_skills: bool,
+ /// Whether a runtime skill bundle directory was supplied.
+ pub has_skills_root: bool,
+ /// Number of inherited MCP servers.
+ pub mcp_servers: usize,
+ /// Reusable named definition templates.
+ pub templates: Vec<String>,
+}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+/// Policy and learning settings safe to display in capability JSON.
+pub struct ConfigurationInfo {
+ /// Whether the in-process autonomy policy is enabled.
+ pub autonomy_enabled: bool,
+ /// Data egress policy name.
+ pub privacy: String,
+ /// Whether stored credentials are encrypted.
+ pub secrets_encrypted: bool,
+ /// Whether configured cron scheduling is enabled.
+ pub cron_enabled: bool,
+ /// Background memory learning policy.
+ pub learning: LearningSettings,
+ /// Whether global tool rules constrain tools through rules or a deny default.
+ pub has_tool_rules: bool,
+}
+impl RuntimeBuilder {
+ /// Describe this builder without booting a core or discovering operator files.
+ /// Discovered config values are unknown until `Runtime::capabilities()`.
+ pub fn describe(&self) -> RuntimeInfo {
+ let mut config = self.config.clone().unwrap_or_default();
+ self.config_knobs.apply(&mut config);
+ self.access.apply(&mut config);
+ super::build::apply_provider(&mut config, &self.provider);
+ let defaults = self.resolved_defaults(
+ &config,
+ self.domains.unwrap_or_else(super::presets::default_domains),
+ self.tool_groups.clone().unwrap_or_default(),
+ );
+ let host = super::build::effective_host_kind(
+ self.host_kind,
+ self.workspace.is_operator_owned(),
+ super::build::routed_provider_effective(&self.provider, Some(&config))
+ || self.api_key.is_some(),
+ );
+ let mut info = make_info(
+ &defaults,
+ &config,
+ self.services
+ .unwrap_or_else(super::presets::default_services),
+ host,
+ self.max_agents,
+ self.selection.as_ref(),
+ );
+ info.configuration_resolved = self.config_source == super::ConfigSource::Resolved;
+ info.storage = StorageInfo::describe(self.seams.storage.as_ref(), &config);
+ info
+ }
+}
+impl Runtime {
+ /// Snapshot of the effective runtime, including the host kind chosen during boot.
+ pub fn capabilities(&self) -> RuntimeInfo {
+ let mut info = make_info(
+ &self.defaults(),
+ &self.base_config,
+ self.services(),
+ self.effective_host_kind,
+ self.max_agents,
+ self.selection.as_ref(),
+ );
+ info.configuration_resolved = self.config_unavailable.is_none();
+ info.storage = self.storage_info.clone();
+ info
+ }
+}
+fn make_info(
+ defaults: &super::AgentDefaults,
+ config: &Config,
+ services: crate::ServiceSet,
+ host: crate::HostKind,
+ max_agents: usize,
+ selection: Option<&super::ModuleSelection>,
+) -> RuntimeInfo {
+ use openhuman_core::core::all::DomainGroup;
+ let domains = DomainGroup::ALL
+ .iter()
+ .filter(|g| defaults.domains.allows(**g))
+ .map(|g| format!("{g:?}").to_lowercase())
+ .collect();
+ let service_flags = [
+ ("rpc_http", services.rpc_http),
+ ("socketio", services.socketio),
+ ("cron", services.cron),
+ ("channels", services.channels),
+ ("login_gated", services.login_gated),
+ ("update_scheduler", services.update_scheduler),
+ ("memory_queue", services.memory_queue),
+ ("harness_init", services.harness_init),
+ ("skill_catalog_refresh", services.skill_catalog_refresh),
+ ("mcp_boot", services.mcp_boot),
+ ("integrations", services.integrations),
+ ("memory_sync", services.memory_sync),
+ ];
+ RuntimeInfo {
+ schema_version: 1,
+ configuration_resolved: true,
+ compiled_features: openhuman_core::core::runtime::compiled_features(),
+ domains,
+ services: service_flags
+ .into_iter()
+ .filter(|(_, v)| *v)
+ .map(|(k, _)| k.into())
+ .collect(),
+ tool_groups: crate::ToolGroups::ids()
+ .map(|id| {
+ (
+ id.into(),
+ format!("{:?}", defaults.tool_groups.mode(id)).to_lowercase(),
+ )
+ })
+ .collect(),
+ host_kind: format!("{host:?}"),
+ max_agents,
+ defaults: DefaultsInfo {
+ model: defaults.model.clone(),
+ provider_model: config.default_model.clone(),
+ routed_provider: defaults.provider.is_routed(),
+ sandbox: format!("{:?}", defaults.sandbox),
+ approval_gate: defaults.access.approval_gate_enabled(),
+ include_user_skills: defaults.skills.include_user_skills,
+ has_skills_root: defaults.skills.root.is_some(),
+ mcp_servers: {
+ #[cfg(feature = "mcp")]
+ {
+ config.mcp_client.servers.len() + defaults.mcp_baseline.len()
+ }
+ #[cfg(not(feature = "mcp"))]
+ {
+ config.mcp_client.servers.len()
+ }
+ },
+ templates: defaults.templates.keys().cloned().collect(),
+ },
+ configuration: ConfigurationInfo {
+ autonomy_enabled: config.autonomy.enabled,
+ privacy: format!("{:?}", config.privacy.mode),
+ secrets_encrypted: config.secrets.encrypt,
+ cron_enabled: config.cron.enabled,
+ learning: LearningSettings {
+ build_beliefs_every: config.memory.recall.build_beliefs_every,
+ learnings_limit: config.memory.recall.learnings_limit,
+ },
+ has_tool_rules: config.tool_rules.default != tinytools::DefaultEffect::Allow
+ || !config.tool_rules.rules.is_empty(),
+ },
+ storage: StorageInfo::describe(None, config),
+ modules: selection.map(|s| s.modules.clone()).unwrap_or_default(),
+ weight: selection
+ .map(|s| s.weight)
+ .unwrap_or(super::WeightClass::Custom),
+ }
+}
+
+#[cfg(test)]
+#[path = "info_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-embed/src/runtime/info_tests.rs b/crates/openhuman-embed/src/runtime/info_tests.rs
new file mode 100644
index 0000000000..947b3137d4
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/info_tests.rs
@@ -0,0 +1,195 @@
+use super::*;
+use crate::{ModelDefaults, Provider, RuntimeBuilder, RuntimeModule, SkillsPolicy, WeightClass};
+#[test]
+fn capability_json_is_versioned_and_never_contains_credentials() {
+ let info = RuntimeBuilder::new()
+ .provider(
+ Provider::openai_compatible(
+ "https://user:[email protected]/v1?key=secret-query",
+ "secret-api-key",
+ )
+ .model("sample-model"),
+ )
+ .api_key("secret-backend-key")
+ .token(crate::TokenSource::Fixed(std::sync::Arc::new(
+ "secret-rpc-token".into(),
+ )))
+ .describe();
+ let json = serde_json::to_string(&info).unwrap();
+ for secret in [
+ "password",
+ "secret-query",
+ "secret-api-key",
+ "secret-backend-key",
+ "secret-rpc-token",
+ "host.example",
+ ] {
+ assert!(!json.contains(secret), "{secret} escaped introspection");
+ }
+ let value: serde_json::Value = serde_json::from_str(&json).unwrap();
+ assert_eq!(value["schema_version"], 1);
+ let roundtrip: RuntimeInfo = serde_json::from_str(&json).unwrap();
+ assert_eq!(
+ roundtrip.defaults.provider_model.as_deref(),
+ Some("sample-model")
+ );
+ assert_eq!(
+ info.compiled_features,
+ openhuman_core::core::runtime::compiled_features()
+ );
+}
+#[test]
+fn describe_includes_effective_host_limits_and_agent_defaults() {
+ let info = RuntimeBuilder::new()
+ .workspace(crate::Workspace::Inherit)
+ .max_agents(3)
+ .model_defaults(ModelDefaults {
+ temperature: Some(0.4),
+ max_tokens: Some(100),
+ top_p: Some(0.8),
+ max_iterations: Some(5),
+ })
+ .skills(SkillsPolicy {
+ root: Some("skills-root".into()),
+ include_user_skills: true,
+ })
+ .describe();
+ assert_eq!(info.host_kind, "Cli");
+ assert_eq!(info.max_agents, 3);
+ assert_eq!(info.defaults.model.temperature, Some(0.4));
+ assert_eq!(info.defaults.model.max_tokens, Some(100));
+ assert!(info.defaults.include_user_skills);
+ assert!(info.defaults.has_skills_root);
+}
+#[test]
+fn typed_configuration_groups_apply_on_top_of_supplied_config() {
+ use openhuman_core::config::schema::{
+ AutonomyConfig, CronConfig, PrivacyConfig, PrivacyMode, SecretsConfig,
+ };
+ let info = RuntimeBuilder::new()
+ .privacy(PrivacyConfig {
+ mode: PrivacyMode::Sensitive,
+ })
+ .secrets(SecretsConfig { encrypt: false })
+ .cron(CronConfig {
+ enabled: false,
+ ..Default::default()
+ })
+ .learning(LearningSettings {
+ build_beliefs_every: 30,
+ learnings_limit: 2,
+ })
+ .autonomy(AutonomyConfig {
+ max_actions_per_hour: 7,
+ ..Default::default()
+ })
+ .describe();
+ assert_eq!(info.configuration.privacy, "Sensitive");
+ assert!(!info.configuration.secrets_encrypted);
+ assert!(!info.configuration.cron_enabled);
+ assert_eq!(info.configuration.learning.build_beliefs_every, 30);
+ assert_eq!(info.configuration.learning.learnings_limit, 2);
+}
+#[test]
+fn presets_report_consistent_module_weight_and_optional_gates() {
+ let lean = RuntimeBuilder::lean().describe();
+ assert_eq!(lean.weight, WeightClass::Lean);
+ assert_eq!(
+ lean.modules,
+ vec![
+ RuntimeModule::Agent,
+ RuntimeModule::Memory,
+ RuntimeModule::Inference
+ ]
+ );
+ let standard = RuntimeBuilder::standard().describe();
+ assert_eq!(standard.weight, WeightClass::Standard);
+ assert!(!standard.modules.contains(&RuntimeModule::Voice));
+ assert!(!standard.modules.contains(&RuntimeModule::Automation));
+ let full = RuntimeBuilder::full().describe();
+ assert_eq!(full.weight, WeightClass::Full);
+ for module in [
+ RuntimeModule::Integrations,
+ RuntimeModule::Automation,
+ RuntimeModule::Runtimes,
+ ] {
+ assert!(full.modules.contains(&module));
+ }
+ assert!(full.services.contains(&"cron".into()));
+ assert!(lean.services.iter().all(|s| s == "harness_init"));
+ assert!(!lean.domains.contains(&"modules".into()));
+ assert!(!lean.domains.contains(&"flows".into()));
+ for info in [
+ RuntimeBuilder::standard().describe(),
+ RuntimeBuilder::full().describe(),
+ ] {
+ for module in info.modules {
+ if let Some(feature) = module.required_feature() {
+ assert!(info.compiled_features[feature]);
+ }
+ }
+ }
+}
+#[test]
+fn unavailable_module_error_names_its_cargo_feature() {
+ let features = openhuman_core::core::runtime::compiled_features();
+ for module in [
+ RuntimeModule::Voice,
+ RuntimeModule::Web3,
+ RuntimeModule::Documents,
+ RuntimeModule::Hosting,
+ RuntimeModule::Skills,
+ RuntimeModule::Mcp,
+ ] {
+ if let Some(feature) = module.required_feature() {
+ let builder = RuntimeBuilder::new().modules([module]);
+ if !features[feature] {
+ assert!(
+ matches!(builder.validate(), Err(crate::RuntimeError::MissingFeature{feature:actual,..}) if actual==feature)
+ );
+ } else {
+ assert!(builder.validate().is_ok());
+ }
+ }
+ }
+}
+#[test]
+fn discovered_config_still_rejects_typed_boot_edits() {
+ let builder = RuntimeBuilder::desktop().cron(Default::default());
+ assert!(builder.validate().is_err());
+ assert!(RuntimeBuilder::desktop()
+ .model_defaults(ModelDefaults {
+ max_tokens: Some(300),
+ ..Default::default()
+ })
+ .validate()
+ .is_ok());
+}
+
+#[test]
+fn storage_config_and_explicit_sources_are_credential_safe() {
+ let mut config = openhuman_core::config::Config::default();
+ config.storage.url =
+ Some("mongodb://app:secret-password@private-host/database?authSource=secret-query".into());
+ let builder = RuntimeBuilder::new().config(config);
+ let info = builder.describe();
+ assert_eq!(info.storage.driver.as_deref(), Some("mongodb"));
+ assert_eq!(info.storage.source, "configuration");
+ assert!(info.storage.configured);
+ let json = serde_json::to_string(&info).unwrap();
+ for secret in ["secret-password", "private-host", "secret-query"] {
+ assert!(!json.contains(secret));
+ }
+ if !info.compiled_features["storage-mongodb"] {
+ assert!(matches!(
+ builder.validate(),
+ Err(crate::RuntimeError::MissingStorageFeature {
+ feature: "storage-mongodb",
+ ..
+ })
+ ));
+ }
+ let info = RuntimeBuilder::new().storage("memory").describe();
+ assert_eq!(info.storage.driver.as_deref(), Some("memory"));
+ assert_eq!(info.storage.source, "explicit");
+}
diff --git a/crates/openhuman-embed/src/runtime/lifecycle.rs b/crates/openhuman-embed/src/runtime/lifecycle.rs
index 5a9cf8c41d..7df17da08a 100644
--- a/crates/openhuman-embed/src/runtime/lifecycle.rs
+++ b/crates/openhuman-embed/src/runtime/lifecycle.rs
@@ -2,6 +2,7 @@
use std::future::{Future, IntoFuture};
use std::pin::Pin;
+use std::sync::Arc;
use std::time::Duration;
use super::Runtime;
@@ -10,6 +11,51 @@ use crate::agent::AgentError;
/// How long [`Runtime::remove_agent`] waits for in-flight turns to unwind.
const REMOVE_IDLE_WAIT: Duration = Duration::from_secs(10);
+// Reserve the public id until all old-instance cleanup finishes, including
+// when a caller cancels the removal future after it has started.
+struct RemovalSlot<'a> {
+ runtime: &'a Runtime,
+ inner: Arc<crate::agent::AgentInner>,
+ purge: bool,
+}
+
+impl RemovalSlot<'_> {
+ fn purge_home(&mut self) -> Result<(), AgentError> {
+ if !std::mem::take(&mut self.purge) {
+ return Ok(());
+ }
+ let home = &self.inner.layout.home;
+ if home.exists() {
+ std::fs::remove_dir_all(home).map_err(|source| AgentError::Workspace {
+ what: "delete the removed agent's home",
+ source,
+ })?;
+ }
+ Ok(())
+ }
+}
+
+impl Drop for RemovalSlot<'_> {
+ fn drop(&mut self) {
+ self.inner.teardown("agent_removed");
+ if let Err(error) = self.purge_home() {
+ log::warn!("[embed][runtime] cancelled removal purge failed: {error}");
+ }
+ let mut agents = self
+ .runtime
+ .agents
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ if agents
+ .get(&self.inner.id)
+ .and_then(std::sync::Weak::upgrade)
+ .is_some_and(|current| Arc::ptr_eq(&current, &self.inner))
+ {
+ agents.remove(&self.inner.id);
+ }
+ }
+}
+
/// A pending [`Runtime::remove_agent`]. Await it, optionally after
/// [`purge`](Self::purge).
#[must_use = "an agent is removed only when this is awaited"]
@@ -40,12 +86,14 @@ impl<'a> IntoFuture for RemoveAgent<'a> {
impl Runtime {
/// Remove agent `id` from this runtime.
///
- /// In order: its parked approvals are denied with resolution
- /// `agent_removed`; new turns on any handle to it are refused with
- /// [`CoreError::AgentRemoved`](crate::CoreError::AgentRemoved); turns in
+ /// New turns on any handle to it are refused with
+ /// [`CoreError::AgentRemoved`](crate::CoreError::AgentRemoved); its parked
+ /// approvals are denied with resolution `agent_removed`; turns in
/// flight end with the same error, waited on for up to ten seconds; its
/// state slots and MCP host are dropped and its context deregistered, so
- /// its cron jobs stay dormant. The id is free for reuse once this returns.
+ /// its cron jobs stay dormant. The id is free for reuse once cleanup ends.
+ /// Cancelling an already-started removal still tears down the old instance
+ /// and performs a requested purge before releasing its id.
///
/// Cancellation is cooperative: a tool already executing when the agent
/// is removed, or a sub-agent it detached, may finish after this returns.
@@ -59,16 +107,23 @@ impl Runtime {
async fn remove(&self, id: &str, purge: bool) -> Result<(), AgentError> {
let inner = {
- let mut agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
- agents.retain(|_, weak| weak.strong_count() > 0);
+ let agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
agents
- .remove(id)
+ .get(id)
.and_then(|weak| weak.upgrade())
.ok_or_else(|| AgentError::UnknownId(id.to_string()))?
};
+ if !inner.lifecycle.mark_removed() {
+ return Err(AgentError::UnknownId(id.to_string()));
+ }
+ let mut removal = RemovalSlot {
+ runtime: self,
+ inner,
+ purge,
+ };
+ let inner = &removal.inner;
log::debug!("[embed][runtime] removing agent id={id} purge={purge}");
inner.deny_approvals("agent_removed");
- inner.lifecycle.mark_removed();
if !inner.lifecycle.wait_idle(REMOVE_IDLE_WAIT).await {
log::warn!(
"[embed][runtime] agent id={id} still had turns unwinding after {}s",
@@ -76,15 +131,7 @@ impl Runtime {
);
}
inner.teardown("agent_removed");
- if purge {
- let home = inner.layout.home.clone();
- if home.exists() {
- std::fs::remove_dir_all(&home).map_err(|source| AgentError::Workspace {
- what: "delete the removed agent's home",
- source,
- })?;
- }
- }
+ removal.purge_home()?;
log::debug!("[embed][runtime] agent removed id={id}");
Ok(())
}
diff --git a/crates/openhuman-embed/src/runtime/live_hooks.rs b/crates/openhuman-embed/src/runtime/live_hooks.rs
new file mode 100644
index 0000000000..6ec4be273c
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/live_hooks.rs
@@ -0,0 +1,72 @@
+//! Tracked runtime hooks, composed with agent-local hooks.
+use super::Runtime;
+use crate::seams::{PostTurnHook, ToolHook, ToolHookContext, ToolHookDecision, TurnContext};
+use std::sync::Arc;
+
+pub(super) struct NamedPostTurnHook(pub String, pub Arc<dyn PostTurnHook>);
+#[async_trait::async_trait]
+impl PostTurnHook for NamedPostTurnHook {
+ fn name(&self) -> &str {
+ &self.0
+ }
+ async fn on_turn_complete(&self, context: &TurnContext) -> anyhow::Result<()> {
+ self.1.on_turn_complete(context).await
+ }
+}
+pub(super) struct NamedToolHook(pub String, pub Arc<dyn ToolHook>);
+#[async_trait::async_trait]
+impl ToolHook for NamedToolHook {
+ fn name(&self) -> &str {
+ &self.0
+ }
+ async fn before_tool(&self, context: &ToolHookContext) -> anyhow::Result<()> {
+ self.1.before_tool(context).await
+ }
+ async fn after_tool(&self, context: &ToolHookContext) -> anyhow::Result<()> {
+ self.1.after_tool(context).await
+ }
+ async fn before_tool_decision(&self, context: &ToolHookContext) -> ToolHookDecision {
+ self.1.before_tool_decision(context).await
+ }
+ async fn after_tool_context(&self, context: &ToolHookContext) -> Option<String> {
+ self.1.after_tool_context(context).await
+ }
+}
+impl Runtime {
+ /// Add, replace, or remove a runtime-wide post-turn hook by name.
+ /// This also replaces hooks installed by the builder. Changes apply to
+ /// subsequently assembled turns; removal restores any predecessor hook.
+ pub fn post_turn_hook(&self, name: &str, hook: Option<Arc<dyn crate::seams::PostTurnHook>>) {
+ let context = self.core_runtime().context().clone();
+ openhuman_core::core::runtime::CoreContext::sync_scope(context.clone(), || {
+ let mut seams = self
+ .guard
+ .seams
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(seams) = seams.as_mut() {
+ seams.post_turn_hook(name, hook);
+ } else if let Some(overrides) = context.host_overrides() {
+ overrides.post_turn_hook(name, hook);
+ }
+ });
+ }
+ /// Add, replace, or remove a runtime-wide tool hook by name.
+ /// This also replaces hooks installed by the builder. Changes apply to
+ /// subsequently assembled turns; removal restores any predecessor hook.
+ pub fn tool_hook(&self, name: &str, hook: Option<Arc<dyn crate::seams::ToolHook>>) {
+ let context = self.core_runtime().context().clone();
+ openhuman_core::core::runtime::CoreContext::sync_scope(context.clone(), || {
+ let mut seams = self
+ .guard
+ .seams
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if let Some(seams) = seams.as_mut() {
+ seams.tool_hook(name, hook);
+ } else if let Some(overrides) = context.host_overrides() {
+ overrides.tool_hook(name, hook);
+ }
+ });
+ }
+}
diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs
index 911b32530b..c83695a083 100644
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@ -69,19 +69,28 @@
mod api_key;
mod build;
pub(crate) mod builder;
+mod defaults;
mod host_agents;
+pub(crate) use host_agents::AgentMap;
+mod info;
mod lifecycle;
+mod live_hooks;
mod presets;
mod run;
mod seams;
+mod selection;
mod summary;
pub use api_key::ApiKey;
pub use builder::{ConfigSource, RuntimeBuilder};
+pub use defaults::{AgentDefaults, LearningSettings, ModelDefaults, RuntimeDefaults, SkillsPolicy};
+pub use info::{ConfigurationInfo, DefaultsInfo, RuntimeInfo, StorageInfo};
pub use lifecycle::RemoveAgent;
pub use run::run_from_args;
#[doc(hidden)]
pub use seams::StorageSource;
+use selection::ModuleSelection;
+pub use selection::{RuntimeModule, WeightClass};
pub use summary::BuilderSummary;
use std::collections::HashMap;
@@ -95,7 +104,7 @@ use openhuman_core::tools::toolpacks::ToolGroups;
use crate::agent::{Agent, AgentError, AgentSpec};
use crate::harness::workspace::ResolvedWorkspace;
-use crate::harness::{Access, HarnessCore, Provider};
+use crate::harness::HarnessCore;
use crate::{Core, CoreError};
/// Guards the process-scoped core state described in the module docs.
@@ -138,6 +147,24 @@ pub enum RuntimeError {
#[error("the TinyHumans API key is blank")]
BlankApiKey,
+ /// A requested module was excluded from this core artifact.
+ #[error("module {module:?} requires Cargo feature `{feature}`")]
+ MissingFeature {
+ /// Requested module family.
+ module: RuntimeModule,
+ /// Cargo feature required by this selection.
+ feature: &'static str,
+ },
+
+ /// The requested storage driver was excluded from this core artifact.
+ #[error("storage driver {driver} requires Cargo feature `{feature}`")]
+ MissingStorageFeature {
+ /// Requested storage driver.
+ driver: String,
+ /// Cargo feature required by this selection.
+ feature: &'static str,
+ },
+
/// [`Workspace::Stateless`](crate::Workspace::Stateless) was asked for
/// without a [`RuntimeBuilder::session_store`] to keep conversations in.
#[error(
@@ -148,7 +175,7 @@ pub enum RuntimeError {
/// The process-scoped state a [`Runtime`] and every [`Agent`](crate::Agent)
/// built on it share ownership of: the core itself and, for
-/// [`Workspace::Ephemeral`], the workspace it lives in.
+/// [`crate::Workspace::Ephemeral`], the workspace it lives in.
///
/// Held as `Arc<CoreGuard>` by both `Runtime` and `AgentInner` so its `Drop`
/// — releasing [`RUNTIME_LIVE`] and removing an ephemeral workspace — runs
@@ -160,6 +187,7 @@ pub enum RuntimeError {
/// call reinitialized the same process-global keyring, event bus and
/// subscribers underneath it.
pub(crate) struct CoreGuard {
+ pub(crate) events: Arc<crate::events::EventHub>,
core: Option<Core>,
/// Held for its `Drop`: an ephemeral workspace lives exactly as long as
/// the last owner of this guard.
@@ -177,7 +205,7 @@ pub(crate) struct CoreGuard {
Mutex<HashMap<String, openhuman_core::cron::system_job_handlers::SystemJobRegistration>>,
/// Process-global seams this runtime installed; dropping restores the
/// restorable ones (see [`seams`]).
- seams: Option<seams::InstalledSeams>,
+ seams: Mutex<Option<seams::InstalledSeams>>,
}
impl Drop for CoreGuard {
@@ -199,7 +227,12 @@ impl Drop for CoreGuard {
openhuman_core::agent::session_store::restore(self.previous_session_store.take());
}
}
- drop(self.seams.take());
+ drop(
+ self.seams
+ .get_mut()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .take(),
+ );
// For an ephemeral workspace, take ownership of the temp path and
// remove it with a short retry. The core's memory/session writers keep
// running a moment after a turn returns and can recreate workspace
@@ -234,7 +267,7 @@ impl Drop for CoreGuard {
/// Build once with [`Runtime::builder`]; share as `Arc<Runtime>` when several
/// parts of the host create agents. Dropping the last of this `Runtime` and
/// every [`Agent`](crate::Agent) built on it tears the core down and, for
-/// [`Workspace::Ephemeral`], removes the workspace — see [`CoreGuard`].
+/// [`crate::Workspace::Ephemeral`], removes the workspace — see `CoreGuard`.
pub struct Runtime {
id: String,
guard: Arc<CoreGuard>,
@@ -248,13 +281,55 @@ pub struct Runtime {
inherited: bool,
domains: DomainSet,
tool_groups: ToolGroups,
- provider: Provider,
- access: Access,
agents: Arc<host_agents::AgentMap>,
max_agents: usize,
+ defaults: Mutex<AgentDefaults>,
+ effective_host_kind: openhuman_core::core::types::HostKind,
+ selection: Option<ModuleSelection>,
+ storage_info: StorageInfo,
+ storage_backend: Option<Arc<dyn openhuman_core::storage::StorageBackend>>,
}
impl Runtime {
+ /// Subscribe to content-free runtime metadata; slow consumers receive a lag error.
+ pub fn events(&self) -> crate::RuntimeEvents {
+ self.guard.events.subscribe()
+ }
+
+ /// Backend installed for this runtime; absent for the classic workspace layout.
+ pub fn storage(&self) -> Option<Arc<dyn openhuman_core::storage::StorageBackend>> {
+ self.storage_backend.clone()
+ }
+
+ /// Snapshot of defaults used by newly created agents. Existing agents retain theirs.
+ pub fn defaults(&self) -> RuntimeDefaults {
+ self.defaults
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ }
+
+ /// Register a reusable definition template. Agents resolve it once, at creation.
+ pub fn define_template(
+ &self,
+ id: impl Into<String>,
+ spec: crate::AgentDefinitionSpec,
+ ) -> Result<(), AgentError> {
+ let id = id.into();
+ if id.trim().is_empty() {
+ return Err(AgentError::Invalid("template id must not be blank".into()));
+ }
+ spec.clone()
+ .inherit(self.defaults().definition)?
+ .into_core("template-validation")?;
+ self.defaults
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .templates
+ .insert(id, spec);
+ Ok(())
+ }
+
/// Opaque identity of this instantiated runtime.
pub fn runtime_id(&self) -> &str {
&self.id
@@ -288,7 +363,6 @@ impl Runtime {
// id as free and both instantiate, with the second `insert`
// silently overwriting the first agent's registry entry.
let mut agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
- agents.retain(|_, weak| weak.strong_count() > 0);
if agents.contains_key(&id) {
return Err(AgentError::DuplicateId(id));
}
@@ -304,6 +378,9 @@ impl Runtime {
let inner = Arc::new(crate::agent::build::instantiate(self, spec)?);
agents.insert(id.clone(), Arc::downgrade(&inner));
drop(agents);
+ self.guard
+ .events
+ .emit(Some(id.clone()), None, crate::RuntimeEventKind::AgentAdded);
log::debug!("[embed][runtime] agent registered id={id}");
Ok(Agent::from_inner(inner))
}
@@ -360,6 +437,11 @@ impl Runtime {
pub async fn start_services(&self) {
log::debug!("[embed][runtime] start_services");
self.core_runtime().start_services().await;
+ self.guard.events.emit(
+ None,
+ None,
+ crate::RuntimeEventKind::ServicesChanged { running: true },
+ );
}
/// Stop the background services. They also stop when the last owner of
@@ -367,12 +449,16 @@ impl Runtime {
pub fn stop_services(&self) {
log::debug!("[embed][runtime] stop_services");
self.core_runtime().stop_services();
+ self.guard.events.emit(
+ None,
+ None,
+ crate::RuntimeEventKind::ServicesChanged { running: false },
+ );
}
- /// Ids of the agents currently alive on this runtime.
+ /// Ids reserved by live agents or their teardown in progress.
pub fn agent_ids(&self) -> Vec<String> {
- let mut agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
- agents.retain(|_, weak| weak.strong_count() > 0);
+ let agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
let mut ids: Vec<String> = agents.keys().cloned().collect();
ids.sort();
ids
@@ -474,11 +560,16 @@ impl Runtime {
/// The shared teardown guard, cloned into every [`AgentInner`] so the
/// core and an ephemeral workspace outlive whichever of `Runtime` or its
- /// agents is dropped last. See [`CoreGuard`].
+ /// agents is dropped last. See `CoreGuard`.
pub(crate) fn guard(&self) -> Arc<CoreGuard> {
Arc::clone(&self.guard)
}
+ /// Keeps agent ids reserved through the last owner's teardown.
+ pub(crate) fn agent_registry(&self) -> Arc<AgentMap> {
+ Arc::clone(&self.agents)
+ }
+
pub(crate) fn base_config(&self) -> &Config {
&self.base_config
}
@@ -487,14 +578,6 @@ impl Runtime {
self.inherited
}
- pub(crate) fn default_provider(&self) -> &Provider {
- &self.provider
- }
-
- pub(crate) fn default_access(&self) -> &Access {
- &self.access
- }
-
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
core: Core,
@@ -509,9 +592,12 @@ impl Runtime {
inherited: bool,
domains: DomainSet,
tool_groups: ToolGroups,
- provider: Provider,
- access: Access,
max_agents: usize,
+ defaults: AgentDefaults,
+ effective_host_kind: openhuman_core::core::types::HostKind,
+ selection: Option<ModuleSelection>,
+ storage_info: StorageInfo,
+ storage_backend: Option<Arc<dyn openhuman_core::storage::StorageBackend>>,
) -> Self {
let agents: Arc<host_agents::AgentMap> = Arc::new(Mutex::new(HashMap::new()));
let resolver: Arc<dyn openhuman_core::agent::host_agents::HostAgentResolver> =
@@ -520,23 +606,27 @@ impl Runtime {
Self {
id: uuid::Uuid::new_v4().to_string(),
guard: Arc::new(CoreGuard {
+ events: crate::events::EventHub::new(256),
core: Some(core),
workspace,
session_store,
previous_session_store,
host_agents: resolver,
system_jobs: Mutex::new(HashMap::new()),
- seams,
+ seams: Mutex::new(seams),
}),
base_config,
config_unavailable,
inherited,
domains,
tool_groups,
- provider,
- access,
agents,
max_agents,
+ defaults: Mutex::new(defaults),
+ effective_host_kind,
+ selection,
+ storage_info,
+ storage_backend,
}
}
}
diff --git a/crates/openhuman-embed/src/runtime/seams.rs b/crates/openhuman-embed/src/runtime/seams.rs
index 51f3c302a7..be563bfffb 100644
--- a/crates/openhuman-embed/src/runtime/seams.rs
+++ b/crates/openhuman-embed/src/runtime/seams.rs
@@ -249,6 +249,62 @@ pub(crate) struct InstalledSeams {
}
impl InstalledSeams {
+ pub(crate) fn post_turn_hook(&mut self, name: &str, hook: Option<Arc<dyn PostTurnHook>>) {
+ while let Some(index) = self
+ .post_turn_hooks
+ .iter()
+ .rposition(|installed| installed.name == name)
+ {
+ let installed = self.post_turn_hooks.remove(index);
+ let current = embedder_post_turn_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name);
+ if current.is_some_and(|current| Arc::ptr_eq(&current, &installed.ours)) {
+ replace_embedder_post_turn_hook(name, installed.previous);
+ }
+ }
+ if let Some(hook) = hook {
+ let hook: Arc<dyn PostTurnHook> =
+ Arc::new(super::live_hooks::NamedPostTurnHook(name.to_owned(), hook));
+ let previous = embedder_post_turn_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name);
+ replace_embedder_post_turn_hook(name, Some(hook.clone()));
+ self.post_turn_hooks.push(InstalledHook {
+ name: name.to_owned(),
+ ours: hook,
+ previous,
+ });
+ }
+ }
+ pub(crate) fn tool_hook(&mut self, name: &str, hook: Option<Arc<dyn ToolHook>>) {
+ while let Some(index) = self
+ .tool_hooks
+ .iter()
+ .rposition(|installed| installed.name == name)
+ {
+ let installed = self.tool_hooks.remove(index);
+ let current = embedder_tool_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name);
+ if current.is_some_and(|current| Arc::ptr_eq(&current, &installed.ours)) {
+ replace_embedder_tool_hook(name, installed.previous);
+ }
+ }
+ if let Some(hook) = hook {
+ let hook: Arc<dyn ToolHook> =
+ Arc::new(super::live_hooks::NamedToolHook(name.to_owned(), hook));
+ let previous = embedder_tool_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name);
+ replace_embedder_tool_hook(name, Some(hook.clone()));
+ self.tool_hooks.push(InstalledHook {
+ name: name.to_owned(),
+ ours: hook,
+ previous,
+ });
+ }
+ }
/// Install the live policy, if one was given, against the booted config's
/// directories. Call after the core's bootstrap has installed its own.
pub(crate) fn install_live_policy(
diff --git a/crates/openhuman-embed/src/runtime/seams_tests.rs b/crates/openhuman-embed/src/runtime/seams_tests.rs
index 00916d0ef7..571f75166a 100644
--- a/crates/openhuman-embed/src/runtime/seams_tests.rs
+++ b/crates/openhuman-embed/src/runtime/seams_tests.rs
@@ -39,6 +39,53 @@ impl PostTurnHook for NamedPostTurn {
struct NamedToolHook(&'static str);
+#[test]
+fn live_replacement_and_removal_update_builder_hooks_and_restore_predecessors() {
+ let name = "seams-live-builder-hook";
+ let original: Arc<dyn PostTurnHook> = Arc::new(NamedPostTurn(name));
+ replace_embedder_post_turn_hook(name, Some(original.clone()));
+ let mut seams = HostSeams {
+ post_turn_hooks: vec![Arc::new(NamedPostTurn(name))],
+ ..Default::default()
+ }
+ .install()
+ .unwrap();
+ seams.post_turn_hook(
+ name,
+ Some(Arc::new(NamedPostTurn("different-diagnostic-name"))),
+ );
+ assert_eq!(post_turn_marker(name), Some(1));
+ assert_eq!(post_turn_marker("different-diagnostic-name"), None);
+ seams.post_turn_hook(name, None);
+ assert!(Arc::ptr_eq(
+ &embedder_post_turn_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name)
+ .unwrap(),
+ &original
+ ));
+ seams.tool_hook(
+ "seams-live-tool",
+ Some(Arc::new(NamedToolHook("different-tool-name"))),
+ );
+ assert!(embedder_tool_hooks()
+ .iter()
+ .any(|hook| hook.name() == "seams-live-tool"));
+ seams.tool_hook("seams-live-tool", None);
+ assert!(!embedder_tool_hooks()
+ .iter()
+ .any(|hook| hook.name() == "seams-live-tool"));
+ drop(seams);
+ assert!(Arc::ptr_eq(
+ &embedder_post_turn_hooks()
+ .into_iter()
+ .find(|hook| hook.name() == name)
+ .unwrap(),
+ &original
+ ));
+ replace_embedder_post_turn_hook(name, None);
+}
+
#[async_trait::async_trait]
impl ToolHook for NamedToolHook {
fn name(&self) -> &str {
diff --git a/crates/openhuman-embed/src/runtime/selection.rs b/crates/openhuman-embed/src/runtime/selection.rs
new file mode 100644
index 0000000000..30ab123ced
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/selection.rs
@@ -0,0 +1,243 @@
+//! Runtime module selection is independent from Cargo dependency selection.
+use super::{RuntimeBuilder, RuntimeError};
+use crate::{DomainSet, GroupMode, ServiceSet, ToolGroups};
+/// Module families selectable as a coordinated domain/service/tool-group unit.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum RuntimeModule {
+ /// Agent definitions, orchestration and model/tool turns.
+ Agent,
+ /// Memory records and agent recall.
+ Memory,
+ /// Model routing and inference; does not require the microphone feature.
+ Inference,
+ /// Skill registry and execution.
+ Skills,
+ /// MCP server clients and tool discovery.
+ Mcp,
+ /// Workflow graph execution.
+ Flows,
+ /// Message channels and listeners.
+ Channels,
+ /// Speech input and output.
+ Voice,
+ /// Image and video generation.
+ Media,
+ /// Wallet and payment tools.
+ Web3,
+ /// External connector actions.
+ Integrations,
+ /// Scheduled jobs.
+ Automation,
+ /// Code execution runtimes.
+ Runtimes,
+ /// Loadable native module host.
+ Modules,
+ /// Office document extraction and generation tools.
+ Documents,
+ /// Hosting provider deployment tools.
+ Hosting,
+}
+impl RuntimeModule {
+ /// Cargo gate required by this module, when it has one.
+ pub fn required_feature(self) -> Option<&'static str> {
+ match self {
+ Self::Skills => Some("skills"),
+ Self::Mcp => Some("mcp"),
+ Self::Flows => Some("flows"),
+ Self::Channels => Some("channels"),
+ Self::Voice => Some("voice"),
+ Self::Media => Some("media"),
+ Self::Web3 => Some("web3"),
+ Self::Modules => Some("modules"),
+ Self::Documents => Some("documents"),
+ Self::Hosting => Some("hosting"),
+ _ => None,
+ }
+ }
+}
+/// Approximate runtime activity, not a claim about compile-time dependency size.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum WeightClass {
+ /// Agent and memory only, without background services.
+ Lean,
+ /// Agent core with compiled skills, MCP and workflows.
+ Standard,
+ /// All compiled module families and their supporting services.
+ Full,
+ /// An explicit selection or manually configured builder.
+ Custom,
+}
+#[derive(Clone)]
+pub(crate) struct ModuleSelection {
+ pub modules: Vec<RuntimeModule>,
+ pub weight: WeightClass,
+}
+impl RuntimeBuilder {
+ /// Agent and memory only; no background services or optional tool groups.
+ /// Pair with `--no-default-features` to disable Cargo default feature gates.
+ pub fn lean() -> Self {
+ Self::new()
+ .modules([
+ RuntimeModule::Agent,
+ RuntimeModule::Memory,
+ RuntimeModule::Inference,
+ ])
+ .weight(WeightClass::Lean)
+ }
+ /// Agent core plus the compiled skills, MCP and workflow families. No background services.
+ pub fn standard() -> Self {
+ let features = openhuman_core::core::runtime::compiled_features();
+ let mut modules = vec![
+ RuntimeModule::Agent,
+ RuntimeModule::Memory,
+ RuntimeModule::Inference,
+ ];
+ for module in [
+ RuntimeModule::Skills,
+ RuntimeModule::Mcp,
+ RuntimeModule::Flows,
+ ] {
+ if module.required_feature().is_some_and(|f| features[f]) {
+ modules.push(module);
+ }
+ }
+ Self::new().modules(modules).weight(WeightClass::Standard)
+ }
+ /// All available module families, with their supporting background services.
+ pub fn full() -> Self {
+ use RuntimeModule::*;
+ let features = openhuman_core::core::runtime::compiled_features();
+ let modules = [
+ Agent,
+ Memory,
+ Inference,
+ Skills,
+ Mcp,
+ Flows,
+ Channels,
+ Voice,
+ Media,
+ Web3,
+ Integrations,
+ Automation,
+ Runtimes,
+ Modules,
+ Documents,
+ Hosting,
+ ]
+ .into_iter()
+ .filter(|m| m.required_feature().is_none_or(|f| features[f]));
+ let mut builder = Self::new().modules(modules).weight(WeightClass::Full);
+ let domains = builder.domains.unwrap();
+ builder.services = Some(ServiceSet {
+ harness_init: true,
+ cron: domains.automation,
+ channels: domains.channels,
+ integrations: domains.integrations,
+ memory_queue: domains.memory,
+ memory_sync: domains.memory,
+ skill_catalog_refresh: domains.skills,
+ mcp_boot: domains.mcp,
+ ..ServiceSet::none()
+ });
+ builder
+ }
+ fn weight(mut self, weight: WeightClass) -> Self {
+ if let Some(s) = &mut self.selection {
+ s.weight = weight;
+ }
+ self
+ }
+ /// Select exactly these families; missing Cargo gates are rejected before boot.
+ pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self {
+ let mut modules: Vec<_> = modules.into_iter().collect();
+ modules.sort();
+ modules.dedup();
+ let mut d = DomainSet::kernel();
+ let mut g = ToolGroups::none();
+ for module in &modules {
+ match module {
+ RuntimeModule::Agent => d.agent = true,
+ RuntimeModule::Memory => d.memory = true,
+ RuntimeModule::Inference => d.inference = true,
+ RuntimeModule::Skills => {
+ d.skills = true;
+ g = g.with("skills", GroupMode::Withheld);
+ }
+ RuntimeModule::Mcp => {
+ d.mcp = true;
+ g = g.with("mcp", GroupMode::Withheld);
+ }
+ RuntimeModule::Flows => {
+ d.flows = true;
+ g = g.with("workflows", GroupMode::Withheld);
+ }
+ RuntimeModule::Channels => d.channels = true,
+ RuntimeModule::Voice => {
+ d.voice = true;
+ g = g.with("audio", GroupMode::Withheld);
+ }
+ RuntimeModule::Media => {
+ d.media = true;
+ g = g.with("media", GroupMode::Withheld);
+ }
+ RuntimeModule::Web3 => {
+ d.web3 = true;
+ g = g.with("web3", GroupMode::Withheld);
+ }
+ RuntimeModule::Integrations => {
+ d.integrations = true;
+ g = g.with("composio", GroupMode::Withheld);
+ }
+ RuntimeModule::Automation => {
+ d.automation = true;
+ g = g.with("scheduling", GroupMode::Withheld);
+ }
+ RuntimeModule::Runtimes => {
+ d.runtimes = true;
+ g = g.with("coding", GroupMode::Withheld);
+ }
+ RuntimeModule::Modules => d.modules = true,
+ RuntimeModule::Documents => {
+ d.modules = true;
+ d.platform = true;
+ g = g.with("documents", GroupMode::Withheld);
+ }
+ RuntimeModule::Hosting => d.platform = true,
+ }
+ }
+ self.domains = Some(d);
+ self.tool_groups = Some(g);
+ self.services = Some(ServiceSet {
+ harness_init: d.agent,
+ skill_catalog_refresh: d.skills,
+ mcp_boot: d.mcp,
+ ..ServiceSet::none()
+ });
+ self.selection = Some(ModuleSelection {
+ modules,
+ weight: WeightClass::Custom,
+ });
+ self
+ }
+ pub(super) fn validate_modules(&self) -> Result<(), RuntimeError> {
+ let features = openhuman_core::core::runtime::compiled_features();
+ if let Some(selection) = &self.selection {
+ for module in &selection.modules {
+ if let Some(feature) = module.required_feature() {
+ if !features[feature] {
+ return Err(RuntimeError::MissingFeature {
+ module: *module,
+ feature,
+ });
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/openhuman-embed/src/runtime/summary.rs b/crates/openhuman-embed/src/runtime/summary.rs
index 4739d9e13e..c4934eaf10 100644
--- a/crates/openhuman-embed/src/runtime/summary.rs
+++ b/crates/openhuman-embed/src/runtime/summary.rs
@@ -19,28 +19,45 @@ use crate::harness::Workspace;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct BuilderSummary {
+ /// Requested host identity before workspace resolution.
pub host_kind: HostKind,
+ /// Workspace ownership and layout selection.
pub workspace: Workspace,
+ /// Optional runtime state directory override.
pub workspace_dir: Option<PathBuf>,
+ /// Optional acting-tool root override.
pub action_dir: Option<PathBuf>,
+ /// Whether the host supplies or the core discovers configuration.
pub config_source: ConfigSource,
+ /// Explicit domain-family selection, if supplied.
pub domains: Option<DomainSet>,
+ /// Explicit service selection, if supplied.
pub services: Option<ServiceSet>,
/// `true` for [`TokenSource::Fixed`].
pub fixed_token: bool,
+ /// Optional transport bind host.
pub listen_host: Option<String>,
+ /// Optional transport bind port.
pub listen_port: Option<u16>,
+ /// Whether a backend API key was supplied, without exposing it.
pub has_api_key: bool,
+ /// Whether a backend transport was supplied.
pub has_backend_transport: bool,
+ /// Whether a host memory engine was supplied.
pub has_memory_engine: bool,
+ /// Whether a host session store was supplied.
pub has_session_store: bool,
/// The group of each controller extension, in registration order.
pub controller_extensions: Vec<DomainGroup>,
/// The [`kind`](tinytools::ToolRanker::kind) of the tool ranker.
pub tool_ranker: Option<String>,
+ /// Names of configured post-turn hooks.
pub post_turn_hooks: Vec<String>,
+ /// Names of configured tool hooks.
pub tool_hooks: Vec<String>,
+ /// Whether a server launcher was supplied.
pub has_server_launcher: bool,
+ /// Whether a live policy override was supplied.
pub has_live_policy: bool,
}
diff --git a/crates/openhuman-embed/src/stream.rs b/crates/openhuman-embed/src/stream.rs
new file mode 100644
index 0000000000..fa29049791
--- /dev/null
+++ b/crates/openhuman-embed/src/stream.rs
@@ -0,0 +1,85 @@
+//! 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 {
+ tokio::select! {
+ biased;
+ item = progress_rx.recv() => {
+ if let Some(item) = item {
+ tokio::select! {
+ 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;
+ }
+ }
+ 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;
+ }
+ }
+ }
+ });
+ 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 --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 0f453a9b69..2806e804c8 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -257,6 +257,8 @@ pub struct Turn {
meter: Option<Box<dyn FnOnce(Option<LastTurnUsage>) + Send>>,
response_format: Option<crate::complete::ResponseFormat>,
max_tokens: Option<u32>,
+ top_p: Option<f64>,
+ cancellation: Option<crate::CancellationToken>,
untrusted_input: bool,
}
@@ -272,6 +274,8 @@ impl Turn {
meter: None,
response_format: None,
max_tokens: None,
+ top_p: None,
+ cancellation: None,
untrusted_input: false,
}
}
@@ -446,6 +450,27 @@ impl Turn {
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
+ }
+
+ pub(crate) fn stream_cancellation(&self) -> crate::CancellationToken {
+ self.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
@@ -463,7 +488,7 @@ impl Turn {
/// Run the turn.
///
/// Establishes the origin and progress scopes described in the module docs,
- /// then dispatches through [`call`](super::call::call) so the
+ /// then dispatches through `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.
@@ -474,6 +499,59 @@ impl Turn {
/// 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> {
+ let token = self.cancellation.take().unwrap_or_default();
+ openhuman_core::agent::host_overrides::with_cancellation(token, self.send_observed()).await
+ }
+
+ async fn send_observed(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_inner().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 cancellation = openhuman_core::agent::host_overrides::current_cancellation();
+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);
+ self.progress = Some(tx);
+ let mut dispatch = Box::pin(self.send_inner());
+ let outcome = loop {
+ tokio::select! {
+ biased;
+ item = rx.recv() => if let Some(item) = item { observe_progress(&hub, &agent_id, &turn_id, &item); if let Some(sink) = &forward { tokio::select! { _ = sink.send(item) => {}, _ = cancellation.cancelled() => {} } } } else { break dispatch.await; },
+ result = &mut dispatch => break result,
+ }
+ };
+ while let Ok(item) = rx.try_recv() {
+ observe_progress(&hub, &agent_id, &turn_id, &item);
+ if let Some(sink) = &forward {
+ tokio::select! { _ = sink.send(item) => {}, _ = cancellation.cancelled() => {} }
+ }
+ }
+ end.success = outcome.is_ok();
+ outcome
+ }
+
+ 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
@@ -535,11 +613,20 @@ impl Turn {
.take()
.map(crate::complete::ResponseFormat::into_wire),
max_output_tokens: self.max_tokens,
+ top_p: self.top_p,
},
),
untrusted_input: self.untrusted_input,
};
- let dispatch = dispatch(self.target, self.request, self.seed.take(), &usage, options);
+ let dispatch: std::pin::Pin<
+ Box<dyn std::future::Future<Output = Result<AgentReply, CoreError>> + Send + '_>,
+ > = Box::pin(dispatch(
+ self.target,
+ self.request,
+ self.seed.take(),
+ &usage,
+ options,
+ ));
let reply = match (self.origin, self.progress) {
(Some(origin), Some(sink)) => {
@@ -628,10 +715,22 @@ impl Turn {
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() {
+ if self.response_format.is_some()
+ || self.max_tokens.is_some()
+ || self.top_p.is_some()
+ {
return refuse(
"response_format and max_tokens need a runtime-owned Agent",
"turn_shape_unsupported",
@@ -810,3 +909,52 @@ pub fn absolute(dir: impl AsRef<Path>) -> std::io::Result<PathBuf> {
#[cfg(test)]
#[path = "turn_tests.rs"]
mod tests;
+
+fn event_thread_id(origin: Option<&AgentTurnOrigin>, session_id: &str) -> String {
+ match origin {
+ Some(AgentTurnOrigin::WebChat { thread_id, .. }) => thread_id.clone(),
+ _ => session_id.to_owned(),
+ }
+}
+
+struct ObservedTurn {
+ hub: Arc<crate::events::EventHub>,
+ agent_id: Option<String>,
+ thread_id: String,
+ turn_id: String,
+ success: bool,
+}
+impl Drop for ObservedTurn {
+ fn drop(&mut self) {
+ self.hub.end_turn(
+ self.agent_id.clone(),
+ &self.thread_id,
+ &self.turn_id,
+ self.success,
+ );
+ }
+}
+fn observe_progress(
+ hub: &crate::events::EventHub,
+ agent_id: &Option<String>,
+ turn_id: &str,
+ item: &AgentProgress,
+) {
+ let kind = match item {
+ AgentProgress::ToolCallStarted { tool_name, .. } => {
+ Some(crate::RuntimeEventKind::ToolStarted {
+ tool_name: tool_name.clone(),
+ })
+ }
+ AgentProgress::ToolCallCompleted {
+ tool_name, success, ..
+ } => Some(crate::RuntimeEventKind::ToolEnded {
+ tool_name: tool_name.clone(),
+ success: *success,
+ }),
+ _ => None,
+ };
+ if let Some(kind) = kind {
+ hub.emit(agent_id.clone(), Some(turn_id.to_owned()), kind);
+ }
+}
diff --git a/crates/openhuman-embed/src/turn_tests.rs b/crates/openhuman-embed/src/turn_tests.rs
index 9f9edc49d6..f9d9a51ae6 100644
--- a/crates/openhuman-embed/src/turn_tests.rs
+++ b/crates/openhuman-embed/src/turn_tests.rs
@@ -264,3 +264,66 @@ fn a_turn_outcome_carries_what_the_turn_spent() {
};
assert_ne!(unmetered, outcome);
}
+
+#[test]
+fn approval_event_correlation_uses_the_web_chat_origin_without_replacing_session_identity() {
+ let origin = AgentTurnOrigin::WebChat {
+ thread_id: "approval-thread".into(),
+ client_id: "client".into(),
+ request_id: None,
+ };
+ let session = "durable-session";
+ assert_eq!(event_thread_id(Some(&origin), session), "approval-thread");
+ assert_eq!(
+ event_thread_id(Some(&AgentTurnOrigin::Cli), session),
+ session
+ );
+ assert_eq!(event_thread_id(None, session), session);
+}
+
+#[tokio::test]
+async fn runtime_tool_events_preserve_order_and_discard_tool_payloads() {
+ let hub = crate::events::EventHub::new(8);
+ let mut events = hub.subscribe();
+ let agent = Some("a".to_owned());
+ let private = "private-tool-content";
+ let started = crate::AgentProgress::ToolCallStarted {
+ call_id: private.into(),
+ tool_name: "host_tool".into(),
+ arguments: serde_json::json!({"input": private}),
+ iteration: 1,
+ display_label: Some(private.into()),
+ display_detail: Some(private.into()),
+ };
+ let completed = crate::AgentProgress::ToolCallCompleted {
+ call_id: private.into(),
+ tool_name: "host_tool".into(),
+ success: true,
+ output_chars: private.len(),
+ output: private.into(),
+ arguments: Some(serde_json::json!({"input": private})),
+ elapsed_ms: 1,
+ iteration: 1,
+ failure: None,
+ display_label: Some(private.into()),
+ display_detail: Some(private.into()),
+ structured: Some(serde_json::json!({"output": private})),
+ };
+ observe_progress(&hub, &agent, "turn-a", &started);
+ observe_progress(&hub, &agent, "turn-a", &completed);
+ for expected in [
+ crate::RuntimeEventKind::ToolStarted {
+ tool_name: "host_tool".into(),
+ },
+ crate::RuntimeEventKind::ToolEnded {
+ tool_name: "host_tool".into(),
+ success: true,
+ },
+ ] {
+ let event = events.recv().await.unwrap();
+ assert_eq!(event.agent_id.as_deref(), Some("a"));
+ assert_eq!(event.turn_id.as_deref(), Some("turn-a"));
+ assert_eq!(event.kind, expected);
+ assert!(!serde_json::to_string(&event).unwrap().contains(private));
+ }
+}
diff --git a/crates/openhuman-embed/tests/approval_lifecycle.rs b/crates/openhuman-embed/tests/approval_lifecycle.rs
new file mode 100644
index 0000000000..1a164325fd
--- /dev/null
+++ b/crates/openhuman-embed/tests/approval_lifecycle.rs
@@ -0,0 +1,466 @@
+//! Removed agents cannot leave approval callbacks or polling handles attached to reused IDs.
+mod common;
+
+use async_trait::async_trait;
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentError, AgentSpec, AgentTurnOrigin, ApprovalDecision,
+ ApprovalHandler, ApprovalsError, HostTurnTools, PendingApproval, Runtime, Tool, ToolScopeSpec,
+ TrustedAccess,
+};
+use std::collections::BTreeSet;
+use std::path::Path;
+use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc, Condvar, Mutex,
+};
+use std::time::Duration;
+use tokio::sync::mpsc;
+
+struct ApproveAndRecord {
+ label: &'static str,
+ calls: Arc<AtomicUsize>,
+ seen: mpsc::UnboundedSender<&'static str>,
+}
+#[async_trait]
+impl ApprovalHandler for ApproveAndRecord {
+ async fn decide(&self, _: &PendingApproval) -> ApprovalDecision {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ let _ = self.seen.send(self.label);
+ ApprovalDecision::ApproveOnce
+ }
+}
+
+struct WaitForRemoval {
+ label: &'static str,
+ started: mpsc::UnboundedSender<(&'static str, String)>,
+ dropped: mpsc::UnboundedSender<&'static str>,
+}
+struct DecisionDrop {
+ label: &'static str,
+ dropped: mpsc::UnboundedSender<&'static str>,
+}
+impl Drop for DecisionDrop {
+ fn drop(&mut self) {
+ let _ = self.dropped.send(self.label);
+ }
+}
+#[async_trait]
+impl ApprovalHandler for WaitForRemoval {
+ async fn decide(&self, request: &PendingApproval) -> ApprovalDecision {
+ let _guard = DecisionDrop {
+ label: self.label,
+ dropped: self.dropped.clone(),
+ };
+ let _ = self.started.send((self.label, request.request_id.clone()));
+ std::future::pending().await
+ }
+}
+
+fn supervised(id: &str, scratch: &Path, provider: &wiremock::MockServer) -> AgentSpec {
+ AgentSpec::new(id)
+ .provider(common::route(provider, "approval-fixture"))
+ .action_dir(scratch)
+ .access(
+ Access::supervised()
+ .origin(AgentTurnOrigin::WebChat {
+ thread_id: id.into(),
+ client_id: "lifecycle-test".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(scratch.display().to_string(), TrustedAccess::ReadWrite),
+ )
+ .definition(AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])))
+}
+
+async fn writing_provider(marker: &Path) -> wiremock::MockServer {
+ common::scripted_provider(
+ vec![common::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", marker.display())}).to_string(),
+ )],
+ "denied without writing",
+ )
+ .await
+}
+
+#[test]
+fn removal_invalidates_approval_handles_and_reserves_ids_until_cleanup() {
+ common::runtime()
+ .block_on(async {
+ tokio::spawn(async {
+ let backend = common::stub_backend().await;
+ let provider = common::provider("no tools").await;
+ let scratch = tempfile::tempdir().unwrap();
+ let mut config = common::offline_config();
+ config.autonomy.enabled = true;
+ let runtime = Arc::new(Runtime::builder()
+ .config(config)
+ .backend_url(backend.uri())
+ .provider(common::route(&provider, "approval-fixture"))
+ .build()
+ .await
+ .unwrap());
+ let builder_calls = Arc::new(AtomicUsize::new(0));
+ let live_calls = Arc::new(AtomicUsize::new(0));
+ let (old_seen, mut old_seen_rx) = mpsc::unbounded_channel();
+ let original = runtime
+ .agent(supervised("reused", scratch.path(), &provider).approval_handler(Arc::new(
+ ApproveAndRecord {
+ label: "removed builder callback",
+ calls: builder_calls.clone(),
+ seen: old_seen.clone(),
+ },
+ )))
+ .unwrap();
+ let original_polling = original.approvals();
+ let original_subscription = original.handle_approvals(Arc::new(ApproveAndRecord {
+ label: "removed live callback",
+ calls: live_calls.clone(),
+ seen: old_seen,
+ }));
+ runtime.remove_agent("reused").await.unwrap();
+ assert!(original_polling.pending().unwrap().is_empty());
+
+ let marker = scratch.path().join("replacement-must-not-write");
+ let replacement_provider = writing_provider(&marker).await;
+ let (started, mut started_rx) = mpsc::unbounded_channel();
+ let (dropped, mut dropped_rx) = mpsc::unbounded_channel();
+ let replacement = runtime
+ .agent(
+ supervised("reused", scratch.path(), &replacement_provider).approval_handler(
+ Arc::new(WaitForRemoval {
+ label: "replacement",
+ started,
+ dropped,
+ }),
+ ),
+ )
+ .unwrap();
+ let turning = replacement.clone();
+ let turn = tokio::spawn(async move { turning.run("Create a marker").await });
+ let request_id = tokio::time::timeout(Duration::from_secs(10), async {
+ tokio::select! {
+ biased;
+ Some(old) = old_seen_rx.recv() => panic!("removed callback observed replacement approval: {old:?}"),
+ request = started_rx.recv() => request.expect("replacement callback starts").1,
+ }
+ })
+ .await
+ .expect("replacement approval reaches its callback");
+ assert!(!marker.exists(), "replacement write remains parked");
+ assert_eq!(builder_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(live_calls.load(Ordering::SeqCst), 0);
+ assert!(
+ original_polling.pending().unwrap().is_empty(),
+ "removed polling handle must not see the replacement's request"
+ );
+ assert!(matches!(
+ original_polling.decide(&request_id, ApprovalDecision::ApproveOnce),
+ Err(ApprovalsError::NotFound(_))
+ ));
+ assert!(replacement
+ .approvals()
+ .pending()
+ .unwrap()
+ .iter()
+ .any(|request| request.request_id == request_id));
+ replacement
+ .approvals()
+ .decide(&request_id, ApprovalDecision::Deny)
+ .unwrap();
+ assert_eq!(
+ tokio::time::timeout(Duration::from_secs(10), turn)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap()
+ .reply,
+ "denied without writing"
+ );
+ runtime.remove_agent("reused").await.unwrap();
+ assert_eq!(
+ tokio::time::timeout(Duration::from_secs(10), dropped_rx.recv())
+ .await
+ .unwrap(),
+ Some("replacement")
+ );
+ assert!(!marker.exists());
+ assert_eq!(builder_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(live_calls.load(Ordering::SeqCst), 0);
+
+ // Removal also destroys callbacks already waiting on an original
+ // request, while both the agent and returned subscription remain live.
+ let marker = scratch.path().join("inflight-must-not-write");
+ let inflight_provider = writing_provider(&marker).await;
+ let (started, mut started_rx) = mpsc::unbounded_channel();
+ let (dropped, mut dropped_rx) = mpsc::unbounded_channel();
+ let inflight = runtime
+ .agent(
+ supervised("inflight", scratch.path(), &inflight_provider).approval_handler(
+ Arc::new(WaitForRemoval {
+ label: "builder",
+ started: started.clone(),
+ dropped: dropped.clone(),
+ }),
+ ),
+ )
+ .unwrap();
+ let inflight_subscription = inflight.handle_approvals(Arc::new(WaitForRemoval {
+ label: "live",
+ started,
+ dropped,
+ }));
+ let turning = inflight.clone();
+ let turn = tokio::spawn(async move { turning.run("Create a marker").await });
+ let mut callbacks = BTreeSet::new();
+ for _ in 0..2 {
+ let (label, _) = tokio::time::timeout(Duration::from_secs(10), started_rx.recv())
+ .await
+ .unwrap()
+ .expect("callback starts");
+ callbacks.insert(label);
+ }
+ assert_eq!(callbacks, BTreeSet::from(["builder", "live"]));
+ runtime.remove_agent("inflight").await.unwrap();
+ let mut destroyed = BTreeSet::new();
+ for _ in 0..2 {
+ destroyed.insert(
+ tokio::time::timeout(Duration::from_secs(10), dropped_rx.recv())
+ .await
+ .expect("agent removal drops the pending decision future")
+ .unwrap(),
+ );
+ }
+ assert_eq!(destroyed, callbacks);
+ let _ = tokio::time::timeout(Duration::from_secs(10), turn)
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(inflight.approvals().pending().unwrap().is_empty());
+ assert!(!marker.exists());
+ drop(inflight_subscription);
+ drop(inflight);
+ drop(replacement);
+ drop(original_subscription);
+ drop(original);
+ removal_reserves_ids_until_cleanup_finishes(runtime.clone(), scratch.path()).await;
+ natural_drop_reserves_id_until_state_teardown_finishes(runtime.clone()).await;
+ drop(runtime);
+ })
+ .await
+ .expect("approval lifecycle worker did not panic");
+ });
+}
+
+#[derive(Default)]
+struct DropBarrier {
+ released: Mutex<bool>,
+ changed: Condvar,
+}
+impl DropBarrier {
+ fn release(&self) {
+ *self.released.lock().unwrap() = true;
+ self.changed.notify_all();
+ }
+ fn wait(&self) {
+ let mut released = self.released.lock().unwrap();
+ while !*released {
+ released = self.changed.wait(released).unwrap();
+ }
+ }
+}
+// Always unblock a worker when an assertion unwinds the fixture.
+struct ReleaseBarrier(Arc<DropBarrier>);
+impl Drop for ReleaseBarrier {
+ fn drop(&mut self) {
+ self.0.release();
+ }
+}
+struct BlockingDecisionDrop {
+ barrier: Arc<DropBarrier>,
+ dropping: mpsc::UnboundedSender<()>,
+}
+impl Drop for BlockingDecisionDrop {
+ fn drop(&mut self) {
+ let _ = self.dropping.send(());
+ // Hand the worker queue to another worker while holding teardown,
+ // so the test can observe the destructor-start signal.
+ tokio::task::block_in_place(|| self.barrier.wait());
+ }
+}
+struct RemovalTool {
+ barrier: Arc<DropBarrier>,
+ started: mpsc::UnboundedSender<()>,
+ dropping: mpsc::UnboundedSender<()>,
+}
+#[async_trait]
+impl Tool for RemovalTool {
+ fn name(&self) -> &str {
+ "wait_for_removal"
+ }
+ fn description(&self) -> &str {
+ "A host-owned fixture held until the agent is removed"
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object", "properties": {}})
+ }
+ async fn execute(
+ &self,
+ _: serde_json::Value,
+ ) -> anyhow::Result<openhuman_core::tools::ToolResult> {
+ let _guard = BlockingDecisionDrop {
+ barrier: self.barrier.clone(),
+ dropping: self.dropping.clone(),
+ };
+ let _ = self.started.send(());
+ std::future::pending().await
+ }
+}
+
+async fn removal_reserves_ids_until_cleanup_finishes(runtime: Arc<Runtime>, scratch: &Path) {
+ for cancel in [false, true] {
+ let id = if cancel {
+ "cancelled-removal"
+ } else {
+ "concurrent-removal"
+ };
+ let provider = common::scripted_provider(
+ vec![common::tool_call_completion("wait_for_removal", "{}")],
+ "unreachable",
+ )
+ .await;
+ let barrier = Arc::new(DropBarrier::default());
+ let release_on_unwind = ReleaseBarrier(barrier.clone());
+ let (started, mut started_rx) = mpsc::unbounded_channel();
+ let (dropping, mut dropping_rx) = mpsc::unbounded_channel();
+ let tool_barrier = barrier.clone();
+ let original = runtime
+ .agent(
+ AgentSpec::new(id)
+ .provider(common::route(&provider, "removal-fixture"))
+ .action_dir(scratch)
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use wait_for_removal.")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ HostTurnTools::advertised(vec![Box::new(RemovalTool {
+ barrier: tool_barrier.clone(),
+ started: started.clone(),
+ dropping: dropping.clone(),
+ })])
+ }),
+ )
+ .unwrap();
+ let home = original.home_dir().to_path_buf();
+ let turning = original.clone();
+ let turn = tokio::spawn(async move { turning.run("Wait until removed").await });
+ tokio::time::timeout(Duration::from_secs(10), started_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ let removing_runtime = runtime.clone();
+ let removing = tokio::spawn(async move { removing_runtime.remove_agent(id).purge().await });
+ // The turn's destructor has begun but cannot release its in-flight
+ // accounting yet, so removal is deterministically waiting for idle.
+ tokio::time::timeout(Duration::from_secs(10), dropping_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ assert!(
+ runtime.agent_ids().iter().any(|reserved| reserved == id),
+ "removal must retain the id reservation until cleanup finishes"
+ );
+ assert!(
+ openhuman_core::agent::host_agents::resolve(id).is_none(),
+ "removed agents must not admit new sessions through core drivers"
+ );
+ assert!(
+ matches!(runtime.remove_agent(id).await, Err(AgentError::UnknownId(ref removed)) if removed == id),
+ "a second removal cannot claim the same cleanup reservation"
+ );
+ let replacement = runtime.agent(AgentSpec::new(id));
+ assert!(
+ matches!(replacement, Err(AgentError::DuplicateId(ref duplicate)) if duplicate == id),
+ "the id must remain reserved while removal waits for a turn to unwind"
+ );
+ if cancel {
+ removing.abort();
+ assert!(removing.await.unwrap_err().is_cancelled());
+ assert!(
+ !home.exists(),
+ "cancelling removal still performs requested purge"
+ );
+ barrier.release();
+ } else {
+ barrier.release();
+ removing.await.unwrap().unwrap();
+ assert!(
+ !home.exists(),
+ "normal removal performs purge before releasing the id"
+ );
+ }
+ tokio::time::timeout(Duration::from_secs(10), turn)
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap_err();
+ // Keep the original handle live: cancellation must clean up now,
+ // rather than relying on its eventual destructor.
+ let replacement = runtime
+ .agent(AgentSpec::new(id))
+ .expect("cleanup releases the reserved id");
+ assert!(original.approvals().pending().unwrap().is_empty());
+ runtime.remove_agent(id).await.unwrap();
+ drop(replacement);
+ drop(original);
+ drop(release_on_unwind);
+ }
+}
+
+#[derive(Default)]
+struct BlockingStateSlot(Mutex<Option<BlockingDecisionDrop>>);
+
+async fn natural_drop_reserves_id_until_state_teardown_finishes(runtime: Arc<Runtime>) {
+ let id = "natural-drop";
+ let original = runtime.agent(AgentSpec::new(id)).unwrap();
+ let context = openhuman_core::core::runtime::AgentContextRegistry::get(id).unwrap();
+ let barrier = Arc::new(DropBarrier::default());
+ let release_on_unwind = ReleaseBarrier(barrier.clone());
+ let (dropping, mut dropping_rx) = mpsc::unbounded_channel();
+ let slot = context.agent_state().slot::<BlockingStateSlot>();
+ *slot.0.lock().unwrap() = Some(BlockingDecisionDrop {
+ barrier: barrier.clone(),
+ dropping,
+ });
+ drop(slot);
+ let dropping_agent = tokio::task::spawn_blocking(move || drop(original));
+ tokio::time::timeout(Duration::from_secs(10), dropping_rx.recv())
+ .await
+ .unwrap()
+ .unwrap();
+ // The last Agent Arc is already gone, but its destructor is still
+ // clearing old-instance state before evicting the keyed MCP host.
+ assert!(
+ runtime.agent_ids().iter().any(|reserved| reserved == id),
+ "the natural destructor keeps its id reserved until teardown finishes"
+ );
+ assert!(
+ matches!(runtime.agent(AgentSpec::new(id)), Err(AgentError::DuplicateId(ref duplicate)) if duplicate == id)
+ );
+ barrier.release();
+ dropping_agent.await.unwrap();
+ assert!(context.agent_state().is_empty());
+ let replacement = runtime
+ .agent(AgentSpec::new(id))
+ .expect("natural teardown releases its id");
+ // Later release of a retained old context cannot unregister the new one.
+ drop(context);
+ assert!(openhuman_core::core::runtime::AgentContextRegistry::get(id).is_some());
+ runtime.remove_agent(id).await.unwrap();
+ drop(replacement);
+ drop(release_on_unwind);
+}
diff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rs
index 5735e5ba51..22d75e8fc0 100644
--- a/crates/openhuman-embed/tests/common/mod.rs
+++ b/crates/openhuman-embed/tests/common/mod.rs
@@ -64,6 +64,19 @@ pub fn offline_config() -> Config {
/// sub-agent and aborts the whole process, so building it the documented way is
/// both what the test needs and a check that the documented way works.
pub fn runtime() -> tokio::runtime::Runtime {
+ // Hosts initialize encryption before an API key is persisted by runtime
+ // boot. The runner supplies a disposable master key for headless tests.
+ if std::env::var_os("OPENHUMAN_KEYRING_MASTER_KEY").is_some() {
+ static KEY_ROOT: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
+ let root = KEY_ROOT.get_or_init(|| tempfile::tempdir().expect("fixture key root"));
+ std::env::set_var("OPENHUMAN_WORKSPACE", root.path());
+ openhuman_embed::process::init_master_key().expect("fixture master key initializes");
+ }
+ runtime_without_master_key()
+}
+
+/// A tuned async runtime for profile hosts which initialize keys after choosing their root.
+pub fn runtime_without_master_key() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_stack_size(AGENT_WORKER_STACK_BYTES)
diff --git a/crates/openhuman-embed/tests/isolation_autonomy.rs b/crates/openhuman-embed/tests/isolation_autonomy.rs
index 5f7b6b5345..42b2ef4550 100644
--- a/crates/openhuman-embed/tests/isolation_autonomy.rs
+++ b/crates/openhuman-embed/tests/isolation_autonomy.rs
@@ -8,8 +8,8 @@
mod common;
use common::{
- eventually, offline_config, route, runtime, scripted_provider, stub_backend,
- tool_call_completion,
+ chat_requests, eventually, offline_config, route, runtime, scripted_provider, stub_backend,
+ tool_call_completion, tool_results,
};
use openhuman_core::security::AutonomyLevel;
use openhuman_embed::{
@@ -73,10 +73,15 @@ fn every_agent_answers_policy_from_its_own_tier() {
assert_eq!(a.config().autonomy.level, AutonomyLevel::ReadOnly);
let a_out = a.run("write the marker").await.expect("a's turn returns");
assert!(!a_file.exists(), "a read-only agent must not write");
+ assert_eq!(
+ a_out.reply, "a-done",
+ "the provider controls the final reply"
+ );
+ let a_requests = chat_requests(&a_provider).await;
+ let refusal = a_requests.iter().map(tool_results).collect::<String>();
assert!(
- a_out.reply.contains("read-only mode"),
- "a's shell call is refused by its own tier: {}",
- a_out.reply
+ refusal.contains("read-only mode"),
+ "a's shell refusal is returned to its own provider: {refusal}"
);
// ── B: supervised, shell on its own allowlist; runs without parking ──
diff --git a/crates/openhuman-embed/tests/runtime_configuration.rs b/crates/openhuman-embed/tests/runtime_configuration.rs
new file mode 100644
index 0000000000..dd5ba0a0e6
--- /dev/null
+++ b/crates/openhuman-embed/tests/runtime_configuration.rs
@@ -0,0 +1,139 @@
+//! One process owns one runtime: verify defaults, templates and storage together.
+mod common;
+use common::{chat_requests, offline_config, provider, runtime};
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentError, AgentSpec, ModelDefaults, RuntimeBuilder, ServiceSet,
+ ToolScopeSpec,
+};
+
+#[test]
+fn runtime_defaults_templates_sampling_and_storage_are_isolated() {
+ runtime().block_on(async {
+ tokio::spawn(assert_runtime_configuration()).await.unwrap();
+ });
+}
+
+async fn assert_runtime_configuration() {
+ let provider = provider("configured reply").await;
+ let mut config = offline_config();
+ config.default_model = Some("gpt-4o-mini".into());
+ config.default_temperature = 0.1;
+ config.storage.url = Some("memory".into());
+ let rules: openhuman_embed::config::ToolRules = serde_json::from_value(
+ serde_json::json!({"rules":[{"effect":"deny","match":{"name":"shell"}}]}),
+ )
+ .unwrap();
+ let runtime = RuntimeBuilder::lean()
+ .config(config)
+ .services(ServiceSet::none())
+ .provider(openhuman_embed::Provider::openai_compatible(
+ format!("{}/v1", provider.uri()),
+ "local-test",
+ ))
+ .model_defaults(ModelDefaults {
+ temperature: Some(0.3),
+ max_tokens: Some(90),
+ top_p: Some(0.8),
+ max_iterations: Some(5),
+ })
+ .autonomy(openhuman_embed::config::AutonomyConfig {
+ max_actions_per_hour: 7,
+ ..Default::default()
+ })
+ .privacy(openhuman_embed::config::PrivacyConfig {
+ mode: openhuman_embed::config::PrivacyMode::Sensitive,
+ })
+ .cron(openhuman_embed::config::CronConfig {
+ enabled: false,
+ ..Default::default()
+ })
+ .secrets(openhuman_embed::config::SecretsConfig { encrypt: false })
+ .learning(openhuman_embed::LearningSettings {
+ build_beliefs_every: 21,
+ learnings_limit: 3,
+ })
+ .tool_rules(rules.clone())
+ .access(Access::readonly())
+ .build()
+ .await
+ .unwrap();
+ assert_eq!(runtime.defaults().model.temperature, Some(0.3));
+ assert_eq!(
+ runtime.capabilities().storage.driver.as_deref(),
+ Some("memory")
+ );
+ assert!(runtime.storage().is_some());
+ runtime
+ .define_template(
+ "shared",
+ AgentDefinitionSpec::new()
+ .bare_prompt("Shared reviewer.")
+ .tools(ToolScopeSpec::Named(Vec::new())),
+ )
+ .unwrap();
+ assert_eq!(runtime.defaults().templates.len(), 1);
+ assert!(
+ matches!(runtime.agent(AgentSpec::new("missing").extends("unknown")),Err(AgentError::UnknownTemplate(name)) if name=="unknown")
+ );
+ let first = runtime
+ .agent(
+ AgentSpec::new("first")
+ .model("gpt-4o-mini")
+ .extends("shared")
+ .model_defaults(ModelDefaults {
+ temperature: Some(0.6),
+ max_tokens: Some(120),
+ ..Default::default()
+ }),
+ )
+ .unwrap();
+ let second = runtime
+ .agent(AgentSpec::new("second").extends("shared"))
+ .unwrap();
+ assert_eq!(first.config().default_model.as_deref(), Some("gpt-4o-mini"));
+ assert_eq!(second.config().default_temperature, 0.3);
+ assert_eq!(first.config().autonomy.max_actions_per_hour, 7);
+ assert_eq!(first.config().tool_rules, rules);
+ assert!(runtime.capabilities().configuration.has_tool_rules);
+ assert_eq!(
+ first.config().privacy.mode,
+ openhuman_embed::config::PrivacyMode::Sensitive
+ );
+ assert!(!first.config().cron.enabled);
+ assert!(!first.config().secrets.encrypt);
+ assert_eq!(first.config().memory.recall.build_beliefs_every, 21);
+ assert_eq!(first.config().memory.recall.learnings_limit, 3);
+ first.turn("first question").send().await.unwrap();
+ second.turn("second question").send().await.unwrap();
+ first
+ .turn("override question")
+ .temperature(0.9)
+ .max_tokens(150)
+ .send()
+ .await
+ .unwrap();
+ let requests = chat_requests(&provider).await;
+ assert_eq!(requests.len(), 3);
+ let bodies: Vec<serde_json::Value> = requests
+ .iter()
+ .map(|r| serde_json::from_slice(&r.body).unwrap())
+ .collect();
+ assert_eq!(bodies[0]["temperature"], 0.6);
+ assert_eq!(bodies[0]["max_tokens"], 120);
+ assert_eq!(bodies[1]["temperature"], 0.3);
+ assert_eq!(bodies[1]["max_tokens"], 90);
+ assert_eq!(bodies[2]["temperature"], 0.9);
+ assert_eq!(bodies[2]["max_tokens"], 150);
+ for body in &bodies {
+ assert_eq!(body["top_p"], 0.8);
+ }
+ assert_eq!(runtime.defaults().model.temperature, Some(0.3));
+ assert!(matches!(
+ runtime.agent(
+ AgentSpec::new("wide")
+ .extends("shared")
+ .definition(AgentDefinitionSpec::new().tools(ToolScopeSpec::Wildcard))
+ ),
+ Err(AgentError::WidensRuntime(_))
+ ));
+}
diff --git a/crates/openhuman-embed/tests/runtime_observation.rs b/crates/openhuman-embed/tests/runtime_observation.rs
new file mode 100644
index 0000000000..7e50adcc3d
--- /dev/null
+++ b/crates/openhuman-embed/tests/runtime_observation.rs
@@ -0,0 +1,228 @@
+//! Isolation and lifecycle checks for custom inference and runtime observation.
+mod common;
+use async_trait::async_trait;
+use openhuman_embed::providers::{ChatModel, ModelRequest, ModelResponse};
+use openhuman_embed::seams::{PostTurnHook, TurnContext};
+use openhuman_embed::{
+ Access, AgentDefinitionSpec, AgentSpec, InMemorySessionStores, ModelDefaults, Provider,
+ Runtime, RuntimeEventKind, SessionStoreProvider, StreamEvent,
+};
+use std::sync::Arc;
+
+struct Model {
+ label: &'static str,
+ seen: tokio::sync::mpsc::UnboundedSender<ModelRequest>,
+}
+#[async_trait]
+impl ChatModel<()> for Model {
+ async fn invoke(
+ &self,
+ _: &(),
+ request: ModelRequest,
+ ) -> openhuman_embed::providers::Result<ModelResponse> {
+ self.seen.send(request).unwrap();
+ Ok(ModelResponse::assistant(self.label))
+ }
+}
+struct Hook {
+ name: &'static str,
+ seen: tokio::sync::mpsc::UnboundedSender<String>,
+}
+#[async_trait]
+impl PostTurnHook for Hook {
+ fn name(&self) -> &str {
+ self.name
+ }
+ async fn on_turn_complete(&self, ctx: &TurnContext) -> anyhow::Result<()> {
+ self.seen.send(ctx.agent_id.clone().unwrap_or_default())?;
+ Ok(())
+ }
+}
+
+#[test]
+fn custom_models_local_hooks_session_stores_and_events_stay_scoped() {
+ common::runtime().block_on(async {
+ tokio::spawn(async {
+ let backend = common::stub_backend().await;
+ let (model_tx, mut model_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (hook_tx, mut hook_rx) = tokio::sync::mpsc::unbounded_channel();
+ let (global_tx, mut global_rx) = tokio::sync::mpsc::unbounded_channel();
+ let runtime = Runtime::builder()
+ .config(common::offline_config())
+ .backend_url(backend.uri())
+ .access(Access::readonly())
+ .provider(
+ Provider::custom(Arc::new(Model {
+ label: "answer-a",
+ seen: model_tx.clone(),
+ }))
+ .model("custom-a"),
+ )
+ .model_defaults(ModelDefaults {
+ max_tokens: Some(40),
+ top_p: Some(0.8),
+ ..Default::default()
+ })
+ .post_turn_hook(Arc::new(Hook {
+ name: "global",
+ seen: global_tx,
+ }))
+ .build()
+ .await
+ .unwrap();
+ let mut events = runtime.events();
+ let store_a = Arc::new(InMemorySessionStores::new());
+ let store_b = Arc::new(InMemorySessionStores::new());
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(openhuman_embed::ToolScopeSpec::Named(Vec::new()))
+ };
+ let a = runtime
+ .agent(
+ AgentSpec::new("a")
+ .definition(definition())
+ .session_store(store_a.clone())
+ .post_turn_hook(Arc::new(Hook {
+ name: "local",
+ seen: hook_tx,
+ })),
+ )
+ .unwrap();
+ let b = runtime
+ .agent(
+ AgentSpec::new("b")
+ .definition(definition())
+ .session_store(store_b.clone())
+ .provider(
+ Provider::custom(Arc::new(Model {
+ label: "answer-b",
+ seen: model_tx,
+ }))
+ .model("custom-b"),
+ ),
+ )
+ .unwrap();
+ assert!(matches!(
+ events.recv().await.unwrap().kind,
+ RuntimeEventKind::AgentAdded
+ ));
+ assert!(matches!(
+ events.recv().await.unwrap().kind,
+ RuntimeEventKind::AgentAdded
+ ));
+ let first = a
+ .turn("private input a")
+ .session("thread-a")
+ .top_p(0.3)
+ .max_tokens(20)
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(first.reply, "answer-a");
+ let request = model_rx.recv().await.unwrap();
+ assert_eq!(request.max_tokens, Some(20));
+ assert_eq!(request.top_p, Some(0.3));
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(5), hook_rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ "a"
+ );
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(5), global_rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ "a"
+ );
+ let mut stream = b.turn("private input b").session("thread-b").stream();
+ let mut progress_before_final = false;
+ let outcome = loop {
+ match stream.recv().await.unwrap() {
+ StreamEvent::Progress(_) => progress_before_final = true,
+ StreamEvent::Finished(outcome) => break outcome.unwrap(),
+ }
+ };
+ assert!(progress_before_final);
+ assert_eq!(outcome.reply, "answer-b");
+ assert!(stream.recv().await.is_none());
+ let request = model_rx.recv().await.unwrap();
+ assert_eq!(request.max_tokens, Some(40));
+ assert_eq!(request.top_p, Some(0.8));
+ assert_eq!(
+ tokio::time::timeout(std::time::Duration::from_secs(5), global_rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ "b"
+ );
+ assert!(hook_rx.try_recv().is_err(), "A's hook never observes B");
+ runtime.post_turn_hook("global", None);
+ a.post_turn_hook("local", None);
+ assert_eq!(
+ a.turn("private input after removing hooks")
+ .session("thread-a")
+ .send()
+ .await
+ .unwrap()
+ .reply,
+ "answer-a"
+ );
+ let _ = model_rx.recv().await.unwrap();
+ assert!(
+ hook_rx.try_recv().is_err(),
+ "removed local hook stays removed on resume"
+ );
+ assert!(
+ global_rx.try_recv().is_err(),
+ "removed builder hook stays removed on resume"
+ );
+ let stored = store_a
+ .for_agent("a")
+ .transcripts
+ .root_for_thread("thread-a")
+ .unwrap()
+ .read_session()
+ .unwrap()
+ .unwrap();
+ assert!(stored
+ .messages
+ .iter()
+ .any(|message| message.content.contains("private input a")));
+ assert!(store_b
+ .for_agent("a")
+ .transcripts
+ .root_for_thread("thread-a")
+ .is_none());
+ assert!(store_a
+ .for_agent("b")
+ .transcripts
+ .root_for_thread("thread-b")
+ .is_none());
+ // The session stores are inspected through their public destination
+ // identity; transcript format/identity remains TinyAgents-owned.
+ assert!(store_b
+ .for_agent("b")
+ .transcripts
+ .root_for_thread("thread-b")
+ .is_some());
+ let mut ends = 0;
+ while ends < 3 {
+ let event = events.recv().await.unwrap();
+ let json = serde_json::to_string(&event).unwrap();
+ assert!(!json.contains("private input"));
+ if matches!(event.kind, RuntimeEventKind::TurnEnded { success: true }) {
+ ends += 1;
+ }
+ }
+ drop(stream);
+ drop(a);
+ drop(b);
+ drop(runtime);
+ })
+ .await
+ .expect("scenario runs on tuned worker");
+ });
+}
diff --git a/crates/openhuman-embed/tests/saas_profiles.rs b/crates/openhuman-embed/tests/saas_profiles.rs
index 40e0ccc919..f505375143 100644
--- a/crates/openhuman-embed/tests/saas_profiles.rs
+++ b/crates/openhuman-embed/tests/saas_profiles.rs
@@ -10,7 +10,10 @@ mod common;
use std::time::Duration;
-use common::{chat_requests, echo_inference, last_user_message, runtime, PointedTransport};
+use common::{
+ chat_requests, echo_inference, last_user_message, runtime_without_master_key as runtime,
+ PointedTransport,
+};
use openhuman_embed::profiles::ProfileCredentialKind;
use openhuman_embed::{
OpenError, ProfileError, ProfileRuntime, RelayMessage, Runtime, SaasConfig, Workspace,
diff --git a/crates/openhuman-embed/tests/stream_cancellation.rs b/crates/openhuman-embed/tests/stream_cancellation.rs
new file mode 100644
index 0000000000..f247144d6c
--- /dev/null
+++ b/crates/openhuman-embed/tests/stream_cancellation.rs
@@ -0,0 +1,211 @@
+//! 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);
+ 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);
+ drop(flood);
+ drop(agent);
+ drop(runtime);
+ })
+ .await
+ .expect("scenario runs on tuned worker");
+ });
+}
diff --git a/crates/openhuman-rpc/src/host.rs b/crates/openhuman-rpc/src/host.rs
index d0bd0fd8e3..edec84d5e6 100644
--- a/crates/openhuman-rpc/src/host.rs
+++ b/crates/openhuman-rpc/src/host.rs
@@ -54,6 +54,20 @@ pub fn cli_builder() -> RuntimeBuilder {
.controller_extension(crate::http_host::extension())
}
+/// Parse the side-effect-free embedding capability command.
+#[cfg(any(feature = "server", test))]
+fn embed_info(args: &[String]) -> anyhow::Result<Option<crate::embed::RuntimeInfo>> {
+ if args.first().map(String::as_str) != Some("embed") {
+ return Ok(None);
+ }
+ if !matches!(args.get(1).map(String::as_str), Some("info"))
+ || args.iter().skip(2).any(|arg| arg != "--json")
+ {
+ anyhow::bail!("usage: openhuman-core embed info [--json]");
+ }
+ Ok(Some(crate::embed::RuntimeBuilder::standard().describe()))
+}
+
/// Run the core's command-line dispatcher on `args` (without the binary
/// name) as the `openhuman-core` binary does: connected to the TinyHumans
/// backend, with this crate's server behind `run` / `serve`.
@@ -64,6 +78,12 @@ pub fn cli_builder() -> RuntimeBuilder {
/// the dispatched command failed.
#[cfg(feature = "server")]
pub fn cli(args: &[String]) -> anyhow::Result<()> {
+ // Introspection belongs above the core: never introduce a core -> embed dependency.
+ if let Some(info) = embed_info(args)? {
+ println!("{}", serde_json::to_string_pretty(&info)?);
+ return Ok(());
+ }
+
log::debug!(
"[rpc:host] cli command={} argc={}",
args.first().map(String::as_str).unwrap_or("<none>"),
diff --git a/crates/openhuman-rpc/src/host_tests.rs b/crates/openhuman-rpc/src/host_tests.rs
index c5f21e2802..f1ae9a021c 100644
--- a/crates/openhuman-rpc/src/host_tests.rs
+++ b/crates/openhuman-rpc/src/host_tests.rs
@@ -162,3 +162,14 @@ fn cli_storage_is_opened_for_one_shot_commands_only() {
assert!(uses(&["cron", "add", "--name", "help"]));
assert!(uses(&["--model", "help", "cron", "list"]));
}
+
+#[test]
+fn embed_info_is_versioned_and_rejects_unknown_flags() {
+ let info = embed_info(&["embed".into(), "info".into(), "--json".into()])
+ .unwrap()
+ .unwrap();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.compiled_features.contains_key("voice"));
+ assert!(embed_info(&["embed".into(), "info".into(), "--secret".into()]).is_err());
+ assert!(embed_info(&["serve".into()]).unwrap().is_none());
+}
diff --git a/crates/openhuman-rpc/src/lib.rs b/crates/openhuman-rpc/src/lib.rs
index 10864ea2d9..79cd37a9f0 100644
--- a/crates/openhuman-rpc/src/lib.rs
+++ b/crates/openhuman-rpc/src/lib.rs
@@ -55,7 +55,8 @@ pub mod embed {
pub use openhuman_tinyhumans::embed::modules;
pub use openhuman_tinyhumans::embed::{
artifacts, chat_surface, config, process, schema_for_rpc_method, CoreRuntime,
- PickListenPortError, ServiceSet, HTTP_SERVER_COMPILED_IN, VOICE_COMPILED_IN,
+ PickListenPortError, RuntimeBuilder, RuntimeInfo, ServiceSet, HTTP_SERVER_COMPILED_IN,
+ VOICE_COMPILED_IN,
};
}
diff --git a/crates/openhuman-tinyhumans/src/lib.rs b/crates/openhuman-tinyhumans/src/lib.rs
index d92464f959..4d0b8ecec3 100644
--- a/crates/openhuman-tinyhumans/src/lib.rs
+++ b/crates/openhuman-tinyhumans/src/lib.rs
@@ -51,9 +51,11 @@
pub mod embed {
// Runtime, builder and the knobs the hosts configure it with.
pub use openhuman_embed::{
- Access, Agent, AgentSpec, ApiKey, ConfigSource, CoreError, CoreRuntime, DomainSet, Harness,
- HarnessBuilder, HostKind, Provider, Runtime, RuntimeBuilder, RuntimeError, ServiceSet,
- TokenSource, Workspace,
+ Access, Agent, AgentDefaults, AgentDefinitionSpec, AgentSpec, ApiKey, ConfigSource,
+ ConfigurationInfo, CoreError, CoreRuntime, DefaultsInfo, DefinitionBase, DomainSet,
+ Harness, HarnessBuilder, HostKind, LearningSettings, ModelDefaults, Provider, Runtime,
+ RuntimeBuilder, RuntimeDefaults, RuntimeError, RuntimeInfo, RuntimeModule, ServiceSet,
+ SkillsPolicy, StorageInfo, TokenSource, WeightClass, Workspace,
};
// Process-level facts a host reads.
pub use openhuman_embed::{
diff --git a/docs/RELEASE-MANUAL-SMOKE.md b/docs/RELEASE-MANUAL-SMOKE.md
index d5a4e58c70..1b8239a346 100644
--- a/docs/RELEASE-MANUAL-SMOKE.md
+++ b/docs/RELEASE-MANUAL-SMOKE.md
@@ -97,6 +97,9 @@ Applies to every release, all platforms.
### Cross-platform
+- [ ] **Embed capability report and storage configuration** — Run `openhuman-core embed info --json` from a headless install. Expected: versioned JSON lists compiled features and effective defaults without credentials, prompts, endpoint URLs or workspace paths. Run the Embed `storage` recipe with `storage-sqlite`: it writes, reads and deletes an item in its configured SQLite backend. For a release that includes `storage-mongodb`, repeat against an operator-provided test database using the recipe's explicit live settings; confirm the configured backend is reported as MongoDB without exposing its URL.
+- [ ] **Embed agents remain independent during streaming** — Run the offline `runtime_events`, `custom_provider` and `approvals` recipes. Expected: per-agent model routes and hooks stay isolated, events identify the acting agent without user content, and dropping an approval subscription cancels its pending callback. Run the stream cancellation integration test: dropping or externally cancelling a stream releases its model even while the receiver remains unread.
+
- [ ] **Chat model picker selects the provider as well as the model (#6938)** — In an isolated test profile, switch the same thread from managed to Ollama, then to a configured BYOK provider, and back to a managed catalog model (including a `:free` variant). Verify the actual request endpoint and model match each selection, configured background routes stay unchanged, and reopening the app restores the selected provider/model. Selecting a workload hint must retain its configured route.
- [ ] **Agent files land in a visible folder** — Ask the agent for a short document or deck. Expected: the file appears in `~/OpenHuman/projects/Files` under its title (not in `~/.openhuman`); **Show in folder** in the chat Files panel opens the file manager at it; Settings → Agent OS access → **Files folder** shows that path, **Show in folder** opens it, and choosing another folder sends the next file there while the earlier file still opens. On an upgraded install, files from before the upgrade have moved into the folder.
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 167ad79e01..533e577d48 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -661,6 +661,19 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 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.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 |
@@ -672,5 +685,5 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| **Total leaves** | **153 explicit + nested = 213 product features** |
PR-A delta: 13 leaves moved from ❌ → ✅ via 5 WDIO specs + 2 Vitest + 1 Rust integration test.
-Section 16 adds 11 leaves (10 ✅, 1 🟡) for the embedded library harness.
+Section 16.1 adds 11 leaves (10 ✅, 1 🟡) for the embedded library harness. Section 16.2 adds eight covered leaves for dynamic runtime configuration, lifecycle and generated documentation.
Remaining gaps tracked under sub-issues #965 (process), #966 (docs), #967 (tools), #968 (auth/perm), #969 (settings), #970 (rewards), #971 (manual smoke).
diff --git a/docs/gitbooks/en/SUMMARY.md b/docs/gitbooks/en/SUMMARY.md
index 9057603478..ea87ad6cfd 100644
--- a/docs/gitbooks/en/SUMMARY.md
+++ b/docs/gitbooks/en/SUMMARY.md
@@ -75,6 +75,7 @@
- [Architecture](developing/architecture/README.md)
- [Deep Architecture Reference](developing/architecture.md)
- [Agent Harness](developing/architecture/agent-harness.md)
+ - [Storage](developing/architecture/storage.md)
- [Flows on TinyAgents](developing/architecture/flows-on-tinyagents.md)
- [Memory](developing/architecture/memory.md)
- [MCP Registry](developing/architecture/mcp-registry.md)
@@ -86,7 +87,52 @@
- [Performance and footprint](developing/performance.md)
- [Pluggable engines](developing/engines.md)
- [Jev](developing/jev.md)
-- [Embedding OpenHuman](developing/embedding.md)
+- [Embedding](developing/embed/README.md)
+ - [Installation](developing/embed/installation.md)
+ - [Quickstart](developing/embed/quickstart.md)
+ - [Embedding architecture](developing/embed/architecture.md)
+ - [Concepts](developing/embed/concepts/README.md)
+ - [Runtime](developing/embed/concepts/runtime.md)
+ - [Runtime defaults](developing/embed/concepts/runtime-defaults.md)
+ - [Agents](developing/embed/concepts/agents.md)
+ - [Access and approvals](developing/embed/concepts/access-approvals.md)
+ - [Providers](developing/embed/concepts/providers.md)
+ - [Turns and sessions](developing/embed/concepts/turns-sessions.md)
+ - [Tools](developing/embed/concepts/tools.md)
+ - [MCP](developing/embed/concepts/mcp.md)
+ - [Skills](developing/embed/concepts/skills.md)
+ - [Memory](developing/embed/concepts/memory.md)
+ - [Cron](developing/embed/concepts/cron.md)
+ - [Channels](developing/embed/concepts/channels.md)
+ - [Profiles and SaaS](developing/embed/concepts/profiles-saas.md)
+ - [Completer](developing/embed/concepts/completer.md)
+ - [Hooks and seams](developing/embed/concepts/hooks-seams.md)
+ - [Observability](developing/embed/concepts/observability.md)
+ - [Testing](developing/embed/concepts/testing.md)
+ - [Errors](developing/embed/concepts/errors.md)
+ - [Embedding guides](developing/embed/guides/README.md)
+ - [CLI chatbot](developing/embed/guides/cli-chatbot.md)
+ - [Multiple agents](developing/embed/guides/multi-agent.md)
+ - [SaaS with multiple tenants](developing/embed/guides/saas-multi-tenant.md)
+ - [Deploy a server](developing/embed/guides/deploy-server.md)
+ - [Lean and headless hosts](developing/embed/guides/lean-headless.md)
+ - [Test with a mock backend](developing/embed/guides/mock-backend-testing.md)
+ - [Embedding integrations](developing/embed/integrations/README.md)
+ - [OpenAI-compatible providers and BYOK](developing/embed/integrations/openai-compatible.md)
+ - [TinyHumans managed inference](developing/embed/integrations/tinyhumans-managed.md)
+ - [Local and custom models](developing/embed/integrations/local-models.md)
+ - [MCP servers](developing/embed/integrations/mcp.md)
+ - [Composio](developing/embed/integrations/composio.md)
+ - [Storage drivers](developing/embed/integrations/storage-drivers.md)
+ - [Channels](developing/embed/integrations/channels.md)
+ - [Cookbook](developing/embed/cookbook.md)
+ - [Embedding API reference](developing/embed/api-reference.md)
+ - [API index](developing/embed/api-index.md)
+ - [RuntimeBuilder setters](developing/embed/builder-setters.md)
+ - [Compiled feature matrix](developing/embed/capability-matrix.md)
+ - [Embedding FAQ](developing/embed/faq.md)
+ - [Embedding troubleshooting](developing/embed/troubleshooting.md)
+- [SaaS profiles](developing/saas-profiles.md)
- [One TinyHumans API key](developing/tinyhumans-api-key.md)
- [Hooks](developing/hooks.md)
- [MCP Server](developing/mcp-server.md)
diff --git a/docs/gitbooks/en/developing/architecture/storage.md b/docs/gitbooks/en/developing/architecture/storage.md
new file mode 100644
index 0000000000..0c427ef41d
--- /dev/null
+++ b/docs/gitbooks/en/developing/architecture/storage.md
@@ -0,0 +1,118 @@
+---
+description: >-
+ The storage domain in crates/openhuman-core/src/storage/: the ports, URL
+ resolution, Cargo features, per-agent scopes, drivers and on-disk layout.
+icon: database
+---
+
+# Storage
+
+OpenHuman keeps durable state on the ports of [`tinystoragedrivers`](https://github.com/tinyhumansai/tinystoragedrivers), vendored through `vendor/tinyagents/vendor/tinystoragedrivers`. One URL picks the backend for the whole process. The host adapter is `crates/openhuman-core/src/storage/`. It resolves the URL, opens the backend, holds it in a process slot and decides which scope a call runs in. The ports, the drivers and their conformance suites belong to `tinystoragedrivers`, and the typed records stay with the domain that owns them.
+
+With no URL configured, which is the desktop default, nothing here is opened and every domain keeps its classic on-disk layout under the workspace. Setting a URL switches the domains that have moved onto the ports. The rest still use their files.
+
+## The ports
+
+A backend is a `StorageBackend`. It hands out a `ScopedStorage` for each `Scope`, and every handle on it is already bound to that scope, so no method takes a scope argument.
+
+| Port | Holds | Used for |
+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
+| `DocumentStore` | Versioned JSON documents in named collections, with filters, paging, unique indexes, compare-and-swap (`Precondition`), atomic `claim` and optional expiry | Approvals, devices, notifications, task sources, cron jobs and runs, the flow catalog, graph checkpoints, encrypted secrets |
+| `StreamStore` | Append-only logs with dense offsets | Transcripts, journals |
+| `BlobStore` | Opaque bytes by key | Attachments, artifacts |
+| `SearchIndex` | Full-text membership | Where the driver supports it |
+| `SecretStore` | Encrypted values (`enc2:` envelope) | Keyring user secrets and the credential stores |
+
+The core's stores are mostly synchronous, so `storage::block_on` runs a storage future on one shared runtime thread. It never uses `block_in_place`, which panics on a current-thread runtime. `storage::documents::Repo` is the base the domain stores build on. It declares a domain's collections once per process and runs each call.
+
+## Choosing a backend
+
+The storage URL is the first of these that is set. Blank values count as unset.
+
+1. `OPENHUMAN_STORAGE_URL`
+2. `[storage] url` in `config.toml`
+3. Nothing: the classic layout
+
+`[storage]` is bootstrap configuration. It is always read from the environment or the file and never from storage itself.
+
+| URL | Driver | Cargo feature |
+| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
+| `memory` | In-process maps, keeps nothing | Always |
+| `sqlite:<path>` (a `.db` file, or a directory that holds `storage.db`) | SQLite | `storage-sqlite` |
+| `file:<dir>` | `<dir>/scopes/<scope>/docs/<collection>/<id>.json` for documents, with collection metadata in `<dir>/_meta/collections/<collection>.json`. Streams are JSONL and blobs are raw files under the same scope directory. | `storage-file` |
+| `mongodb://…/<db>`, `mongodb+srv://…/<db>` | MongoDB, one database shared by every scope | `storage-mongodb` |
+
+A URL for a driver the build lacks fails at `storage::open`, and the error names the Cargo feature. A misconfigured deployment therefore stops at boot rather than at its first write. Credentials in a URL are redacted in logs and in `Debug` output.
+
+Each feature is forwarded through the whole library chain (`openhuman-core`, `openhuman-embed`, `openhuman-tinyhumans`, `openhuman-rpc`, then the `openhuman-cli` and `openhuman-tui` hosts). `scripts/ci/check-feature-forwarding.mjs` checks the links. A desktop build never links a MongoDB client, and a cloud build does not need SQLite.
+
+The host opens the configured backend before the core boots and installs it with `storage::install`. It then installs TinyAgents' `DriverSessionStores` over the same backend, so transcripts, turn states, the run ledger and journals live in it too. Library hosts use `RuntimeBuilder::storage(..)`, which installs only the backend: conversations move onto it with `RuntimeBuilder::session_store(..)`, configured separately.
+
+## Scopes
+
+Every record lives in a scope, and two scopes on one backend never see each other's data. A single-user install scopes by **agent id**, and a SaaS host scopes by **profile** (the tenant). `storage::scope_for_agent` and `storage::scope_for_profile` are the single mappings, and the session store uses the same ones, so every domain agrees. An agent's scope is its id when that is a valid scope name, else `sha256:<hex digest of the id>` (TinyAgents' `DriverSessionStores::scope_for`). A profile's scope is `profile:<id>`, or `profile-sha256:<hex digest of the id>` when that is not a valid scope name. The prefixes keep the two kinds of key from colliding, and `local` is the literal operator scope.
+
+`storage::current_scope()` resolves the scope of the current call from the task's tenant (`storage::scope_from(profile, agent, saas)`), in this order:
+
+1. A **profile**, when the work runs for one: the scope is the profile's, whatever agent acts inside it. In SaaS mode the agents of one profile therefore share that profile's scope.
+2. Otherwise the acting **agent** (`CoreContext::session_agent`): the scope is that agent's.
+3. Otherwise `local`: the operator, the CLI and the desktop shell in single-user mode.
+
+In SaaS mode a call with no profile is refused instead of falling into a bucket other users could share, whether or not an agent acts. If the task's tenant cannot be resolved at all (`current_tenant()` fails), `current_scope()` returns that error in every mode instead of falling back to `local`.
+
+A backend decides how it enforces the scope. SQLite and the file driver keep each scope's data apart, and `local` is the scope a single-user install uses. MongoDB injects a scope key into every filter and every index prefix.
+
+### Background work
+
+Background work runs under the process default context, which names no agent, and on its own would only see `local`. `storage::agents` closes the gap. Agents are known when they are live (`AgentContextRegistry`) or when an earlier process recorded their id in the `local` scope (`storage_agents`). `for_each_scope` runs a step once for `local` and once under each known agent. The cron scheduler's agent pass (`cron::scheduler::tick_live_agents`, driven in tests through the public `cron::scheduler::run_live_agent_pass`) runs each live agent's due jobs under that agent's own context, so their results are recorded in the agent's own scope. A recorded agent that is not live waits until it is live again, because its jobs need its host tools and prompt.
+
+On a shared backend (MongoDB) other processes may write the same records, so boot-time recovery such as the orphaned-run sweep is skipped (`storage::installed_is_shared`).
+
+## Drivers and on-disk layout
+
+| Driver | Where the data lives |
+| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `memory` | Nowhere. Records last as long as the backend value. |
+| `sqlite:<dir>` | `<dir>/storage.db` in WAL mode (with its `-wal` and `-shm` files). The scope is a column on every row. The large relational stores keep their tables through the driver's native mode. |
+| `sqlite:<file>.db` | That file, laid out the same way. |
+| `file:<dir>` | `<dir>/scopes/<scope>/docs/<collection>/<id>.json` for documents, with collection metadata in `<dir>/_meta/collections/<collection>.json`. Streams are JSONL and blobs are raw files under the same scope directory. |
+| `mongodb://…/<db>` | One database. Each named database is a collection prefix, and every record carries its scope. |
+
+Without a URL, the classic layout is unchanged: per-domain SQLite databases (`approval/approval.db`, `devices/devices.db`, `notifications/notifications.db`, `task_sources/sources.db`, `cron/jobs.db`, `flows/flows.db`, `graph_checkpoints.db`), JSON and JSONL files, and the OS keyring or `secrets.enc`. Records written to a configured backend are not copied back to those files. The domain stores do not import their files either, with one exception: credentials. On first read with a backend installed, the auth-profile and HTTP-credential stores copy the records in their files into the backend, and the keyring adopts a secret it finds in the process backend. The source files are left untouched.
+
+Secrets with a backend installed are encrypted documents in the current storage scope: the acting agent's scope on a desktop or CLI host, and the profile's scope under SaaS, where every agent in one profile shares the profile's credentials and data key. Each scope's data key is derived with HKDF-SHA256 from the keyring master key (`OPENHUMAN_KEYRING_MASTER_KEY` or `_FILE`, else the OS keychain), and with no master key they fail closed. The config encryption key stays on the process keyring because `config.toml` is loaded before any agent acts.
+
+## Tests and CI
+
+Every storage test target runs the same body once per driver, and each run is a separate test case named after the driver (`memory::…`, `sqlite::…`, `file::…`, `mongodb::…`), so a failure says which driver broke. The shared helper is `tests/support/storage_drivers.rs`.
+
+| Driver | Runs |
+| ---------------- | ------------------------------------------------------------------------------------------------------- |
+| `memory` | Always |
+| `sqlite`, `file` | When `storage-sqlite` or `storage-file` is compiled in, on temp directories |
+| `mongodb` | When `storage-mongodb` is compiled in and `TSD_MONGO_URL` is set. Each case uses a database of its own. |
+
+The targets are `storage_approvals_e2e`, `storage_domains_e2e`, `storage_flows_e2e`, `storage_secrets_e2e`, `storage_scope_e2e`, `storage_agent_scopes_e2e`, `storage_delegation_e2e` and `cli_storage_url_e2e`. Run one locally with the drivers you want:
+
+```bash
+cargo test -p openhuman-cli --features storage-sqlite,storage-file --test storage_approvals_e2e
+```
+
+For MongoDB, start a single-node replica set and set the URL (a replica set is what lets the driver report and exercise transactions):
+
+```bash
+bash vendor/tinyagents/vendor/tinystoragedrivers/.github/scripts/start-mongo-replset.sh 27017
+export TSD_MONGO_URL='mongodb://127.0.0.1:27017/tsd_test?directConnection=true'
+cargo test -p openhuman-cli --features storage-mongodb --test storage_approvals_e2e
+```
+
+CI has two lanes for this:
+
+- The `storage-drivers` lane in `scripts/ci/self-hosted/lanes-plan.mjs` builds with `storage-sqlite,storage-file`. It runs every storage target plus the lib tests of the domains on the ports. The `storage` area in `.github/ci-paths-filter.yml` arms it when storage, cron, flows, approvals, devices, notifications, task sources, keyring or credentials, orchestration, the cost tracker, app and desktop-control state or the rpc session store change.
+- `.github/workflows/storage-mongodb.yml` builds with `storage-mongodb` against a real replica set. It runs on pull requests that touch the same paths, nightly on `main` and on demand.
+
+## Where to read next
+
+- `crates/openhuman-core/src/storage/README.md` for the entry points and the consumers.
+- The `tinystoragedrivers` specs: `docs/specs/storage-ports.md` and `docs/plans/storage-rollout.md` in `vendor/tinyagents/vendor/tinystoragedrivers`.
+- [Security](security.md) for the keyring and credential stores.
diff --git a/docs/gitbooks/en/developing/embed/README.md b/docs/gitbooks/en/developing/embed/README.md
new file mode 100644
index 0000000000..29e568533e
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/README.md
@@ -0,0 +1,34 @@
+---
+description: "Run the OpenHuman core inside a Rust application with one Runtime and independently configured Agents."
+---
+
+# Embedding OpenHuman
+
+`openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+
+Build one `Runtime` per process and register the agents your product needs. Each agent can choose its own provider, prompt, working folder, tool scope, skills and MCP servers. Agents share runtime credentials; use `ProfileRuntime` when separate customers need separate credentials and workspaces.
+
+## Start here
+
+- [Installation](installation.md): dependency, Cargo gates, runtime setup and configuration.
+- [Quickstart](quickstart.md): run a verified offline turn, then choose a live provider explicitly.
+- [Architecture](architecture.md): ownership, lifecycle and the library chain.
+- [Concepts](concepts/README.md): the 18 public API concepts and their runtime/agent scope.
+- [Guides](guides/README.md): chatbots, multiple agents, SaaS, server deployment and tests.
+- [Integrations](integrations/README.md): inference, MCP, connectors, storage and channels.
+- [Cookbook](cookbook.md): generated inventory of executable examples.
+- [API reference](api-reference.md): local rustdoc, source links and generated builder knobs.
+
+## Choose the right surface
+
+| Requirement | Start with |
+| --- | --- |
+| One agent with a small host | `Harness` |
+| Several independently configured agents | `Runtime` and `AgentSpec` |
+| Stateless model generation | `Completer` |
+| Authenticated users with isolated credentials and state | `ProfileRuntime` |
+| Public JSON-RPC server or shipped desktop host | The `openhuman-rpc` host layer |
+
+The snippets in this section are injected from compiled, offline-tested Rust examples. Their full source files include the surrounding setup. `pnpm docs:check` checks source drift, local links, the generated API inventory and the published English mirror.
+
+See [FAQ](faq.md) for design choices and [troubleshooting](troubleshooting.md) for setup failures.
diff --git a/docs/gitbooks/en/developing/embed/api-index.json b/docs/gitbooks/en/developing/embed/api-index.json
new file mode 100644
index 0000000000..76919ff831
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/api-index.json
@@ -0,0 +1,565 @@
+{
+ "schema_version": 1,
+ "exports": [
+ "Access",
+ "Agent",
+ "AgentDefaults",
+ "AgentDefinition",
+ "AgentDefinitionSpec",
+ "AgentError",
+ "AgentLayout",
+ "AgentProgress",
+ "AgentSpec",
+ "AgentTurnOrigin",
+ "ApiKey",
+ "ApprovalDecision",
+ "ApprovalHandler",
+ "ApprovalSubscription",
+ "Approvals",
+ "ApprovalsError",
+ "Auth",
+ "AuthState",
+ "BackendRequest",
+ "BackendTransport",
+ "BackendTransportError",
+ "BaseUrlPurpose",
+ "CancellationToken",
+ "ChannelError",
+ "ChannelListener",
+ "Channels",
+ "ChatMessage",
+ "ChatReply",
+ "Completer",
+ "CompletionObserver",
+ "CompletionRequest",
+ "CompletionResponse",
+ "CompletionTrace",
+ "CompletionUsage",
+ "ComposioHostCredential",
+ "Config",
+ "ConfigSource",
+ "ConfigurationInfo",
+ "ControllerSchema",
+ "CoreAgent",
+ "CoreBuilder",
+ "CoreError",
+ "CoreRuntime",
+ "Cron",
+ "CronError",
+ "DEFAULT_MAX_AGENTS",
+ "DaemonConfig",
+ "DefaultsInfo",
+ "DefinitionBase",
+ "DomainSet",
+ "EventStreamError",
+ "GroupMode",
+ "HTTP_SERVER_COMPILED_IN",
+ "Harness",
+ "HarnessBuilder",
+ "HarnessCore",
+ "HarnessError",
+ "HostKind",
+ "HostTools",
+ "HostTurnTools",
+ "HttpHeader",
+ "InMemorySessionStores",
+ "JobRun",
+ "JobRunRecord",
+ "JobSchedule",
+ "JobSpec",
+ "JobTarget",
+ "LastTurnUsage",
+ "LearningSettings",
+ "McpAuthConfig",
+ "McpServer",
+ "MemoryBinding",
+ "ModelDefaults",
+ "OpenError",
+ "PendingApproval",
+ "PermissionLevel",
+ "PickListenPortError",
+ "ProfileError",
+ "ProfileEvents",
+ "ProfileHandle",
+ "ProfileId",
+ "ProfileIdMode",
+ "ProfileRuntime",
+ "ProfileRuntimeBuilder",
+ "ProfileSummary",
+ "Provider",
+ "Provisioned",
+ "RelayAccepted",
+ "RelayMessage",
+ "RemoveAgent",
+ "Route",
+ "Runtime",
+ "RuntimeBuilder",
+ "RuntimeConfig",
+ "RuntimeDefaults",
+ "RuntimeError",
+ "RuntimeEvent",
+ "RuntimeEventKind",
+ "RuntimeEvents",
+ "RuntimeFlags",
+ "RuntimeInfo",
+ "RuntimeModule",
+ "SaasConfig",
+ "SandboxModeSpec",
+ "ScheduledJob",
+ "ServiceSet",
+ "Session",
+ "SessionStoreProvider",
+ "SkillsPolicy",
+ "StorageInfo",
+ "StreamEvent",
+ "StreamMode",
+ "SystemJobContext",
+ "TelegramChannelSpec",
+ "TokenSource",
+ "Tool",
+ "ToolAttachmentError",
+ "ToolExposure",
+ "ToolGroups",
+ "ToolResult",
+ "ToolScopeSpec",
+ "TransportProfile",
+ "TrustedAccess",
+ "TrustedAutomationSource",
+ "Turn",
+ "TurnContext",
+ "TurnOutcome",
+ "TurnRequest",
+ "TurnStream",
+ "VOICE_COMPILED_IN",
+ "WeightClass",
+ "Workspace",
+ "absolute",
+ "agent_progress",
+ "artifacts",
+ "channels",
+ "chat_surface",
+ "complete",
+ "config",
+ "cron",
+ "embeddings",
+ "events",
+ "identity",
+ "install_backend_transport",
+ "installed_backend_transport",
+ "memory",
+ "modules",
+ "process",
+ "profiles",
+ "providers",
+ "run_from_args",
+ "schema_for_rpc_method",
+ "seams",
+ "session_store",
+ "skill_registry",
+ "stream"
+ ],
+ "builder_setters": [
+ {
+ "name": "access",
+ "signature": "pub fn access(mut self, access: Access) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 343
+ },
+ {
+ "name": "action_dir",
+ "signature": "pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 300
+ },
+ {
+ "name": "agent_defaults",
+ "signature": "pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 151
+ },
+ {
+ "name": "api_key",
+ "signature": "pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 320
+ },
+ {
+ "name": "autonomy",
+ "signature": "pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 186
+ },
+ {
+ "name": "backend_transport",
+ "signature": "pub fn backend_transport(mut self, transport: Arc<dyn BackendTransport>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 225
+ },
+ {
+ "name": "backend_url",
+ "signature": "pub fn backend_url(mut self, url: impl Into<String>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 330
+ },
+ {
+ "name": "config",
+ "signature": "pub fn config(mut self, config: Config) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 444
+ },
+ {
+ "name": "config_source",
+ "signature": "pub fn config_source(mut self, source: ConfigSource) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 308
+ },
+ {
+ "name": "controller_extension",
+ "signature": "pub fn controller_extension(mut self, extension: ControllerExtension) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 415
+ },
+ {
+ "name": "cron",
+ "signature": "pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 211
+ },
+ {
+ "name": "definition_base",
+ "signature": "pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 170
+ },
+ {
+ "name": "domains",
+ "signature": "pub fn domains(mut self, domains: DomainSet) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 374
+ },
+ {
+ "name": "host_kind",
+ "signature": "pub fn host_kind(mut self, host_kind: HostKind) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 391
+ },
+ {
+ "name": "learning",
+ "signature": "pub fn learning(mut self, value: super::LearningSettings) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 206
+ },
+ {
+ "name": "listen",
+ "signature": "pub fn listen(self, host: impl Into<String>, port: u16) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 413
+ },
+ {
+ "name": "listen_host",
+ "signature": "pub fn listen_host(mut self, host: impl Into<String>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 418
+ },
+ {
+ "name": "listen_port",
+ "signature": "pub fn listen_port(mut self, port: u16) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 424
+ },
+ {
+ "name": "live_policy",
+ "signature": "pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 464
+ },
+ {
+ "name": "max_agents",
+ "signature": "pub fn max_agents(mut self, limit: usize) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 263
+ },
+ {
+ "name": "mcp_baseline",
+ "signature": "pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 181
+ },
+ {
+ "name": "memory_engine",
+ "signature": "pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 239
+ },
+ {
+ "name": "model_defaults",
+ "signature": "pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 160
+ },
+ {
+ "name": "modules",
+ "signature": "pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/selection.rs",
+ "line": 156
+ },
+ {
+ "name": "post_turn_hook",
+ "signature": "pub fn post_turn_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 430
+ },
+ {
+ "name": "privacy",
+ "signature": "pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 196
+ },
+ {
+ "name": "provider",
+ "signature": "pub fn provider(mut self, provider: Provider) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 336
+ },
+ {
+ "name": "sandbox",
+ "signature": "pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 165
+ },
+ {
+ "name": "secrets",
+ "signature": "pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 201
+ },
+ {
+ "name": "server_launcher",
+ "signature": "pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 444
+ },
+ {
+ "name": "services",
+ "signature": "pub fn services(mut self, services: ServiceSet) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 362
+ },
+ {
+ "name": "session",
+ "signature": "pub fn session(mut self, session: Session) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 434
+ },
+ {
+ "name": "session_store",
+ "signature": "pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 254
+ },
+ {
+ "name": "skills",
+ "signature": "pub fn skills(mut self, policy: super::SkillsPolicy) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 175
+ },
+ {
+ "name": "storage",
+ "signature": "pub fn storage(mut self, source: impl Into<StorageSource>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 457
+ },
+ {
+ "name": "token",
+ "signature": "pub fn token(mut self, token: TokenSource) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 401
+ },
+ {
+ "name": "tool_groups",
+ "signature": "pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 383
+ },
+ {
+ "name": "tool_hook",
+ "signature": "pub fn tool_hook(mut self, hook: Arc<dyn ToolHook>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 437
+ },
+ {
+ "name": "tool_ranker",
+ "signature": "pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 422
+ },
+ {
+ "name": "tool_rules",
+ "signature": "pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 191
+ },
+ {
+ "name": "workspace",
+ "signature": "pub fn workspace(mut self, workspace: Workspace) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 273
+ },
+ {
+ "name": "workspace_dir",
+ "signature": "pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 287
+ }
+ ],
+ "capabilities": {
+ "schema_version": 1,
+ "configuration_resolved": true,
+ "compiled_features": {
+ "channels": true,
+ "crash-reporting": false,
+ "default": true,
+ "documents": false,
+ "e2e-test-support": false,
+ "file-logging": true,
+ "flows": true,
+ "hosting": false,
+ "http-server": true,
+ "inference": false,
+ "mcp": true,
+ "media": true,
+ "modules": true,
+ "rss-bench": false,
+ "runtime-node": false,
+ "scheduler-gate": true,
+ "skills": true,
+ "storage-file": false,
+ "storage-mongodb": false,
+ "storage-sqlite": false,
+ "tinymemes": true,
+ "voice": false,
+ "web3": false,
+ "whatsapp-web": false
+ },
+ "domains": [
+ "agent",
+ "memory",
+ "threads",
+ "config",
+ "security",
+ "flows",
+ "skills",
+ "channels",
+ "inference",
+ "integrations",
+ "automation",
+ "runtimes",
+ "platform"
+ ],
+ "services": [
+ "harness_init"
+ ],
+ "tool_groups": {
+ "audio": "withheld",
+ "coding": "withheld",
+ "composio": "withheld",
+ "docs": "withheld",
+ "documents": "withheld",
+ "goals": "withheld",
+ "mcp": "withheld",
+ "media": "withheld",
+ "scheduling": "withheld",
+ "skills": "withheld",
+ "storage": "withheld",
+ "system": "withheld",
+ "tasks": "withheld",
+ "web3": "withheld",
+ "workflows": "withheld"
+ },
+ "host_kind": "Library",
+ "max_agents": 1024,
+ "defaults": {
+ "model": {
+ "temperature": 0.7,
+ "max_tokens": null,
+ "top_p": null,
+ "max_iterations": 200
+ },
+ "provider_model": "openrouter/deepseek/deepseek-v4-flash",
+ "routed_provider": false,
+ "sandbox": "None",
+ "approval_gate": true,
+ "include_user_skills": false,
+ "has_skills_root": false,
+ "mcp_servers": 0,
+ "templates": []
+ },
+ "configuration": {
+ "autonomy_enabled": true,
+ "privacy": "Standard",
+ "secrets_encrypted": true,
+ "cron_enabled": true,
+ "learning": {
+ "build_beliefs_every": 10,
+ "learnings_limit": 8
+ },
+ "has_tool_rules": false
+ },
+ "storage": {
+ "source": "workspace",
+ "driver": null,
+ "configured": false
+ },
+ "modules": [],
+ "weight": "custom"
+ },
+ "pages": [
+ "gitbooks/developing/embed/README.md",
+ "gitbooks/developing/embed/api-reference.md",
+ "gitbooks/developing/embed/architecture.md",
+ "gitbooks/developing/embed/concepts/README.md",
+ "gitbooks/developing/embed/concepts/access-approvals.md",
+ "gitbooks/developing/embed/concepts/agents.md",
+ "gitbooks/developing/embed/concepts/channels.md",
+ "gitbooks/developing/embed/concepts/completer.md",
+ "gitbooks/developing/embed/concepts/cron.md",
+ "gitbooks/developing/embed/concepts/errors.md",
+ "gitbooks/developing/embed/concepts/hooks-seams.md",
+ "gitbooks/developing/embed/concepts/mcp.md",
+ "gitbooks/developing/embed/concepts/memory.md",
+ "gitbooks/developing/embed/concepts/observability.md",
+ "gitbooks/developing/embed/concepts/profiles-saas.md",
+ "gitbooks/developing/embed/concepts/providers.md",
+ "gitbooks/developing/embed/concepts/runtime-defaults.md",
+ "gitbooks/developing/embed/concepts/runtime.md",
+ "gitbooks/developing/embed/concepts/skills.md",
+ "gitbooks/developing/embed/concepts/testing.md",
+ "gitbooks/developing/embed/concepts/tools.md",
+ "gitbooks/developing/embed/concepts/turns-sessions.md",
+ "gitbooks/developing/embed/faq.md",
+ "gitbooks/developing/embed/guides/README.md",
+ "gitbooks/developing/embed/guides/cli-chatbot.md",
+ "gitbooks/developing/embed/guides/deploy-server.md",
+ "gitbooks/developing/embed/guides/lean-headless.md",
+ "gitbooks/developing/embed/guides/mock-backend-testing.md",
+ "gitbooks/developing/embed/guides/multi-agent.md",
+ "gitbooks/developing/embed/guides/saas-multi-tenant.md",
+ "gitbooks/developing/embed/installation.md",
+ "gitbooks/developing/embed/integrations/README.md",
+ "gitbooks/developing/embed/integrations/channels.md",
+ "gitbooks/developing/embed/integrations/composio.md",
+ "gitbooks/developing/embed/integrations/local-models.md",
+ "gitbooks/developing/embed/integrations/mcp.md",
+ "gitbooks/developing/embed/integrations/openai-compatible.md",
+ "gitbooks/developing/embed/integrations/storage-drivers.md",
+ "gitbooks/developing/embed/integrations/tinyhumans-managed.md",
+ "gitbooks/developing/embed/quickstart.md",
+ "gitbooks/developing/embed/troubleshooting.md",
+ "crates/openhuman-embed/README.md",
+ "gitbooks/developing/embedding.md",
+ "gitbooks/developing/embed/cookbook.md",
+ "gitbooks/developing/embed/capability-matrix.md",
+ "gitbooks/developing/embed/builder-setters.md",
+ "gitbooks/developing/embed/api-index.md"
+ ]
+}
diff --git a/docs/gitbooks/en/developing/embed/api-index.md b/docs/gitbooks/en/developing/embed/api-index.md
new file mode 100644
index 0000000000..3e386b0c6d
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/api-index.md
@@ -0,0 +1,268 @@
+# API index
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. [Canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs).
+
+- [`Access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinition`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinitionSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentLayout`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentProgress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentTurnOrigin`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApiKey`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalDecision`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalHandler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalSubscription`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Approvals`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalsError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Auth`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AuthState`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransportError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BaseUrlPurpose`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CancellationToken`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelListener`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatReply`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Completer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionObserver`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionResponse`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionTrace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ComposioHostCredential`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CronError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DEFAULT_MAX_AGENTS`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DaemonConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefaultsInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefinitionBase`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DomainSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`EventStreamError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`GroupMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HTTP_SERVER_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Harness`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessCore`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTurnTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HttpHeader`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`InMemorySessionStores`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRun`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRunRecord`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSchedule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobTarget`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LastTurnUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LearningSettings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpAuthConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpServer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`MemoryBinding`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ModelDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`OpenError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PendingApproval`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PermissionLevel`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PickListenPortError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileHandle`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileId`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileIdMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileSummary`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provisioned`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayAccepted`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RemoveAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Route`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Runtime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEventKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeFlags`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeModule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SaasConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SandboxModeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ScheduledJob`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ServiceSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SessionStoreProvider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SkillsPolicy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StorageInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SystemJobContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TelegramChannelSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TokenSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Tool`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolAttachmentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolExposure`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolGroups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolResult`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolScopeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TransportProfile`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAccess`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAutomationSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Turn`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnOutcome`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnStream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`VOICE_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`WeightClass`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`absolute`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`agent_progress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`artifacts`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`chat_surface`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`complete`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`embeddings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`events`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`identity`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`install_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`installed_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`memory`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`process`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`profiles`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`providers`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`run_from_args`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`schema_for_rpc_method`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`seams`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`skill_registry`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`stream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+
+The compiled capability report describes this build:
+
+```json
+{
+ "schema_version": 1,
+ "configuration_resolved": true,
+ "compiled_features": {
+ "channels": true,
+ "crash-reporting": false,
+ "default": true,
+ "documents": false,
+ "e2e-test-support": false,
+ "file-logging": true,
+ "flows": true,
+ "hosting": false,
+ "http-server": true,
+ "inference": false,
+ "mcp": true,
+ "media": true,
+ "modules": true,
+ "rss-bench": false,
+ "runtime-node": false,
+ "scheduler-gate": true,
+ "skills": true,
+ "storage-file": false,
+ "storage-mongodb": false,
+ "storage-sqlite": false,
+ "tinymemes": true,
+ "voice": false,
+ "web3": false,
+ "whatsapp-web": false
+ },
+ "domains": [
+ "agent",
+ "memory",
+ "threads",
+ "config",
+ "security",
+ "flows",
+ "skills",
+ "channels",
+ "inference",
+ "integrations",
+ "automation",
+ "runtimes",
+ "platform"
+ ],
+ "services": [
+ "harness_init"
+ ],
+ "tool_groups": {
+ "audio": "withheld",
+ "coding": "withheld",
+ "composio": "withheld",
+ "docs": "withheld",
+ "documents": "withheld",
+ "goals": "withheld",
+ "mcp": "withheld",
+ "media": "withheld",
+ "scheduling": "withheld",
+ "skills": "withheld",
+ "storage": "withheld",
+ "system": "withheld",
+ "tasks": "withheld",
+ "web3": "withheld",
+ "workflows": "withheld"
+ },
+ "host_kind": "Library",
+ "max_agents": 1024,
+ "defaults": {
+ "model": {
+ "temperature": 0.7,
+ "max_tokens": null,
+ "top_p": null,
+ "max_iterations": 200
+ },
+ "provider_model": "openrouter/deepseek/deepseek-v4-flash",
+ "routed_provider": false,
+ "sandbox": "None",
+ "approval_gate": true,
+ "include_user_skills": false,
+ "has_skills_root": false,
+ "mcp_servers": 0,
+ "templates": []
+ },
+ "configuration": {
+ "autonomy_enabled": true,
+ "privacy": "Standard",
+ "secrets_encrypted": true,
+ "cron_enabled": true,
+ "learning": {
+ "build_beliefs_every": 10,
+ "learnings_limit": 8
+ },
+ "has_tool_rules": false
+ },
+ "storage": {
+ "source": "workspace",
+ "driver": null,
+ "configured": false
+ },
+ "modules": [],
+ "weight": "custom"
+}
+```
diff --git a/docs/gitbooks/en/developing/embed/api-reference.md b/docs/gitbooks/en/developing/embed/api-reference.md
new file mode 100644
index 0000000000..54d363ad22
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/api-reference.md
@@ -0,0 +1,54 @@
+---
+description: "Use local rustdoc and source-derived indexes for the complete Embed public surface."
+---
+
+# Embedding API reference
+
+Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+
+The crate is currently `publish = false`; docs.rs links are a publication metadata target, not a claim that a live package reference exists. Local rustdoc and [canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) are the current complete reference.
+
+## Generated inventories
+
+- [API index](api-index.md): names exported by the public facade and a versioned runtime report.
+- [Machine-readable API index](api-index.json): export names, builder signatures, capabilities and page paths.
+- [RuntimeBuilder setters](builder-setters.md): current public consuming setters with source locations.
+- [Compiled feature matrix](capability-matrix.md): the actual core gates from the default-feature capability-report executable.
+- [Cookbook](cookbook.md): example titles, run modes and required named facade features from source headers.
+
+The generated setter list is the authoritative knob inventory. It excludes static presets and borrowed inspection/build/run methods; those belong in local rustdoc. Core compiled gates, runtime module/domain selection and named facade exports are separate availability layers.
+
+## Public surface by purpose
+
+| Purpose | API starting point |
+| --- | --- |
+| Boot and inspect a host | `RuntimeBuilder`, `Runtime`, `RuntimeInfo` |
+| Register and remove scoped agents | `AgentSpec`, `Agent`, `AgentDefinitionSpec`, `RemoveAgent` |
+| Configure execution and decisions | `Access`, `SandboxModeSpec`, `Approvals`, `ApprovalHandler` |
+| Execute or stream native turns | `Turn`, `TurnOutcome`, `TurnStream`, `StreamEvent` |
+| Supply custom model adapters | `Provider` and `providers::ChatModel` |
+| Stateless generation | `Completer`, `CompletionRequest`, structured response helpers |
+| Typed non-turn domains | Memory and cron facades, config/auth/artifacts/chat surface |
+| Replace infrastructure ports | `seams`, `session_store`, memory engine and provider contracts |
+| Serve isolated customer profiles | `ProfileRuntime`, `ProfileHandle`, `SaasConfig` |
+
+## Versioned capability data
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The report's schema version is explicit. Read its fields rather than inferring capabilities from preset names, and handle future schema changes deliberately. It omits endpoint, credential, prompt and workspace values so hosts can expose build metadata without exposing private configuration.
diff --git a/docs/gitbooks/en/developing/embed/architecture.md b/docs/gitbooks/en/developing/embed/architecture.md
new file mode 100644
index 0000000000..369b9a2c8c
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/architecture.md
@@ -0,0 +1,68 @@
+---
+description: "The host composes infrastructure around one core; agents derive scoped contexts over its runtime."
+---
+
+# Embedding architecture
+
+Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+
+## Ownership boundaries
+
+| Component | Owns |
+| --- | --- |
+| Your application | UI/HTTP transport, user authentication, supplied credentials, application tools and resource lifetimes |
+| OpenHuman core and Embed facade | Runtime composition, per-agent context, policy, approvals, sandbox selection and typed domain calls |
+| TinyAgents | Model/tool loop, parsing, dialects, durable sessions and transcript replay |
+| TinyInference | Native model/provider contracts and generic ordered fallback |
+| TinyTools | Shared tool traits and contract types |
+| Storage and module libraries | Their backend/module implementations; OpenHuman adapts and orchestrates them |
+
+The library chain is core → Embed → TinyHumans → RPC → app/CLI/TUI. Shipped hosts depend on the layer immediately below them and use its curated facades. Embed users should not build new integrations on doc-hidden `__host` internals.
+
+## Runtime composition versus agent scope
+
+Cargo features decide which implementations exist in an artifact. Runtime domains, services, tool groups and module selection narrow those compiled choices. Agent specs narrow the runtime further and add provider, access, prompt, skills, MCP and action-directory choices.
+
+A turn dispatches through the agent's native context, not through JSON-RPC or an operator fallback. Recursive child contexts inherit the parent host overrides, including custom provider and hook composition, while independent sibling agents remain separately scoped.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs), including runtime construction, imports and fixture setup.
+
+## Lifetime and isolation
+
+An agent handle keeps the core alive after the runtime handle is dropped. Explicit removal marks that instance removed, cancels turns and callbacks, denies parked approvals and clears its state/MCP registration. The ID remains reserved through cleanup, including natural last-handle destruction and cancellation of a started removal. Pointer-checked release prevents an old retained instance from removing a newer registry entry.
+
+Agent separation is not credential separation: all ordinary runtime agents share the operator's config path and credential root. Use [profiles](concepts/profiles-saas.md) for independently authenticated users. See [storage architecture](../architecture/storage.md) for scope/driver ownership and [agent harness architecture](../architecture/agent-harness.md) for session execution.
diff --git a/docs/gitbooks/en/developing/embed/builder-setters.md b/docs/gitbooks/en/developing/embed/builder-setters.md
new file mode 100644
index 0000000000..f2cded84d6
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/builder-setters.md
@@ -0,0 +1,48 @@
+# RuntimeBuilder setters
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+
+- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L343): `pub fn access(mut self, access: Access) -> Self`
+- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L300): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`
+- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L151): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`
+- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L320): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`
+- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L186): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`
+- [`backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L225): `pub fn backend_transport(mut self, transport: Arc<dyn BackendTransport>) -> Self`
+- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L330): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L444): `pub fn config(mut self, config: Config) -> Self`
+- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L308): `pub fn config_source(mut self, source: ConfigSource) -> Self`
+- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L415): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L211): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`
+- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L170): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`
+- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L374): `pub fn domains(mut self, domains: DomainSet) -> Self`
+- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L391): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`
+- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L206): `pub fn learning(mut self, value: super::LearningSettings) -> Self`
+- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L413): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`
+- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L418): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`
+- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L424): `pub fn listen_port(mut self, port: u16) -> Self`
+- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L464): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`
+- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L263): `pub fn max_agents(mut self, limit: usize) -> Self`
+- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L181): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`
+- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L239): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`
+- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L160): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L156): `pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self`
+- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L430): `pub fn post_turn_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self`
+- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L196): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`
+- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L336): `pub fn provider(mut self, provider: Provider) -> Self`
+- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L165): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`
+- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L201): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`
+- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L444): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`
+- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L362): `pub fn services(mut self, services: ServiceSet) -> Self`
+- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L434): `pub fn session(mut self, session: Session) -> Self`
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L254): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`
+- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L175): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`
+- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L457): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`
+- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L401): `pub fn token(mut self, token: TokenSource) -> Self`
+- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L383): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`
+- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L437): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook>) -> Self`
+- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L422): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`
+- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L191): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`
+- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L273): `pub fn workspace(mut self, workspace: Workspace) -> Self`
+- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L287): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`
diff --git a/docs/gitbooks/en/developing/embed/capability-matrix.md b/docs/gitbooks/en/developing/embed/capability-matrix.md
new file mode 100644
index 0000000000..aba183fbf7
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/capability-matrix.md
@@ -0,0 +1,32 @@
+# Compiled feature matrix
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+
+| Cargo feature | Compiled in this build |
+| --- | --- |
+| `channels` | Yes |
+| `crash-reporting` | No |
+| `default` | Yes |
+| `documents` | No |
+| `e2e-test-support` | No |
+| `file-logging` | Yes |
+| `flows` | Yes |
+| `hosting` | No |
+| `http-server` | Yes |
+| `inference` | No |
+| `mcp` | Yes |
+| `media` | Yes |
+| `modules` | Yes |
+| `rss-bench` | No |
+| `runtime-node` | No |
+| `scheduler-gate` | Yes |
+| `skills` | Yes |
+| `storage-file` | No |
+| `storage-mongodb` | No |
+| `storage-sqlite` | No |
+| `tinymemes` | Yes |
+| `voice` | No |
+| `web3` | No |
+| `whatsapp-web` | No |
diff --git a/docs/gitbooks/en/developing/embed/concepts/README.md b/docs/gitbooks/en/developing/embed/concepts/README.md
new file mode 100644
index 0000000000..5262dcd86a
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/README.md
@@ -0,0 +1,26 @@
+---
+description: "The ownership and lifecycle rules behind the Embed public API."
+---
+
+# Concepts
+
+Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+
+- [Runtime](runtime.md): A Runtime owns one initialized core and the process-wide resources that its agents share.
+- [Runtime defaults](runtime-defaults.md): Runtime defaults form the starting point for newly registered agents; explicit agent settings override them.
+- [Agents](agents.md): An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime.
+- [Access and approvals](access-approvals.md): Access configures turn identity and permission policy; the host chooses how parked requests receive decisions.
+- [Providers](providers.md): A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback.
+- [Turns and sessions](turns-sessions.md): A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation.
+- [Tools](tools.md): Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools.
+- [MCP](mcp.md): MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists.
+- [Skills](skills.md): Skills are copied bundles of instructions and resources discovered inside an agent’s own home.
+- [Memory](memory.md): The typed memory facade binds a namespace before learning, retrieving or forgetting records.
+- [Cron](cron.md): Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents.
+- [Channels](channels.md): A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control.
+- [Profiles and SaaS](profiles-saas.md): ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams.
+- [Completer](completer.md): Completer sends stateless model requests without booting a Runtime or entering the agent tool loop.
+- [Hooks and seams](hooks-seams.md): Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries.
+- [Observability](observability.md): Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result.
+- [Testing](testing.md): Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services.
+- [Errors](errors.md): Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances.
diff --git a/docs/gitbooks/en/developing/embed/concepts/access-approvals.md b/docs/gitbooks/en/developing/embed/concepts/access-approvals.md
new file mode 100644
index 0000000000..eef15dbe59
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/access-approvals.md
@@ -0,0 +1,80 @@
+---
+description: "Access configures turn identity and permission policy; the host chooses how parked requests receive decisions."
+---
+
+# Access and approvals
+
+`Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+
+The core autonomy policy is disabled by default. Set `config.autonomy.enabled` when you require its command classification, approval gate, allowlist and budget enforcement. Platform isolation and the credential/system-root safety floor have separate responsibilities; a tool group filter is not an operating-system sandbox.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Autonomy policy defaults and installed approval gate | Origin, access tier, grants, trusted roots and scoped decisions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/approvals.rs#approvals -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("approved-marker");
+ let write_provider = support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", marker.display())}).to_string(),
+ )],
+ "approved",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("supervised")
+ .provider(support::route(&write_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: "demo".into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.path().display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(
+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ ),
+ )?;
+ let pending_agent = agent.clone();
+ let turn = tokio::spawn(async move { pending_agent.run("Create a marker").await });
+ let pending = support::eventually("approval", || {
+ agent.approvals().pending().ok()?.into_iter().next()
+ })
+ .await;
+ assert!(!marker.exists(), "execution waits for the host decision");
+ assert_eq!(pending.agent_id.as_deref(), Some("supervised"));
+ agent.approvals().decide(
+ &pending.request_id,
+ openhuman_embed::ApprovalDecision::ApproveOnce,
+ )?;
+ assert_eq!(turn.await??.reply, "approved");
+ assert!(marker.exists());
+ assert!(agent.approvals().pending()?.is_empty());
+ println!("parked write executed only after approval");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified example enables autonomy before building the runtime. It starts a real shell write, observes that no marker exists while the call is parked, and creates it only after `ApproveOnce`. `agent.approvals()` lists and decides only that instance's requests. A removed instance returns an empty pending list and rejects decisions even if the same public ID has been reused.
+
+For asynchronous integration use `AgentSpec::approval_handler` or retain the handle returned by `Agent::handle_approvals`. Dropping a subscription cancels its pending decision future; it does not silently approve the request. Agent removal cancels both builder and live callbacks. Continue with the [approval callback example](../cookbook.md#polling-and-callback-approvals-with-cancellation) and [sandbox guide](../guides/multi-agent.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/agents.md b/docs/gitbooks/en/developing/embed/concepts/agents.md
new file mode 100644
index 0000000000..7037a766eb
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/agents.md
@@ -0,0 +1,59 @@
+---
+description: "An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime."
+---
+
+# Agents
+
+Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+
+Keep `action_dir` separate from the internal workspace. The action directory is where tools act; the agent home stores internal transcripts, skills and other state. The example gives a reviewer and a fixer distinct folders and prompts while sharing one provider connection setup.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Core, shared configuration path and registry capacity | ID, context, prompt, action directory, provider and per-agent stores |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+IDs stay reserved until teardown completes, including while the last handle's destructor is clearing state. `remove_agent(id).await` marks retained handles removed, cancels active turns, denies parked approvals and releases the ID after cleanup. Add `.purge()` only when the agent's persisted home should also be deleted. Cancelling a started removal still performs teardown and a requested purge.
+
+An old polling handle or approval callback never follows a reused ID to its replacement. Active host tools cancel cooperatively and may finish their external work after removal; the host still owns those external lifetimes. See [turns and sessions](turns-sessions.md) and [access and approvals](access-approvals.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/channels.md b/docs/gitbooks/en/developing/embed/concepts/channels.md
new file mode 100644
index 0000000000..6588d7dbe3
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/channels.md
@@ -0,0 +1,93 @@
+---
+description: "A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control."
+---
+
+# Channels
+
+`Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+
+The named Embed `channels` feature is enabled by default. The runtime must also allow the channel family. Create listeners inside the Tokio runtime after their agents have been registered.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Channel implementation, listener registry and runtime domain ceiling | Bound agent, conversation identity and external-message access context |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified Telegram example uses a local Bot API stub, so the channel test does not contact Telegram. Its live mode requires explicit example credentials and remains opt-in.
+
+External messages use `ExternalChannel` origin and a read-only cap. Model-requested writes and other external effects are not parked for approval from the sender. Keep public-chat tools read-only and perform authorized side effects in host code or a separately configured job. When the bound agent is removed, channel work fails as unavailable instead of falling back to the operator. See [channel integration](../integrations/channels.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/completer.md b/docs/gitbooks/en/developing/embed/concepts/completer.md
new file mode 100644
index 0000000000..e97f5077c8
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/completer.md
@@ -0,0 +1,46 @@
+---
+description: "Completer sends stateless model requests without booting a Runtime or entering the agent tool loop."
+---
+
+# Completer
+
+Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+
+A standalone completer does not claim the process runtime slot. An agent-backed completion uses the agent's effective configuration but still has no implicit durable session. Keep conversation state in your application if you need several completion calls to form a conversation.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| No runtime required for a standalone routed Completer | Optional effective agent configuration; no implicit tools or transcript |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/completer.rs#completer -->
+
+```rust
+ let route = support::example_provider(&provider)?;
+ let completer = openhuman_embed::Completer::new(route.route().expect("explicit route").clone());
+ let response = completer
+ .complete(openhuman_embed::CompletionRequest::new(
+ route.model_id().expect("explicit model"),
+ vec![openhuman_embed::ChatMessage::user("Say hello")],
+ ))
+ .await?;
+ assert!(!response.text.is_empty());
+ if support::offline() {
+ assert_eq!(response.text, "completion reply");
+ assert_eq!(support::chat_requests(&provider).await.len(), 1);
+ }
+ println!("{}", response.text);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks that exactly one inference request was made and verifies the returned text. It uses a local provider fixture by default; the source contains the explicit opt-in live route path.
+
+Choose `Agent` when a model should call tools, resume a durable thread or execute with an agent's access context. Choose the structured completion helpers when the host only needs a validated data result. For routes and transport failures see [providers](providers.md) and [errors](errors.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/cron.md b/docs/gitbooks/en/developing/embed/concepts/cron.md
new file mode 100644
index 0000000000..4f2ee929c1
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/cron.md
@@ -0,0 +1,54 @@
+---
+description: "Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents."
+---
+
+# Cron
+
+The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+
+Background scheduling is a runtime service choice. Explicit `run_now` is useful for tests and host-triggered execution without relying on wall-clock scheduling. Keep the agent registered while scheduled work should be available.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cron storage, scheduler service and system-job handlers | Addressed job target and the agent configuration used for its turn |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/cron.rs#cron -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("scheduled"))?;
+ let cron = runtime.cron();
+ let spec = openhuman_embed::JobSpec::agent(
+ "daily",
+ agent.id(),
+ "Say hello",
+ openhuman_embed::JobSchedule::Cron {
+ expr: "0 0 * * *".into(),
+ tz: None,
+ },
+ );
+ let first = cron.upsert(spec.clone())?;
+ assert_eq!(cron.upsert(spec)?.id, first.id);
+ let run = cron.run_now("daily").await?;
+ assert!(run.success, "{}", run.output);
+ if support::offline() {
+ assert!(run.output.contains("hello from the stub"));
+ }
+ assert_eq!(cron.runs("daily", 1)?[0].status, "ok");
+ assert!(cron.remove("daily")?);
+ assert!(cron.list()?.is_empty());
+ println!("cron execution and history verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks stable upsert identity, executes a job immediately, inspects a successful run record, and removes the job. No test waits for a daily schedule to arrive.
+
+Removing or dropping an agent deregisters its context, leaving addressed cron jobs dormant rather than silently running them as the operator. Hosts can register runtime system-job handlers for work they own outside a model turn. Review [runtime configuration](runtime-defaults.md) and [channels](channels.md) when mixing scheduled work with public chat input.
diff --git a/docs/gitbooks/en/developing/embed/concepts/errors.md b/docs/gitbooks/en/developing/embed/concepts/errors.md
new file mode 100644
index 0000000000..f7bb71ddfa
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/errors.md
@@ -0,0 +1,61 @@
+---
+description: "Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances."
+---
+
+# Errors
+
+Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+
+A structured `CoreError::Domain` carries a stable kind and `expected_user_state`. Expected stale-session or missing-resource states should be shown as notices rather than treated as internal faults. `Decode` signals a facade/domain shape mismatch; retrying unchanged input does not repair it.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Boot errors, unavailable domains and shared transport setup | Registration errors, scoped domain failures and AgentRemoved on retained handles |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/sandbox_access.rs#sandbox_access -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("attempted-write");
+ let attempted_write = support::tool_call_completion(
+ "write_file",
+ &serde_json::json!({
+ "path": marker.display().to_string(), "content": "example"
+ })
+ .to_string(),
+ );
+ let read_provider = support::scripted_provider(vec![attempted_write], "write refused").await;
+ let read = runtime.agent(
+ AgentSpec::new("read")
+ .provider(support::route(&read_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(openhuman_embed::Access::readonly())
+ .definition(
+ AgentDefinitionSpec::new().sandbox(openhuman_embed::SandboxModeSpec::ReadOnly),
+ ),
+ )?;
+ let full = runtime.agent(AgentSpec::new("full").access(openhuman_embed::Access::full()))?;
+ assert_ne!(read.config().autonomy.level, full.config().autonomy.level);
+ assert!(!read.run("Write a marker").await?.reply.is_empty());
+ assert!(
+ !marker.exists(),
+ "readonly sandbox must refuse the attempted write"
+ );
+ let requests = support::chat_requests(&read_provider).await;
+ assert!(!support::tool_names(&requests[0]).contains(&"write_file".to_string()));
+ println!("readonly sandbox refused a model-requested write");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example's refused write is handled as a tool result while the turn can still finish with a reply. Do not assume every rejected tool action is a failed turn. Conversely, a finished stream can contain an error; always inspect `StreamEvent::Finished`.
+
+Bearer routes refuse non-TLS remote endpoints before sending credentials. `BACKEND_UNAVAILABLE` means the embed-only host has no backend transport installed; check the host layer before rotating keys. Agent removal makes later turns on retained handles return `AgentRemoved`, even when its ID now belongs to another instance. See [troubleshooting](../troubleshooting.md) and [provider integration](../integrations/openai-compatible.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/hooks-seams.md b/docs/gitbooks/en/developing/embed/concepts/hooks-seams.md
new file mode 100644
index 0000000000..cbbe25c8d4
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/hooks-seams.md
@@ -0,0 +1,45 @@
+---
+description: "Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries."
+---
+
+# Hooks and seams
+
+Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+
+Post-turn and tool hooks can be registered runtime-wide or on one agent. Agent hooks compose with parent runtime hooks and do not leak into sibling contexts. Use stable hook names to replace or remove runtime registrations through the live API; changes apply to subsequent turns.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Shared port implementations and named global hook registrations | Scoped hooks and host overrides inherited by recursive child contexts |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/hooks.rs#hooks -->
+
+```rust
+ let count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let agent = runtime.agent(
+ AgentSpec::new("hooked").post_turn_hook(std::sync::Arc::new(Counter(count.clone()))),
+ )?;
+ let sibling = runtime.agent(AgentSpec::new("sibling"))?;
+ assert!(!agent.run("Hello hook").await?.reply.is_empty());
+ support::eventually("post-turn hook", || {
+ (count.load(std::sync::atomic::Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ assert!(!sibling.run("Hello sibling").await?.reply.is_empty());
+ assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
+ println!("post-turn hook isolated to its agent");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example verifies that an agent-local post-turn counter observes the configured agent and not its sibling. Runtime live add/remove behavior is demonstrated in the [runtime events example](../cookbook.md#runtime-lifecycle-events-and-live-hook-registration).
+
+Removing or replacing a builder-installed named hook through the runtime API affects that registration too; the runtime tracks and restores prior process slots when its seam ownership ends. Keep hooks fast, cancellation-aware and free of sensitive logging. Use the generated [setter list](../builder-setters.md) and [API reference](../api-reference.md) for the actual port signatures.
diff --git a/docs/gitbooks/en/developing/embed/concepts/mcp.md b/docs/gitbooks/en/developing/embed/concepts/mcp.md
new file mode 100644
index 0000000000..4bc0c350fd
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/mcp.md
@@ -0,0 +1,74 @@
+---
+description: "MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists."
+---
+
+# MCP
+
+MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+
+Enable the named Embed `mcp` Cargo feature for `McpServer` and the agent setter. The default core may already contain MCP code, but a core capability flag does not activate a separately gated Embed API. Runtime domain selection must also allow the MCP family.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Compiled MCP implementation and runtime domain ceiling | Server configuration, auth, discovery and allowed remote tools |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses a real loopback protocol stub: it verifies initialization, `tools/list`, and `tools/call`, then checks that the model saw the remote result. It does not call an external MCP service or require credentials.
+
+Tool allowlists reduce the remote catalog before model disclosure. Server authentication remains host-owned input, and remote tool side effects still pass through the relevant execution/access policy. Removing the agent evicts its MCP host after old-instance teardown, before the ID can be reused. See the [MCP integration](../integrations/mcp.md) for deployment setup.
diff --git a/docs/gitbooks/en/developing/embed/concepts/memory.md b/docs/gitbooks/en/developing/embed/concepts/memory.md
new file mode 100644
index 0000000000..02ac00af99
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/memory.md
@@ -0,0 +1,43 @@
+---
+description: "The typed memory facade binds a namespace before learning, retrieving or forgetting records."
+---
+
+# Memory
+
+`Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+
+A custom `memory_engine` can replace the default engine for a host or test. An agent's `MemoryBinding` configures its own memory context, while the runtime owns engine availability. Scope namespaces separately from provider/model choices: changing inference does not move a record to another tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Memory engine seam and available memory domain | MemoryBinding, acting context and bound namespace |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/memory.rs#memory -->
+
+```rust
+ let acme = runtime.memory("team:acme")?;
+ let other = runtime.memory("team:other")?;
+ let params = serde_json::from_value(serde_json::json!({"text":"Acme ships on Fridays"}))?;
+ let learned = acme.learn(params).await?;
+ let hits = acme.get(vec![learned.id.clone()]).await?;
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].meta.namespace.to_string(), "team:acme");
+ assert!(other.get(vec![learned.id.clone()]).await?.is_empty());
+ assert_eq!(other.forget(vec![learned.id.clone()]).await?.forgotten, 0);
+ assert_eq!(acme.forget(vec![learned.id]).await?.forgotten, 1);
+ println!("memory learning, tenant isolation and deletion verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses the reference in-memory engine and proves that another namespace cannot retrieve or forget the first namespace's record. Forgetting succeeds only through the owning namespace. This is a scope test, not a persistence claim; choose a durable engine/backend for application state that must survive restarts.
+
+Background conversation ingestion can run independently of a completed turn. Tests should disable unrelated learning/ingest activity when asserting ephemeral-workspace cleanup. See [runtime defaults](runtime-defaults.md), [storage drivers](../integrations/storage-drivers.md), and the [memory architecture](../../architecture/memory.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/observability.md b/docs/gitbooks/en/developing/embed/concepts/observability.md
new file mode 100644
index 0000000000..26c78c0d28
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/observability.md
@@ -0,0 +1,73 @@
+---
+description: "Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result."
+---
+
+# Observability
+
+Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+
+Runtime events contain lifecycle metadata, not user prompts or model output. Detailed text/tool progress belongs to the explicitly requested turn stream. A bounded event receiver reports lag explicitly rather than silently claiming that it delivered every event.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Runtime sequence, content-safe lifecycle feed and registered-agent filter | Per-call turn correlation and opt-in text/tool progress stream |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/runtime_events.rs#runtime_events -->
+
+```rust
+ let mut events = runtime.events();
+ let count = Arc::new(AtomicUsize::new(0));
+ runtime.post_turn_hook("live-counter", Some(Arc::new(Counter(count.clone()))));
+ let agent = runtime.agent(AgentSpec::new("observed"))?;
+ assert_eq!(agent.run("private payload one").await?.reply, "event reply");
+ support::eventually("runtime hook", || {
+ (count.load(Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ runtime.post_turn_hook("live-counter", None);
+ assert_eq!(agent.run("private payload two").await?.reply, "event reply");
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 1,
+ "removed hook stops observing turns"
+ );
+ runtime.remove_agent(agent.id()).await?;
+ let mut previous = 0;
+ let (mut added, mut started, mut ended) = (0, 0, 0);
+ loop {
+ let event =
+ tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()).await??;
+ assert!(event.sequence > previous);
+ previous = event.sequence;
+ assert_eq!(event.agent_id.as_deref(), Some("observed"));
+ assert!(!serde_json::to_string(&event)?.contains("private payload"));
+ match event.kind {
+ RuntimeEventKind::AgentAdded => added += 1,
+ RuntimeEventKind::TurnStarted => {
+ assert!(event.turn_id.is_some());
+ started += 1;
+ }
+ RuntimeEventKind::TurnEnded { success } => {
+ assert!(success);
+ ended += 1;
+ }
+ RuntimeEventKind::AgentRemoved => break,
+ _ => {}
+ }
+ }
+ assert_eq!((added, started, ended), (1, 2, 2));
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks ordered add/start/end/remove events and confirms that private prompt text is absent from serialized metadata. Approval events are filtered to agents registered on this runtime. Correlation follows the effective origin thread; a request's later decision keeps its original turn correlation after the turn has ended.
+
+When simultaneous turns share an origin thread, approval correlation can be ambiguous and its turn ID is absent rather than guessed. Handle receiver lag by refreshing state, and do not send text from `AgentProgress` to content-free analytics. See [turns and sessions](turns-sessions.md), [approvals](access-approvals.md), and [testing](testing.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/profiles-saas.md b/docs/gitbooks/en/developing/embed/concepts/profiles-saas.md
new file mode 100644
index 0000000000..7c1e8ef868
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/profiles-saas.md
@@ -0,0 +1,61 @@
+---
+description: "ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams."
+---
+
+# Profiles and SaaS
+
+Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+
+Profile mode claims the process separately from ordinary `Runtime` and `Harness`. Its root must satisfy the boot guard: absolute, existing, outside the operator's workspace and not world-writable. Remove single-user workspace/token environment variables before booting a profile server.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| One profile host, shared compiled core and managed backend transport | Per-profile credential, workspace, threads, memory and event access |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example creates Alice and Bob with the same thread name and verifies that each transcript contains only its own note. Handles keep their profiles open; release/idle eviction can close a profile only after those handles are dropped.
+
+Production managed calls need the TinyHumans transport installed by the host layer. `ProfileHandle::call` exposes the reviewed user surface rather than arbitrary operator controllers. Profiles do not make a shared file-system action directory safe automatically; provision external application resources per user too. See [SaaS deployment guide](../guides/saas-multi-tenant.md) and [SaaS architecture](../../saas-profiles.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/providers.md b/docs/gitbooks/en/developing/embed/concepts/providers.md
new file mode 100644
index 0000000000..d04e5f74de
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/providers.md
@@ -0,0 +1,80 @@
+---
+description: "A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback."
+---
+
+# Providers
+
+A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+
+Named workload roles bind an adapter to selections such as `hint:coding`. The example proves that the role-pinned model bypasses the primary fallback chain. These pins are explicit host configuration; they do not ask the model to decide its own provider.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default route/model and native adapter chain | Provider override, model selection and workload hint |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Ordered fallback advances only on eligible provider failures before visible output. Validation or unsupported-input failures stop the chain. Once text, reasoning or tool-call content becomes visible, the chosen stream keeps its identity and a later failure is reported without switching providers. Requests, options, correlation metadata and cancellation remain attached to the selected adapter.
+
+Use HTTPS when sending bearer credentials; loopback HTTP is supported for local test/model servers. Managed inference needs the TinyHumans host transport and a runtime credential. See [OpenAI-compatible integration](../integrations/openai-compatible.md), [managed integration](../integrations/tinyhumans-managed.md), and [local models](../integrations/local-models.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/runtime-defaults.md b/docs/gitbooks/en/developing/embed/concepts/runtime-defaults.md
new file mode 100644
index 0000000000..13a56ef3b5
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/runtime-defaults.md
@@ -0,0 +1,62 @@
+---
+description: "Runtime defaults form the starting point for newly registered agents; explicit agent settings override them."
+---
+
+# Runtime defaults
+
+The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+
+`Runtime::defaults()` returns a snapshot. Runtime default setters affect agents created afterward; existing agents retain the configuration they were built with. Configure an explicit agent override when its behavior must remain independent of future runtime defaults.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default provider, access and generation settings | Explicit override captured when AgentSpec is registered |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks the request bodies actually received by both providers, including model, temperature and maximum tokens. This distinction matters when testing a configuration change: a correct defaults snapshot alone does not prove that inference received those values.
+
+Use the generated [builder setters](../builder-setters.md) for the current knob list. [Configuration and installation](../installation.md) explain runtime configuration discovery; [providers](providers.md) cover route selection and native models.
diff --git a/docs/gitbooks/en/developing/embed/concepts/runtime.md b/docs/gitbooks/en/developing/embed/concepts/runtime.md
new file mode 100644
index 0000000000..2270f91ceb
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/runtime.md
@@ -0,0 +1,40 @@
+---
+description: "A Runtime owns one initialized core and the process-wide resources that its agents share."
+---
+
+# Runtime
+
+A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+
+The process guard rejects a second runtime with `RuntimeError::AlreadyRunning`. Independent customer credentials and workspaces require [profiles](profiles-saas.md), rather than several ordinary runtimes. `Harness` is the one-agent shorthand and exposes its underlying runtime and agent if you later need more agents.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cargo gates and selected domains/services | Provider, prompt, working folder and tool scope |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+`RuntimeBuilder::describe()` reports a plan before boot; `Runtime::capabilities()` reports resolved configuration afterward. The versioned metadata excludes credentials, endpoints, prompts and workspace paths. Use its `configuration_resolved` flag when deciding whether to treat an inspection result as effective configuration.
+
+Dropping the runtime handle does not tear down the core while an agent still holds it. Drop listeners, agents and the runtime before restarting the host in the same process. See [architecture](../architecture.md), [defaults](runtime-defaults.md), and the generated [builder setters](../builder-setters.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/skills.md b/docs/gitbooks/en/developing/embed/concepts/skills.md
new file mode 100644
index 0000000000..e95f500cc4
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/skills.md
@@ -0,0 +1,47 @@
+---
+description: "Skills are copied bundles of instructions and resources discovered inside an agent\u2019s own home."
+---
+
+# Skills
+
+A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+
+Enable the named Embed `skills` feature for skill setters and registry access. Library agents hide the operator's user skill directory unless `include_user_skills(true)` is explicitly selected. Treat skill installation as part of the agent's configuration, rather than reading arbitrary operator files into every tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Skill registry seam and default user-skill policy | Copied bundles, discovery context and explicit user-skill opt-in |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/skills.rs#skills -->
+
+```rust
+ let skills = tempfile::tempdir()?;
+ std::fs::create_dir(skills.path().join("review"))?;
+ std::fs::write(skills.path().join("review/SKILL.md"),
+ "---\nname: review\ndescription: Review Rust functions carefully.\n---\nCheck error paths.\n")?;
+ let agent = runtime.agent(AgentSpec::new("skilled").skills_dir(skills.path()))?;
+ let copied = agent
+ .workspace_dir()
+ .join("agents/skilled/skills/review/SKILL.md");
+ assert_eq!(
+ std::fs::read_to_string(&copied)?,
+ std::fs::read_to_string(skills.path().join("review/SKILL.md"))?
+ );
+ assert!(!std::fs::symlink_metadata(copied)?.file_type().is_symlink());
+ assert!(!agent.run("Hello").await?.reply.is_empty());
+ println!("skill bundle copied without symlinks");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example writes a bundle, registers an agent, checks the copied contents and verifies that the destination is not a symlink. Use the same directory layout for production bundles; do not depend on the fixture's temporary directory lifetime.
+
+A resumed session's prompt is frozen, so adding or editing a bundle does not rewrite an existing conversation's recorded prefix. Start a new session when you want updated instructions to become visible. See [turns and sessions](turns-sessions.md) and the generated [builder setters](../builder-setters.md) for runtime policy knobs.
diff --git a/docs/gitbooks/en/developing/embed/concepts/testing.md b/docs/gitbooks/en/developing/embed/concepts/testing.md
new file mode 100644
index 0000000000..883138743b
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/testing.md
@@ -0,0 +1,80 @@
+---
+description: "Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services."
+---
+
+# Testing
+
+The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+
+A native `ChatModel<()>` stub is useful for provider selection and cancellation tests without HTTP. Protocol-level stubs remain useful for OpenAI-compatible routing, MCP or messaging transport behavior. Pick the boundary whose behavior your host needs to verify.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Offline configuration, mock backend and injected model/engine ports | Isolated temp action directories, deterministic IDs and scoped assertions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Run the offline example suite with `node scripts/run-embed-examples.mjs`; it clears inherited credentials/workspaces and uses one union feature graph for all examples. Run embed unit/integration tests with `cargo test -p openhuman-embed --features mcp,skills,channels,storage-sqlite --lib --tests -- --test-threads=1`.
+
+Build your Tokio workers with the documented large stack constants for nested agent turns. Use channels, cancellation guards and bounded waits to prove lifecycle transitions instead of sleeps. The [mock-backend guide](../guides/mock-backend-testing.md) covers host fixtures, and [troubleshooting](../troubleshooting.md) distinguishes compile gates from runtime availability.
diff --git a/docs/gitbooks/en/developing/embed/concepts/tools.md b/docs/gitbooks/en/developing/embed/concepts/tools.md
new file mode 100644
index 0000000000..b8465163dc
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/tools.md
@@ -0,0 +1,59 @@
+---
+description: "Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools."
+---
+
+# Tools
+
+An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+
+`AgentSpec::tools` is a per-turn factory returning `HostTurnTools`. Factories can attach the turn's context to their executors without sharing mutable tool state across unrelated sessions. Import `Tool` and `ToolResult` from `openhuman_embed` so their types match the vendored implementation used by the core.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Domain/tool-group ceiling and shared execution policy | ToolScopeSpec, advertised host belt, attachments and prompt |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example drives an actual host tool call and inspects the provider's advertised catalog: it contains only `host_ping`, which executes exactly once. A host executor remains responsible for authorizing its own application operations. Catalog visibility narrows what the model sees; it is not a substitute for permission checks or sandboxing.
+
+Runtime tool hooks apply across agents; local hooks observe only their configured agent. Tool attachments can be added and removed for later turns, while existing durable sessions retain recorded declarations. See [hooks](hooks-seams.md), [MCP](mcp.md), and [access and approvals](access-approvals.md).
diff --git a/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md b/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md
new file mode 100644
index 0000000000..2e5f7c61b1
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/concepts/turns-sessions.md
@@ -0,0 +1,65 @@
+---
+description: "A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation."
+---
+
+# Turns and sessions
+
+`Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+
+`Agent::stream` returns a bounded `TurnStream`. Drain it while the turn is running: progress includes visible deltas and tool lifecycle notifications, followed by one `StreamEvent::Finished` containing the typed final result. Dropping the stream cancels its turn and recursive child work cooperatively.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Session store provider and shared progress/event infrastructure | Durable agent/thread identity, transcript and per-call cancellation |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The stream example checks that deltas precede the final result and that collected and streaming replies agree. A cancellation token passed to a turn is preserved by streaming; cancellation unblocks forwarding even when the consumer has stopped draining a full buffer.
+
+The harness derives transcript paths from the thread and agent IDs without a timestamp. Resumed sessions reuse their recorded system prompt and tool declarations; edits to prompts, skills or integrations apply to new sessions. Compaction seals a generation and opens a child instead of erasing history. See [observability](observability.md) for session IDs versus per-call turn IDs, and [API reference](../api-reference.md) for the session-store port.
diff --git a/docs/gitbooks/en/developing/embed/cookbook.md b/docs/gitbooks/en/developing/embed/cookbook.md
new file mode 100644
index 0000000000..6b7caefc55
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/cookbook.md
@@ -0,0 +1,181 @@
+# Cookbook
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+
+## Polling and callback approvals with cancellation
+
+Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example approvals`
+
+## Stable capability metadata before and after boot
+
+Stable capability metadata before and after boot.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example capability_report`
+
+## Stateless completion without booting an agent runtime
+
+Stateless completion without booting an agent runtime.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example completer`
+
+## Run and inspect an agent cron job
+
+Run and inspect an agent cron job.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example cron`
+
+## Native custom providers, fallback and workload role pins
+
+Inject deterministic native models and prove fallback and role selection without inference HTTP.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) · offline; no live inference path.
+
+Run: `cargo run -p openhuman-embed --example custom_provider`
+
+## Runtime defaults and per-agent overrides
+
+Runtime defaults and per-agent overrides.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example defaults_overrides`
+
+## A per-agent post-turn hook observes completed turns
+
+A per-agent post-turn hook observes completed turns.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example hooks`
+
+## Host tools and HostOnly keep the advertised tool catalog exact
+
+Host tools and HostOnly keep the advertised tool catalog exact.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example host_tools`
+
+## Lean runtime without background services
+
+Lean runtime without background services.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) · offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.
+
+Run: `cargo run -p openhuman-embed --example lean_headless`
+
+## Connect an actual MCP protocol stub over loopback
+
+Connect an actual MCP protocol stub over loopback.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) · offline with loopback stubs; no live path. · feature: mcp
+
+Run: `cargo run -p openhuman-embed --example mcp --features mcp`
+
+## Tenant scoped memory facade with an in-memory engine
+
+Tenant scoped memory facade with an in-memory engine.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example memory`
+
+## SaaS profiles isolate conversation history
+
+SaaS profiles isolate conversation history.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example profiles`
+
+## Hello agent: a prompt in and a reply out
+
+Hello agent: a prompt in and a reply out.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example run_turn`
+
+## Runtime lifecycle events and live hook registration
+
+Observe ordered metadata and add/remove a runtime-wide hook while agents keep running.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs) · offline with a loopback provider; no live path.
+
+Run: `cargo run -p openhuman-embed --example runtime_events`
+
+## Access tiers and explicit sandbox choices
+
+Access tiers and explicit sandbox choices.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example sandbox_access`
+
+## Embed an agent behind a host-owned HTTP server
+
+Embed an agent behind a host-owned HTTP server.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example server`
+
+## Copy a skill bundle into its agent workspace
+
+Copy a skill bundle into its agent workspace.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL. · feature: skills
+
+Run: `cargo run -p openhuman-embed --example skills --features skills`
+
+## SQLite writes and MongoDB configuration through Embed
+
+Open a real local SQLite backend and describe a MongoDB deployment without connecting.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) · offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb. · feature: storage-sqlite
+
+Run: `cargo run -p openhuman-embed --example storage --features storage-sqlite`
+
+## Streaming progress with a draining receiver
+
+Streaming progress with a draining receiver.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example streaming`
+
+## Structured output parsed and checked against the request
+
+Structured output parsed and checked against the request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/structured_output.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example structured_output`
+
+## Telegram channel answered by its bound agent via a local Bot API
+
+Telegram channel answered by its bound agent via a local Bot API.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) · offline with loopback stubs; no live path. · feature: channels
+
+Run: `cargo run -p openhuman-embed --example telegram --features channels`
+
+## Two agents with independent prompts and working folders
+
+Two agents with independent prompts and working folders.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example two_agents`
diff --git a/docs/gitbooks/en/developing/embed/faq.md b/docs/gitbooks/en/developing/embed/faq.md
new file mode 100644
index 0000000000..ec7e19cf55
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/faq.md
@@ -0,0 +1,41 @@
+---
+description: "Answers to common host, lifecycle, feature and provider choices."
+---
+
+# Embedding FAQ
+
+## Can I create more than one runtime?
+
+An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See [runtime](concepts/runtime.md) and [profiles](concepts/profiles-saas.md).
+
+## Is an agent clone an independent agent?
+
+No. It is another handle to the same agent instance, context and state. Register a different `AgentSpec` ID for a separate agent. Runtime credentials are still shared, so agent IDs alone do not isolate authenticated customers.
+
+## Does lean mean fewer dependencies?
+
+`RuntimeBuilder::lean()` selects a smaller runtime surface. Cargo still compiles enabled gates; use `--no-default-features` and explicit named gates for graph reduction. The [compiled matrix](capability-matrix.md) reports one fixed default build, and the [lean guide](guides/lean-headless.md) separates those controls.
+
+## Why do MCP or skills methods disappear while the report says they are compiled?
+
+The report describes core Cargo gates. Named Embed gates control facade exports too. Enable Embed's `mcp` or `skills` feature for their setters/re-exports, even when core defaults already compile the implementation. `channels` is named in Embed defaults.
+
+## Can I supply an in-process model without HTTP?
+
+Yes: `Provider::custom` takes the native `ChatModel<()>` contract. A provider can add an ordered fallback chain and explicit workload role pins. [Providers](concepts/providers.md) describes the rule that fallback stops after visible output.
+
+## Do I need the backend for every agent turn?
+
+An explicit BYOK/local/native provider can run independently of hosted inference. Hosted integrations, voice, billing or other backend surfaces need an installed backend transport and a credential. Use the [TinyHumans layer](integrations/tinyhumans-managed.md) for managed calls; Embed alone reports backend unavailable.
+
+## Can an old handle control a replacement with the same ID?
+
+No. Removal binds cancellation, callbacks and polling handles to the original lifecycle. It keeps the ID reserved until teardown/purge completes; later old handles cannot decide replacement approvals or send replacement turns. Dropping a handle does not purge its persisted home.
+
+## Why did a prompt or tool change not affect a resumed thread?
+
+A resumed session reuses recorded system messages and tool declarations. Start a new session for the changed prompt/tool catalog. Compaction preserves prior generations; it does not rewrite the old conversation. See [turns and sessions](concepts/turns-sessions.md).
+
+## Where is the complete builder knob list?
+
+[RuntimeBuilder setters](builder-setters.md) is generated from actual consuming public setters, with source signatures. Host/weight presets and non-setter methods are intentionally documented through [API reference](api-reference.md).
diff --git a/docs/gitbooks/en/developing/embed/guides/README.md b/docs/gitbooks/en/developing/embed/guides/README.md
new file mode 100644
index 0000000000..b94b18d716
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/README.md
@@ -0,0 +1,17 @@
+---
+description: "Build a chatbot, host multiple agents, serve profiles, or test an embedded runtime."
+icon: code
+---
+
+# Embedding guides
+
+Choose the guide that matches your host:
+
+- [CLI chatbot](cli-chatbot.md): create an agent and collect or stream its reply.
+- [Multiple agents](multi-agent.md): give agents independent prompts, access, and working folders.
+- [SaaS with multiple tenants](saas-multi-tenant.md): isolate user state through profiles.
+- [Deploy a server](deploy-server.md): call an embedded agent from your HTTP host.
+- [Lean and headless hosts](lean-headless.md): select runtime services and Cargo features separately.
+- [Test with a mock backend](mock-backend-testing.md): run the entire example suite offline.
+
+Start with [Embedding](../README.md) for the library boundary and quickstart. See [Integrations](../integrations/README.md) for providers, storage, MCP, and channels.
diff --git a/docs/gitbooks/en/developing/embed/guides/cli-chatbot.md b/docs/gitbooks/en/developing/embed/guides/cli-chatbot.md
new file mode 100644
index 0000000000..281c9588e5
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/cli-chatbot.md
@@ -0,0 +1,74 @@
+---
+description: "Collect a reply or consume progress events in a Rust command-line host."
+icon: code
+---
+
+# CLI chatbot
+
+Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example run_turn` from the repository root. It uses a loopback provider and temporary state. The [complete run_turn example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) includes imports, runtime construction, and offline setup.
+
+For incremental output, consume `agent.stream(...)` until `StreamEvent::Finished`. Progress includes text deltas; the final event carries the same outcome shape as `run`. Dropping the stream cancels the underlying turn.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+The [complete streaming example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) checks that text arrives before completion and that the offline streamed reply equals a collected reply. [Provider configuration](../integrations/openai-compatible.md) covers explicit live inference.
diff --git a/docs/gitbooks/en/developing/embed/guides/deploy-server.md b/docs/gitbooks/en/developing/embed/guides/deploy-server.md
new file mode 100644
index 0000000000..0e5d076d59
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/deploy-server.md
@@ -0,0 +1,58 @@
+---
+description: "Invoke agents from a host-owned HTTP service without adding RPC to Embed."
+icon: code
+---
+
+# Deploy a server
+
+Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/server.rs#server -->
+
+```rust
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let agent = runtime.agent(
+ AgentSpec::new("http-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let address = listener.local_addr()?;
+ // A real host should use its HTTP framework and authenticate requests.
+ // This single-request fixture keeps the library dependency direction intact.
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await?;
+ let mut request = vec![0; 4096];
+ let length = socket.read(&mut request).await?;
+ assert!(String::from_utf8_lossy(&request[..length]).starts_with("GET /hello "));
+ let reply = agent.run("Say hello").await?.reply;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ reply.len(),
+ reply
+ );
+ socket.write_all(response.as_bytes()).await?;
+ Ok::<_, anyhow::Error>(())
+ });
+ let reply = reqwest::get(format!("http://{address}/hello"))
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ assert!(!reply.is_empty());
+ if support::offline() {
+ assert_eq!(reply, "hello from the stub");
+ }
+ server.await??;
+ println!("host HTTP request reached the in-process agent");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example server`. The [complete server example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) checks the HTTP response against the deterministic provider reply.
+
+Use your HTTP framework for a deployed service. The example's one-request parser is deliberately small; a deployed host must handle authentication, request limits, cancellation, and shutdown. Select agents from authenticated host state. For multiple users, use [SaaS profiles](saas-multi-tenant.md).
+
+If your host needs OpenHuman's existing JSON-RPC server, depend on `openhuman-rpc`, the layer above Embed. Adding that dependency to Embed would reverse the crate chain. [Channels](../integrations/channels.md) provide another way to deliver messages to bound agents.
diff --git a/docs/gitbooks/en/developing/embed/guides/lean-headless.md b/docs/gitbooks/en/developing/embed/guides/lean-headless.md
new file mode 100644
index 0000000000..ddc9c00dd6
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/lean-headless.md
@@ -0,0 +1,33 @@
+---
+description: "Control runtime activity separately from compile-time Cargo features."
+icon: code
+---
+
+# Lean and headless hosts
+
+`RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/lean_headless.rs#lean_headless -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.weight, openhuman_embed::WeightClass::Lean);
+ assert!(info.services.is_empty());
+ let agent = runtime.agent(
+ AgentSpec::new("lean").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ assert!(!agent.run("Hello lean runtime").await?.reply.is_empty());
+ println!("lean runtime runs a turn without background services");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example lean_headless`. The [complete lean_headless example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) uses `ServiceSet::none()`, verifies the lean capability report, and completes an actual turn. For a host crate that needs fewer compiled features, disable default features on its Embed dependency and enable only the gates it needs. Verify enabled and disabled builds for that selection.
+
+A headless host also owns process setup: initialize its encryption key before storing credentials, choose its state directory, and keep the runtime alive until shutdown. The example support code uses a random fixture key and temporary credential directory; deployed hosts supply a durable key and durable workspace.
+
+[Storage drivers](../integrations/storage-drivers.md) covers persistent backends. The [complete capability_report example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) reports compiled features and active services without exposing provider keys or URLs.
diff --git a/docs/gitbooks/en/developing/embed/guides/mock-backend-testing.md b/docs/gitbooks/en/developing/embed/guides/mock-backend-testing.md
new file mode 100644
index 0000000000..7fb20fac2a
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/mock-backend-testing.md
@@ -0,0 +1,48 @@
+---
+description: "Run the embedding examples offline and verify behavior, not just compilation."
+icon: code
+---
+
+# Test with a mock backend
+
+Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+
+The shared support module uses loopback Wiremock servers for backend and inference requests. It disables unrelated online services and supplies isolated keyring state. Examples assert replies, transmitted model settings, tool results, and state isolation. MCP and Telegram use their real protocol shapes against local stubs; SQLite performs real local writes.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+The [complete host_tools example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) checks the advertised catalog, executes a host tool exactly once, and verifies that its result reaches the next model request. This catches a host adapter that advertises a tool but never runs it.
+
+Run a single gated example with `cargo run -p openhuman-embed --example mcp --features mcp`, or use the full runner to select all gates automatically. The individual examples default to offline mode. Only the [explicit live provider options](../integrations/openai-compatible.md) and [MongoDB live option](../integrations/storage-drivers.md) contact configured services.
diff --git a/docs/gitbooks/en/developing/embed/guides/multi-agent.md b/docs/gitbooks/en/developing/embed/guides/multi-agent.md
new file mode 100644
index 0000000000..08b48ff1c2
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/multi-agent.md
@@ -0,0 +1,85 @@
+---
+description: "Share one runtime while configuring independent agent prompts and working folders."
+icon: code
+---
+
+# Multiple agents
+
+A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+The [complete two_agents example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) sends real turns and checks the provider requests: the reviewer prompt does not contain the fixer prompt. It also checks different action directories and agent homes. Run `cargo run -p openhuman-embed --example two_agents`.
+
+Agents on one runtime share the runtime configuration and credential root. Separate action directories are useful for cooperating agents; use [SaaS profiles](saas-multi-tenant.md) for user isolation.
+
+Runtime defaults can supply a provider and model settings; individual agents override selected fields. The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) verifies both routes and their transmitted temperature and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
diff --git a/docs/gitbooks/en/developing/embed/guides/saas-multi-tenant.md b/docs/gitbooks/en/developing/embed/guides/saas-multi-tenant.md
new file mode 100644
index 0000000000..3c328b8e8f
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/guides/saas-multi-tenant.md
@@ -0,0 +1,50 @@
+---
+description: "Isolate user credentials, workspaces, and conversation history with ProfileRuntime."
+icon: code
+---
+
+# SaaS with multiple tenants
+
+Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+
+The complete example prepares a temporary SaaS root and initializes the keyring at `SaasConfig::operator_config().workspace_dir` before boot. SaaS validates the operator root, service token, permitted domains, and environment. A process-wide `OPENHUMAN_WORKSPACE` override is rejected. A SaaS core must be the only core in its process.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example profiles`. The [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) installs a loopback backend transport, chats as Alice and Bob, then checks distinct workspaces and same-thread history isolation. No live account or backend is contacted.
+
+Authenticate users in your host before selecting a profile. Keep the operator's configuration and gateway credential separate from user credentials. [Managed inference](../integrations/tinyhumans-managed.md) explains who provides the backend transport.
diff --git a/docs/gitbooks/en/developing/embed/installation.md b/docs/gitbooks/en/developing/embed/installation.md
new file mode 100644
index 0000000000..0d3a82145e
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/installation.md
@@ -0,0 +1,53 @@
+---
+description: "Add the Embed dependency, choose compile-time gates, and configure the host\u2019s runtime and state deliberately."
+---
+
+# Installation
+
+`openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+
+Run repository commands from its root. Build the facade with `cargo check -p openhuman-embed`; validate a narrow graph with `cargo check -p openhuman-embed --no-default-features`. Runtime weight presets and Cargo features control different things.
+
+## Compile-time gates versus runtime selection
+
+| Choice | What it controls |
+| --- | --- |
+| Cargo default features | Code and dependencies compiled into the artifact |
+| Named Embed feature such as `mcp` or `skills` | Public facade items and the forwarded core gate |
+| `RuntimeBuilder::modules`, domains, services and tool groups | Which compiled families a runtime exposes or starts |
+| Agent tool scope and access | Which subset one agent can use |
+
+Embed defaults forward the core defaults and enable the named Embed `channels` feature. Core defaults can include MCP and skills without enabling Embed's separately gated `McpServer`/agent MCP setter or skill setters. Add `--features mcp,skills` when using those public APIs. A runtime selection cannot enable a Cargo gate that was compiled out; inspect the [generated compiled matrix](capability-matrix.md) and the [source manifest](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/Cargo.toml).
+
+`RuntimeBuilder::lean()` narrows runtime activity; it does not reduce the dependency graph by itself. Pair it with `--no-default-features` for a narrow build and explicitly add the gates you need. Use `scripts/assert-shed.sh` or the repository dependency simulator before claiming a dependency reduction. See [lean/headless guide](guides/lean-headless.md).
+
+## Host runtime and credentials
+
+Build a Tokio multi-thread runtime with `enable_all`, a large worker stack and a bounded blocking pool. The verified examples use the [core runtime constants](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/core/runtime/mod.rs) through their repository support module: currently a 20 MiB worker stack and 64 blocking workers. Tokio's default 2 MiB worker stack is insufficient for nested agent turns. Follow the full example's host setup rather than adding an unconfigured `#[tokio::main]` to a large agent workload.
+
+Initialize the credential master key through `openhuman_embed::process::init_master_key` before persisting a runtime API key. Headless hosts can provide a protected 64-hex-character `OPENHUMAN_KEYRING_MASTER_KEY` or configured key file; keep this credential out of source and logs. The offline examples create disposable fixture keys, not production credentials.
+
+## State, configuration and inspection
+
+`Workspace::Ephemeral` is the library preset's default. `Workspace::Dir` moves both internal state and the credential root together; `workspace_dir` overrides internal state only, leaving the credential root at the resolved config path. Keep the action directory outside the internal workspace. Operator host presets use discovered configuration, while a supplied `Config` is resolved host configuration.
+
+[Runtime defaults](concepts/runtime-defaults.md) explains inheritance. The generated [builder setters](builder-setters.md) is the source-derived list of configuration knobs, and `RuntimeBuilder::describe` reports the pre-build plan without starting services.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The example checks the effective report after boot and proves that credentials, provider URL and workspace path are absent. The generated matrix uses the fixed default-feature report command; it describes that build, not every feature combination a host might compile.
diff --git a/docs/gitbooks/en/developing/embed/integrations/README.md b/docs/gitbooks/en/developing/embed/integrations/README.md
new file mode 100644
index 0000000000..4168ac50f5
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/README.md
@@ -0,0 +1,18 @@
+---
+description: "Choose provider, tool, storage, and channel adapters for your host."
+icon: code
+---
+
+# Embedding integrations
+
+An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+
+- [OpenAI-compatible providers and BYOK](openai-compatible.md)
+- [TinyHumans managed inference](tinyhumans-managed.md)
+- [Local models](local-models.md)
+- [MCP servers](mcp.md)
+- [Composio](composio.md)
+- [Storage drivers](storage-drivers.md)
+- [Channels](channels.md)
+
+[Guides](../guides/README.md) show how these pieces fit into a CLI, an HTTP server, or a SaaS host. Every linked executable example defaults to offline mode; a live endpoint requires an explicit choice.
diff --git a/docs/gitbooks/en/developing/embed/integrations/channels.md b/docs/gitbooks/en/developing/embed/integrations/channels.md
new file mode 100644
index 0000000000..f4fa9979e5
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/channels.md
@@ -0,0 +1,82 @@
+---
+description: "Bind an incoming channel to an agent and verify the delivered reply."
+icon: code
+---
+
+# Channels
+
+Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example telegram --features channels`. The [complete telegram example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) receives a stub update, runs the bound agent, and checks that the resulting reply was posted to the expected chat id.
+
+Keep channel credentials in host configuration and map messages to the intended identity and conversation. A provider route controls inference; it does not configure a channel or provide a hosted relay. [Managed backend setup](tinyhumans-managed.md) explains that separate transport responsibility.
+
+For a live Telegram host, supply the real Bot API configuration through your application's channel setup. This offline example deliberately has no live channel environment switch. [Deploy a server](../guides/deploy-server.md) covers a host-owned HTTP alternative.
diff --git a/docs/gitbooks/en/developing/embed/integrations/composio.md b/docs/gitbooks/en/developing/embed/integrations/composio.md
new file mode 100644
index 0000000000..694e719733
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/composio.md
@@ -0,0 +1,14 @@
+---
+description: "Pin connector credentials per agent while the host supplies backend transport."
+icon: code
+---
+
+# Composio
+
+Composio calls use the host backend transport. Install that transport before booting a managed runtime; see [TinyHumans managed inference](tinyhumans-managed.md). An explicit inference provider route supplies model inference, not the connector transport.
+
+Use `AgentSpec::composio(ComposioHostCredential)` to pin a connector credential to an agent. This keeps the credential selection on the host side instead of asking the model to choose another user's credential. Configure the agent's tool scope and access separately. The connector tools still pass through the host's execution policy.
+
+The repository's [Composio agent integration test](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/tests/composio_agents.rs) verifies two agents using their own pinned credentials against a loopback backend. It checks the outgoing authentication and action results rather than contacting Composio. Run the Embed integration suite through the repository's cancellation-aware runner when changing this adapter.
+
+Account login, linking, and credential acquisition belong to your connected host and connector layer. Keep secrets out of prompts and capability reports. For multiple users, use [SaaS profiles](../guides/saas-multi-tenant.md); independent action directories on a shared library runtime do not establish tenant isolation.
diff --git a/docs/gitbooks/en/developing/embed/integrations/local-models.md b/docs/gitbooks/en/developing/embed/integrations/local-models.md
new file mode 100644
index 0000000000..194145321d
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/local-models.md
@@ -0,0 +1,69 @@
+---
+description: "Use a local OpenAI-compatible server or inject a native ChatModel implementation."
+icon: code
+---
+
+# Local and custom models
+
+For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The [OpenAI-compatible example controls](openai-compatible.md) can point a live example at that local server.
+
+A native provider implements `openhuman_embed::providers::ChatModel<()>`. `Provider::custom_with_fallback` tries fallback models when the primary fails before output; validation failures and failures after streamed content do not switch providers. A named role pin can select another native model for a workload.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example custom_provider`. The [complete custom_provider example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) includes the concrete model implementation. It checks one primary failure, one fallback invocation, and a coding role that bypasses the primary chain. These native models are deterministic and make no inference network requests.
+
+For live local inference, configure model availability and authentication in your server. For runtime selection and service controls, see [Lean and headless hosts](../guides/lean-headless.md).
diff --git a/docs/gitbooks/en/developing/embed/integrations/mcp.md b/docs/gitbooks/en/developing/embed/integrations/mcp.md
new file mode 100644
index 0000000000..0688ce318e
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/mcp.md
@@ -0,0 +1,63 @@
+---
+description: "Connect a declared MCP server and verify remote discovery and execution."
+icon: code
+---
+
+# MCP servers
+
+Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example mcp --features mcp`. The [complete mcp example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) performs an actual MCP initialize handshake, lists remote tools, calls the forecast tool, and verifies the returned `sunny` result in the next model request.
+
+The immediately available `mcp_list_tools` and `mcp_call_tool` bridge tools work with a cold configured server. Individual per-server tools use a cached catalog and are deferred by default. On a cold first turn, that catalog may still be warming in the background; do not assume `tool_search` already contains the per-server tool name. Use the bridge to discover and call it, and copy returned tool names and arguments.
+
+MCP transport does not bypass the host's execution policy. Configure agent access and approvals for actions exposed by the server. [Mock testing](../guides/mock-backend-testing.md) keeps this protocol path local during development.
diff --git a/docs/gitbooks/en/developing/embed/integrations/openai-compatible.md b/docs/gitbooks/en/developing/embed/integrations/openai-compatible.md
new file mode 100644
index 0000000000..ac5b643820
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/openai-compatible.md
@@ -0,0 +1,53 @@
+---
+description: "Route inference to an explicit endpoint and bearer without changing shared host configuration."
+icon: code
+---
+
+# OpenAI-compatible providers and BYOK
+
+Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+
+The runtime and agent routes in this example answer independently. Assertions inspect the actual request bodies, including model, temperature, and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) includes the loopback endpoint setup. Run `cargo run -p openhuman-embed --example defaults_overrides` for its offline assertions.
+
+Examples using `support::example_provider` switch to live inference only with `OPENHUMAN_EXAMPLE_LIVE=1` and all three of `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY`, and `OPENHUMAN_EXAMPLE_MODEL`. These settings are example controls, not replacements for your application's credential configuration. Keep provider keys in your host's secret configuration.
+
+For a non-HTTP implementation, [local and custom models](local-models.md) covers `Provider::custom`, native fallback, and role pins. [Managed inference](tinyhumans-managed.md) uses a different backend transport boundary.
diff --git a/docs/gitbooks/en/developing/embed/integrations/storage-drivers.md b/docs/gitbooks/en/developing/embed/integrations/storage-drivers.md
new file mode 100644
index 0000000000..f3449560a0
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/storage-drivers.md
@@ -0,0 +1,84 @@
+---
+description: "Configure SQLite or MongoDB through Embed and inspect the selected backend."
+icon: code
+---
+
+# Storage drivers
+
+Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+
+The SQLite example sets `config.storage.url` to a `sqlite:` URL under a temporary directory, then obtains `Runtime::storage`. It creates a scoped collection, writes a document, reads it back, and deletes it. A configured backend also supplies the default driver-backed session stores; an explicit host session-store adapter takes precedence.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_sqlite -->
+
+```rust
+ let mut config = support::offline_config();
+ config.storage.url = Some(format!(
+ "sqlite:{}",
+ directory.path().join("storage").display()
+ ));
+ let runtime = Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .config(config)
+ .backend_url(backend.uri())
+ .build()
+ .await?;
+ let storage = runtime.storage().expect("configured SQLite backend");
+ assert_eq!(storage.driver(), "sqlite");
+ let scoped = storage.for_scope(&Scope::local())?;
+ let documents = scoped.documents();
+ documents
+ .ensure_collection(&CollectionSpec::new("settings"))
+ .await?;
+ let value = serde_json::json!({"theme":"dark"});
+ documents
+ .put("settings", "demo", value.clone(), Precondition::Absent)
+ .await?;
+ assert_eq!(
+ documents
+ .get("settings", "demo")
+ .await?
+ .expect("stored value")
+ .doc,
+ value
+ );
+ assert!(
+ documents
+ .delete("settings", "demo", Precondition::None)
+ .await?
+ );
+ assert!(documents.get("settings", "demo").await?.is_none());
+ assert_eq!(
+ runtime.capabilities().storage.driver.as_deref(),
+ Some("sqlite")
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example storage --features storage-sqlite`. This performs real local SQLite writes. The [complete storage example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) also describes a MongoDB URL without connecting.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_mongodb -->
+
+```rust
+ // Enable `storage-mongodb` for a deployment that builds this config.
+ // Describing it does not contact MongoDB and never exposes credentials.
+ let mut mongo = support::offline_config();
+ mongo.storage.url = Some("mongodb://app:[email protected]:27017/openhuman".into());
+ let builder = RuntimeBuilder::library().config(mongo);
+ let description = builder.describe();
+ assert_eq!(description.storage.driver.as_deref(), Some("mongodb"));
+ assert!(description.storage.configured);
+ assert!(!serde_json::to_string(&description)?.contains("example-password"));
+ // An explicit environment variable is the only path to a live database.
+ if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_MONGODB_URL") {
+ let live = RuntimeBuilder::library().storage(url).build().await?;
+ assert_eq!(live.storage().expect("MongoDB backend").driver(), "mongodb");
+ }
+```
+
+<!-- END EMBED -->
+
+`RuntimeBuilder::describe()` reports the driver and whether storage is configured, omitting URL credentials. Describing a MongoDB URL does not prove the server is reachable or that the MongoDB driver was compiled. Building a runtime with that URL requires `storage-mongodb` and a reachable server.
+
+The only live database path in this example is `OPENHUMAN_EXAMPLE_MONGODB_URL`. To exercise it deliberately, enable both `storage-sqlite` and `storage-mongodb` and supply your own MongoDB URL. The offline CI runner clears this setting. A deployed host supplies its persistent URL and credentials through its own configuration.
diff --git a/docs/gitbooks/en/developing/embed/integrations/tinyhumans-managed.md b/docs/gitbooks/en/developing/embed/integrations/tinyhumans-managed.md
new file mode 100644
index 0000000000..ef5118247f
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/integrations/tinyhumans-managed.md
@@ -0,0 +1,52 @@
+---
+description: "Install the host backend transport before using managed inference and hosted services."
+icon: code
+---
+
+# TinyHumans managed inference
+
+Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+
+Supply a library backend key with `RuntimeBuilder::api_key` and initialize the process master key before credential storage. Library mode does not perform user login. Managed inference uses the key as a bearer; backend REST calls resolve it through the backend credential seam. Without an installed transport, hosted backend calls return a typed backend-unavailable error.
+
+The SaaS example uses a deterministic implementation of that transport boundary and installs separate profile credentials. It verifies managed turns without a live service.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+See the [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) and its shared support transport for the full offline setup. For a deployed SDK-backed host, follow the connected layer's setup instead of copying the loopback transport.
+
+Use [OpenAI-compatible routing](openai-compatible.md) when your host wants to send inference directly to a BYOK endpoint. That explicit provider route does not supply hosted backend services.
diff --git a/docs/gitbooks/en/developing/embed/quickstart.md b/docs/gitbooks/en/developing/embed/quickstart.md
new file mode 100644
index 0000000000..6b048a8ed7
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/quickstart.md
@@ -0,0 +1,53 @@
+---
+description: "Run one agent against a local fixture, then choose a provider and working directory for your host."
+---
+
+# Quickstart
+
+Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+
+## Create an agent and send a turn
+
+The full example constructs the runtime before this excerpt. `AgentSpec` names the agent and gives it a bare prompt with `HostOnly` tools. With no host tools attached, this is a text-only agent: it cannot inherit the operator's built-in tool catalog.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs), including runtime construction, imports and fixture setup.
+
+`Agent::run` returns a `TurnOutcome` containing the reply and session identity. Use `Agent::turn(...).session(...)` for subsequent messages in the same conversation, or [stream progress](concepts/turns-sessions.md) when your interface should display deltas as they arrive.
+
+## Connect your own host
+
+Replace the fixture provider with an explicit OpenAI-compatible `Provider` or a native custom model. Give tools an explicit action directory, decide whether autonomy enforcement should be enabled, and keep runtime state separate from acting-tool folders. Configure the Tokio worker stack and credential master key as described in [installation](installation.md).
+
+The example's live path requires `OPENHUMAN_EXAMPLE_LIVE=1` plus `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY` and `OPENHUMAN_EXAMPLE_MODEL`. Choosing a live path is an explicit decision; setting credentials alone does not turn the default example into a live call.
+
+For managed TinyHumans inference, use the [TinyHumans host integration](integrations/tinyhumans-managed.md), which installs the backend transport. Embed by itself does not install one.
+
+## Extend the example
+
+- Give a reviewer and a fixer separate tools and folders: [multiple agents](guides/multi-agent.md).
+- Serve a request through your own HTTP transport: [deploy a server](guides/deploy-server.md).
+- Attach application functions: [tools](concepts/tools.md).
+- Isolate authenticated customers: [SaaS guide](guides/saas-multi-tenant.md).
+- Keep the setup offline and deterministic: [mock-backend testing](guides/mock-backend-testing.md).
+
+Drop listeners and agent handles before shutting down the runtime. For early removal, await `remove_agent` so retained handles stop admitting turns and the old ID is released only after cleanup.
diff --git a/docs/gitbooks/en/developing/embed/troubleshooting.md b/docs/gitbooks/en/developing/embed/troubleshooting.md
new file mode 100644
index 0000000000..244a0b68dd
--- /dev/null
+++ b/docs/gitbooks/en/developing/embed/troubleshooting.md
@@ -0,0 +1,46 @@
+---
+description: "Diagnose missing features, blocked turns, credentials, state paths and lifecycle failures."
+---
+
+# Embedding troubleshooting
+
+Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+
+| Symptom | Check and next step |
+| --- | --- |
+| `RuntimeError::AlreadyRunning` | Reuse the process runtime; drop old listeners, agents and runtime before restarting. Profiles require their own process mode. |
+| Method or type not found at compile time | Check named Embed Cargo gates, especially `mcp`/`skills`. Core compiled flags alone do not activate those facade exports. |
+| `CoreError::Unavailable` | Inspect effective domains/modules as well as compiled features. Runtime selections can narrow a compiled family. |
+| `BACKEND_UNAVAILABLE` | Install the host backend transport, normally through `openhuman-tinyhumans`, before backend-touching calls. |
+| Credential master-key failure | Initialize process master-key state before persisting a runtime API key; check headless key/file setup without printing its value. |
+| Invalid or insecure provider route | Supply a nonblank endpoint/key and use HTTPS for remote bearer routes. Loopback fixtures are separate from remote endpoints. |
+| Stack overflow on a nested turn | Use the documented Tokio worker stack; the default 2 MiB stack is insufficient. Follow the runnable example support setup. |
+| A write is waiting indefinitely | Poll the same agent's approvals or retain an active callback subscription. Check origin, enabled autonomy and trusted action roots. |
+| Streaming appears stalled | Drain the bounded progress stream while work runs; inspect the final result. Dropping it cancels forwarding and the turn cooperatively. |
+| A skill is absent | Copy a real bundle into the agent's skill directory; symlinked bundles are rejected. New instructions need a new session. |
+| Agent registration returns `DuplicateId` | Another instance or teardown still reserves the ID. Wait for removal/last-handle cleanup to finish. |
+| Retained handle returns `AgentRemoved` | That instance was removed; obtain a newly registered handle rather than reusing the old one. |
+| `Decode` error on a typed facade | Treat it as an API/result-shape mismatch; preserve safe metadata and report a regression. |
+
+## Inspect without exposing credentials
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+Before boot, `RuntimeBuilder::describe` can report a provisional plan; check `configuration_resolved`. After boot, `Runtime::capabilities` describes resolved defaults, storage source/driver and selection without its URL/key. Runtime events provide content-free lifecycle metadata, while explicit turn progress can contain text and should be handled accordingly.
+
+Reproduce behavior with [offline testing](guides/mock-backend-testing.md) before using a live provider. The [error concept](concepts/errors.md) explains structured kinds and expected-user-state errors.
diff --git a/docs/gitbooks/en/developing/embedding.md b/docs/gitbooks/en/developing/embedding.md
index f34168b691..91e16d052c 100644
--- a/docs/gitbooks/en/developing/embedding.md
+++ b/docs/gitbooks/en/developing/embedding.md
@@ -4,532 +4,10 @@ description: >-
with any number of separately configured Agents on it.
icon: code
---
-
# Embedding OpenHuman
-`openhuman-embed` is a typed Rust library that runs the OpenHuman core inside your own product. It is the same core that ships in the desktop app and the CLI, without the Tauri shell and the RPC server. You call business rules, agent turns, memory, tools and sandboxing directly from your own binary.
-
-## Adding the dependency
-
-Use the default contributor feature set:
-
-```toml
-[dependencies]
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed" }
-```
-
-Or select a narrower build:
-
-```toml
-[dependencies]
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed", default-features = false, features = ["inference", "mcp"] }
-```
-
-Every feature on this crate forwards to the same-named feature on
-`openhuman-core`: `default`, `http-server`, `inference`, `documents`,
-`hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,
-`flows`, `skills`, `mcp`, `crash-reporting`, `channels`,
-`whatsapp-web`, `file-logging`, `scheduler-gate` (eighteen entries including
-`default`). Two of them also gate
-items on this crate's own API: `mcp` gates `HttpHeader`,
-`McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`;
-`skills` gates `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.
-
-Set your product's identity once at startup, before building any client:
-
-```rust
-use openhuman_embed::{set_product_identity, ProductIdentity};
-
-if let Some(identity) = ProductIdentity::new("opencompany") {
- set_product_identity(identity);
-}
-```
-
-## Two steps: a Runtime, then any number of Agents
-
-The library API has two levels. First you build one `Runtime` for the process. It holds features, background services, the backend URL and the TinyHumans API key. Then you add any number of separately configured agents to it. Each agent has its own provider, access tier, working directory, MCP servers and skills.
-
-```rust,no_run
-use openhuman_embed::{Access, AgentSpec, McpServer, Provider, Runtime, Workspace};
-
-# async fn demo() -> Result<(), Box<dyn std::error::Error>> {
-let runtime = Runtime::builder()
- .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 own 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?;
-println!("{}", fix.reply);
-
-// Continue a conversation with the same agent.
-let again = fixer.turn("Now run the tests.").session(&fix.session_id).send().await?;
-println!("{}", again.reply);
-# Ok(())
-# }
-```
-
-An agent owns:
-
-- its provider and model
-- its access tier and turn origin
-- its `action_dir`
-- its MCP servers
-- its skills root (`<workspace>/agents/<id>/skills/`)
-- its system prompt
-- its tool scope and sandbox mode
-- a narrowed domain set or tool-group list
-
-Every turn runs under that agent's own context. Config, domain gating, tool-group filtering and skill discovery all read that agent's settings and never another agent's. Transcripts are keyed by agent id, and a turn resumes only its own thread.
-
-The runtime owns the workspace and credential store, the event bus, the keyring, background services, the registered domain set and the API key. Agents can only narrow the domain set, so enable `mcp` or `skills` at runtime build time if any agent needs them.
-
-Layout under a runtime-owned root:
-
-```text
-<root>/config.toml, auth-profiles.json, core.token
-<root>/workspace/session_db/, session_raw/<session_key>.<agent>[.g<n>].jsonl, agents/<agent>/skills/
-<root>/agents/<agent>/action/ default action_dir
-```
-
-## AgentSpec
-
-`AgentSpec::new(id)` starts from the built-in orchestrator's definition
-(prompt, tools, delegation) applied to a fresh id, except every registered
-tool is visible by default (`ToolScopeSpec::Wildcard`) rather than the
-desktop's own narrower set. Chain builder methods to override:
-
-- `.system_prompt(text)` and `.definition(spec)` for the prompt, tool scope,
- disallowed tools, sandbox mode, iteration cap, temperature, display name
- and delegation blurb (`AgentDefinitionSpec`).
-- `.provider(Provider)` and `.model(id)` for which model answers and where.
-- `.access(Access)` for what the agent may do.
-- `.tool_groups(ToolGroups)` and `.domains(DomainSet)` to narrow further,
- never wider than the runtime's own set.
-- `.mcp(McpServer)` (repeatable) for MCP servers only this agent can call.
-- `.skills_dir(path)` to copy skill bundles into this agent's own root.
-- `.include_user_skills(bool)` to also let the agent see the operator's
- `~/.openhuman/skills` (off by default).
-- `.action_dir(path)` for the agent's read and write root.
-- `.trust(path, access)` to grant a directory outside `action_dir`.
-- `.tools(factory)` to hand the agent real in-process tools built fresh per
- turn, rather than routing host callbacks through an MCP server.
-- `.config(f)` as an escape hatch for config fields the spec does not model.
-
-Agent ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`; avoid the built-in ids
-(`orchestrator`, `summarizer` and so on), which the runtime-wide delegation
-catalog resolves to the shipped definitions.
-
-## Access tiers
-
-`Access` sets two things together on purpose: the autonomy tier that drives
-the security policy, and the turn origin the approval gate checks. Setting
-only the tier produces an agent whose shell, edit and exec tools all
-silently refuse, which reads as a weak model rather than a missing scope.
-
-- `Access::readonly()`: observe only, no writes, no shell, no network side
- effects. Safe default for an untrusted prompt.
-- `Access::supervised()`: act, but park risky operations for a human
- decision. Unlike the desktop default, this turns the autonomy policy on
- for that agent (`Access` sets the policy flag as well as the tier), so the
- approval gate really is live and an unattended harness stalls here until an
- approval answers or the ten-minute TTL denies it. The user-facing default is
- the opposite: `[autonomy] enabled = false`, where the gate is inert. See
- [Approval gate](../features/approval-gate.md).
-- `Access::full()`: act autonomously, no approval pauses. Grants real shell
- and file access under `action_dir`; point it at a directory you are
- willing to have changed. Hard blocks still apply regardless of tier:
- credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and the workspace's own
- internal state stay off limits.
-
-`.trust(path, access)` grants a directory outside the action root, and
-`.allow_tool_install(bool)` opts into OS package installation, off in every
-preset including `full()` because it reaches outside the action directory
-that otherwise bounds the blast radius.
-
-## Provider: BYOK or managed
-
-`Provider::inherit()` uses whatever inference the runtime or the machine is
-already configured with: the account's managed backend, a local Ollama or
-LM Studio, or a configured BYOK provider. `Provider::openai_compatible(url,
-key)` points a turn at a specific OpenAI-compatible endpoint and bearer;
-`/chat/completions` is appended to `url`, so pass the API root. `.model(id)`
-pins the model id on either; it is advisory, because a model that no configured
-provider serves falls back instead of failing.
-
-An agent that names its own `Provider` never touches the runtime's API key.
-One that names none inherits the runtime's default: managed inference on
-the API key when one was supplied, or the machine's own configuration
-otherwise.
-
-## Workspace
-
-`Workspace::Ephemeral` (the default) is a throwaway directory removed when
-the harness or runtime drops; nothing here touches a real install, and
-sessions do not survive the process. `Workspace::dir(path)` is a
-caller-owned directory that persists across runs. `Workspace::Inherit`
-reuses the machine's configured OpenHuman workspace, the same one the
-desktop app and CLI use, resolved the usual way
-(`OPENHUMAN_WORKSPACE`, `active_user.toml`, `~/.openhuman/...`); an inherited
-workspace is the operator's, so the harness will not copy skills into it.
-
-`Workspace::stateless()` keeps nothing durable on disk: every agent's
-transcripts, turn journal, run status, goals and todos go through the
-runtime's session store (`RuntimeBuilder::session_store`, required), a
-`SessionStoreProvider` the host implements over its own database and scopes
-by agent id. It is the shape for a cloud host serving many users from one
-process; see the embed crate's README, "Conversations in a host store".
-
-## Tool scopes and sandbox modes
-
-`AgentDefinitionSpec::tools(ToolScopeSpec::Wildcard)` exposes every
-registered tool (the default); `ToolScopeSpec::Named(vec![...])` restricts
-an agent to exactly those tool names, dropping unknown ones at build time.
-`.disallow_tools([...])` hides specific tools even when the scope would
-include them.
-
-`SandboxModeSpec` confines an agent's shell and file tools:
-
-- `SandboxModeSpec::None` (default): only the access tier and path policy
- apply.
-- `SandboxModeSpec::ReadOnly`: write and execute tools are filtered out
- entirely.
-- `SandboxModeSpec::Sandboxed`: commands run under the platform jail or
- Docker backend.
-
-## MCP servers
-
-`McpServer::stdio(name, command, args)` launches a local subprocess
-speaking newline-delimited JSON-RPC; `McpServer::http(name, endpoint)`
-reaches a remote server over Streamable HTTP. Both support `.env(...)` or `.auth(McpAuthConfig)`. `.allow_tools([...])` and `.deny_tools([...])` narrow which remote tools an agent sees, which is worth doing for a large server because every exposed tool costs prompt budget. `.timeout_secs(n)` and `.description(text)` are also available. Servers declared through `AgentSpec::mcp` are private
-to that agent; other agents on the same runtime do not see them. Servers are fixed at build time. You cannot add one to a running harness.
-
-## Skills
-
-`AgentSpec::skills_dir(dir)` copies skill bundles into
-`<workspace>/agents/<id>/skills/`, visible only to that agent. Bundles are
-copied rather than symlinked because skill discovery rejects symlinked
-bundles. `.include_user_skills(true)` additionally lets the agent discover
-skills the operator installed under `~/.openhuman/skills`; the default
-hides them, because an embedded agent should see what its host installed, not
-what the machine's user did.
-
-## Multi-turn sessions and progress streaming
-
-`agent.turn(message)` returns a builder. `.session(id)` continues an
-existing conversation; without it a fresh session id is minted and returned
-on `TurnOutcome::session_id`. `.model(id)` and `.temperature(t)` override
-those settings for one turn. `.cwd(dir)` roots that turn's filesystem and
-shell tools somewhere other than the agent's configured `action_dir`.
-`.route(Route)` sends one turn to a specific endpoint instead of the
-account's configured route. `.origin(AgentTurnOrigin)` states the calling
-authority explicitly, for a turn that is not a human at a terminal, such as
-a workflow node or a scheduled job.
-
-`.on_progress(sender)` streams tool calls, deltas and turn boundaries as
-they happen. The core awaits every send, so the channel is real
-backpressure: a receiver that stops draining stalls the turn.
-
-```rust,no_run
-# use openhuman_embed::Agent;
-# async fn go(agent: &Agent) -> anyhow::Result<()> {
-let (tx, mut rx) = tokio::sync::mpsc::channel(256);
-let printer = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- eprintln!("[progress] {progress:?}");
- }
-});
-let outcome = agent.turn("go").on_progress(tx).send().await?;
-let _ = tokio::time::timeout(std::time::Duration::from_secs(30), printer).await;
-println!("{}", outcome.reply);
-# Ok(()) }
-```
-
-`.seed(history)` replaces a session's history for one turn with your own `(role, content)` rows instead of reading the transcript. Only a runtime-owned `Agent` can honor it. It silently discards whatever the session held, so pair it with a session id that no other turn shares. `.meter(f)`
-reports what a turn spent, including a turn that ran and then failed.
-
-## Scheduling
-
-OpenHuman's own cron can drive scheduled turns of a runtime's agents, with
-their host tools, and run host code on a schedule. `runtime.cron()` is a typed
-facade over the runtime's job store; jobs are named and `upsert` is idempotent
-by that name, so a host can declare its schedule on every start:
-
-```rust,no_run
-# async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), Box<dyn std::error::Error>> {
-use openhuman_embed::{JobSchedule, JobSpec};
-
-let cron = runtime.cron();
-// One turn of the runtime agent `teeny` every morning.
-cron.upsert(
- JobSpec::agent("morning", "teeny", "Plan the day.", JobSchedule::Cron {
- expr: "0 8 * * *".into(),
- tz: Some("Europe/Berlin".into()),
- })
- .retries(0) // exactly one attempt: the turn has side effects
- .single_flight(true) // skip (and record) a slot that comes due mid-run
-)?;
-// Host code on a schedule; its result is the run's recorded result.
-runtime.on_system_job("digest", |_ctx| async { Ok(()) })?;
-cron.upsert(JobSpec::system("digest", "digest", JobSchedule::Every { ms: 15 * 60_000 }))?;
-
-let run = cron.run_now("morning").await?; // same path as a scheduled run
-println!("{} {}", run.success, run.output);
-# Ok(()) }
-```
-
-- **Jobs fire only while the scheduler runs.** Build the runtime with
- `.services(ServiceSet { cron: true, ..ServiceSet::none() })`; `build()` then
- starts the selected services and dropping the runtime (and its agents) stops
- them. `Runtime::start_services` / `stop_services` give explicit control.
- Without the scheduler, jobs are stored and `run_now` still works.
-- **An agent job runs as the agent.** When `agent_id` names an agent alive on
- the runtime, the turn uses its definition and system prompt, its
- `AgentSpec::tools` and attached tools, its provider and its own context
- (`agent::host_agents` resolves it for the core's cron and workflow drivers).
- Any other id resolves through the core's agent registries. The turn's origin
- is `TrustedAutomation { Cron }`, not the agent's own access origin. Agent jobs
- may not run more often than every five minutes.
-- **A system job runs the host's handler.** `on_system_job(name, handler)`
- registers an async `Fn(SystemJobContext) -> Result<(), String>`; when the job
- comes due the scheduler still publishes `CronSystemJobDue` on the bus, then
- awaits the handler and records `ok` or `error` with its message.
-- **Retries and overlap.** A failed run is retried `retries` times with
- backoff; unset keeps `reliability.scheduler_retries` (2), and `0` is one
- attempt. Two runs of one job never overlap: each due job is dispatched on
- its own task, so a long job no longer holds up the others, `run_now` is
- refused while a run is active, and a slot that comes due mid-run is skipped.
- With `single_flight` that skip is recorded as a `skipped` run.
-- `cron.list()`, `cron.remove(name)` and `cron.runs(name, limit)` cover the
- rest. Shell jobs and workflow schedule triggers are not managed here.
-
-## Channels
-
-A runtime agent can answer a messaging channel. `runtime.channels()` starts a
-channel listener bound to one agent, so every message on it is a turn of that
-agent rather than of the orchestrator:
-
-```rust,no_run
-# async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), Box<dyn std::error::Error>> {
-use openhuman_embed::{AgentSpec, TelegramChannelSpec};
-
-let agent = runtime.agent(AgentSpec::new("teeny-chat").system_prompt("You are Teeny."))?;
-let telegram = runtime.channels().telegram(
- TelegramChannelSpec::new("123456:bot-token", "teeny-chat")
- .allow_everyone() // or .allowed_users(["alice", "4242"])
- .mention_only(true), // in groups, answer only when mentioned
-)?;
-// The bot answers until the listener is stopped or dropped.
-# let _ = (agent, telegram);
-# Ok(()) }
-```
-
-- **The agent answers as itself.** Each message runs with the agent's system
- prompt, tool scope, `AgentSpec::tools` belt and attachments, provider and
- context. History is per chat, kept by the channel the same way it is for the
- orchestrator. Typing indicators, streamed drafts and the reply work as for
- any channel. Call `telegram()` from inside the tokio runtime; it spawns the
- listener there.
-- **Bind to an agent that exists.** `telegram()` refuses an id with no live
- agent on the runtime (`ChannelError::UnknownAgent`). If the agent is dropped
- while the bot is running, each message gets a short "not available" reply and
- an error is logged. The message is never handed to the orchestrator.
-- **Turns are untrusted and read-only.** Anyone who can message the bot writes
- the turn's text, so it runs as `AgentTurnOrigin::ExternalChannel` and is
- capped at `PermissionLevel::ReadOnly`. A tool that writes, executes or has an
- external effect is withheld from the turn's tool list or refused at once with
- a tool error. It never waits on an approval, because the only person who
- could answer one is the sender. Give a public agent read-only host tools, and
- do anything with side effects outside the chat turn (a cron job, host code).
-- **Under the hood** this is the core's channel runtime for that one bot,
- started under the runtime's context with
- `agent.channel_agents = { telegram = "<agent id>" }`. A core started from a
- config file can bind a channel the same way: any channel name works as the
- key, and the agent is resolved through `agent::host_agents`.
-
-## Harness: the one-agent shorthand
-
-`Harness` is a `Runtime` plus exactly one agent, built from one set of
-inputs, for a host that only ever needs one:
-
-```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(())
-# }
-```
-
-`harness.runtime()` and `harness.agent()` hand out the underlying `Runtime`
-and `Agent`, so a host that outgrows one agent adds more on the same
-runtime rather than rebuilding.
-
-## Connecting to the hosted backend
-
-`openhuman-embed` alone installs no backend transport: agents, memory,
-skills, tools and RPC all run, and every hosted-backend surface (billing,
-integration tools, channel relay, cloud voice) answers with a typed
-`BACKEND_UNAVAILABLE:` error. `openhuman-tinyhumans::RuntimeBuilder` mirrors
-`openhuman_embed::RuntimeBuilder` method for method and installs the
-SDK-backed transport on `build()`:
-
-```rust
-use openhuman_tinyhumans::{embed::Workspace, RuntimeBuilder};
-
-let runtime = RuntimeBuilder::new()
- .workspace(Workspace::Ephemeral)
- .api_key("th_...")
- .build()
- .await?;
-```
-
-Hosts that boot the core themselves rather than through either builder (the
-desktop shell, the TUI, the CLI, test fixtures) call `install` once before
-the first backend-touching dispatch:
-
-```rust
-openhuman_tinyhumans::install(openhuman_tinyhumans::InstallOptions::default())?;
-```
-
-That call also registers the seven hosted RPC proxy domains (billing, team,
-referral, announcements, webhooks, channel linking and backend-brokered OAuth)
-into the core's controller registry. See
-[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans
-API key unlocks once it is installed this way.
-
-## Library mode has no user login
-
-`RuntimeBuilder::api_key` installs a TinyHumans API key into the runtime's
-credential store before the core boots. Managed inference then sends it as
-`Authorization: Bearer <key>` to the TinyHumans endpoint, 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, no session JWT, nothing to expire. An
-agent that names its own `Provider` never touches the key at all.
-
-## One runtime per process
-
-The keyring master key, the RPC bearer, the global event bus and the
-process's domain subscribers are process-scoped. A second runtime would
-silently share them while believing it had a separate workspace.
-`RuntimeBuilder::build` returns `RuntimeError::AlreadyRunning` instead.
-Within one process, add agents, not runtimes.
-
-Build the tokio runtime yourself instead of using `#[tokio::main]`. A turn
-is a large async state machine, and a nested sub-agent overflows
-tokio's default 2 MiB worker stack:
-
-```rust,no_run
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
-
-let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()
- .expect("tokio runtime");
-```
-
-## A narrow build, measured
-
-[`docs/library-minimal-recipe.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-minimal-recipe.md) measures a headless recipe aimed at
-100 to 1,000 live agents on a 2 GB RAM / 2 vCPU box:
-
-```bash
-cargo build --release \
- -p openhuman-embed \
- --no-default-features --features "skills,flows"
-```
-
-Stripped binary size: 51.0 MiB with no optional gates at all, about 60.4 MiB
-with `skills,flows` enabled (the recipe above), against 115.9 MiB unstripped
-with every gate on. See [Performance](performance.md) for how that build
-size relates to per-agent memory and cold-start time when many agents share
-one process.
-
-## Examples to run
-
-Against any OpenAI-compatible endpoint:
-
-```bash
-OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-OPENHUMAN_EXAMPLE_API_KEY=sk-... \
-OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
- cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"
-```
-
-Or against the machine's own configured inference, in its real workspace:
-
-```bash
-OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."
-```
-
-Two agents on one runtime, BYOK or managed:
-
-```bash
-OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-OPENHUMAN_EXAMPLE_API_KEY=sk-... \
-OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-
-OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_... \
- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-```
-
-`OPENHUMAN_EXAMPLE_BACKEND_URL` points non-inference backend calls
-somewhere specific, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill
-bundles. The repository-root `examples/embed_headless.rs` and
-`examples/embed_kernel.rs` drive `CoreBuilder` from `openhuman-core`
-directly, without this crate; run them with `cargo run --example
-embed_headless`.
-
-Tests worth reading alongside the examples, all under
-`crates/openhuman-embed/tests/`: `harness_embed.rs` proves
-`Harness` runs a real turn against a mocked provider with nothing else
-bound; `runtime_agents.rs` runs three agents with different
-providers, access tiers, skills, MCP servers and working directories on one
-runtime; `public_api.rs` pins the host-facing embedding contract at
-compile time. Run them with:
+The embedding documentation now lives in the [Embedding section](embed/README.md).
-```bash
-cargo test -p openhuman-embed --features inference,mcp,skills
-```
+Start with [installation](embed/installation.md) and the [quickstart](embed/quickstart.md), then use the [concepts](embed/concepts/README.md), [guides](embed/guides/README.md), [integrations](embed/integrations/README.md) and generated [cookbook](embed/cookbook.md).
-See also: [Jev](jev.md) for the decision model an embedded agent's tool
-search can use, [Pluggable engines](engines.md) for the inference, memory
-and search backends an agent chooses by config, and
-[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans
-API key unlocks in library mode.
+The public library uses one Runtime per process with independently configured Agents. For isolated authenticated users, read [profiles and SaaS](embed/concepts/profiles-saas.md).
diff --git a/docs/gitbooks/en/developing/saas-profiles.md b/docs/gitbooks/en/developing/saas-profiles.md
new file mode 100644
index 0000000000..02d6c66014
--- /dev/null
+++ b/docs/gitbooks/en/developing/saas-profiles.md
@@ -0,0 +1,245 @@
+---
+description: >-
+ Running OpenHuman as a multi-user service: one profile per user, behind a
+ trusted gateway, on one node or a cluster with leased profiles.
+icon: users
+---
+
+# SaaS profiles
+
+The OpenHuman core can serve many users from one process. Each user is one
+**profile**: their own config, credential, workspace, sandbox and threads,
+laid out like the desktop app's `users/<id>/` directory. A trusted gateway in
+front of the core authenticates users and calls the core on their behalf. The
+core never sees a user's password or login; it trusts the gateway's service
+token and the user id the gateway names.
+
+This page covers deploying that service. The in-process variant, for a Rust
+server that wants the same isolation without a gateway, is
+[`ProfileRuntime`](embed/concepts/profiles-saas.md).
+The internals are in
+[`profiles/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/profiles/README.md).
+
+## What a user gets
+
+- **One profile per user.** It is opened on the user's first request, kept
+ while in use, and closed after `idle_evict_secs` of idleness (or when
+ `max_profiles_open` is reached and it is the least recently used idle one).
+- **One thread per conversation, per interface.** Web chat threads are named
+ by the user (`t1`, `work-notes`); a message the gateway relays from a
+ hosted platform (Telegram, iMessage, Discord) lands on that user's
+ `channel:<platform>/<sender>/<chat>` thread. Thread ids are unique per
+ profile, so two users' `t1` never meet.
+- **A reviewed surface.** A user's requests reach only the user methods:
+ their threads, web chat (start, cancel, queue control), the channel relay,
+ and reads and writes of their own memory. Everything else answers as an
+ unknown method.
+- **Their own events.** `GET /events?client_id=` streams only that user's
+ chat progress, final replies and relayed `channel_outbound` replies.
+- **Closed tools by default.** No shell or file tool reaches the host unless
+ the operator opts users into `host_files` or `host_shell`; `host_shell`
+ runs every command in a locked-down Docker container whose only writable
+ mount is the user's `sandbox/`.
+
+## Operator config
+
+The core runs in SaaS mode from the operator's own TOML file, never from a
+user's `config.toml`:
+
+```bash
+openhuman-core run --mode saas --saas-config /etc/openhuman/saas.toml
+```
+
+```toml
+root = "/srv/openhuman" # absolute, existing, not world-writable
+# service_token_file = "/srv/openhuman/service.token" # the default
+max_profiles_open = 256 # profiles open at once on this node
+idle_evict_secs = 1800 # close a profile idle this long
+profile_ids = "raw" # or "hashed"
+require_user_signature = true # X-OpenHuman-User-Sig on every user request
+tool_allowlist = [] # "host_files", "host_shell"
+shared_backend_api_key = true # let every user ride OPENHUMAN_BACKEND_API_KEY
+custom_definitions = false
+
+# Cluster settings (see below)
+# storage_url = "mongodb://db.internal/openhuman" # OPENHUMAN_STORAGE_URL wins
+# node_id = "node-a" # else OPENHUMAN_NODE_ID, else random
+# advertise_url = "http://10.0.0.11:7788" # marks the node as clustered
+# lease_ttl_secs = 30
+# operator_dir = "/var/lib/openhuman/node-a" # default <root>/operator
+
+[sandbox] # only used with host_shell
+image = "alpine:3.20"
+network = "none"
+memory_limit_mb = 512
+cpu_limit = 1.0
+```
+
+Unknown keys are refused. The boot guard refuses to start, listing every
+problem at once, when the root is relative, missing, world-writable or inside
+`~/.openhuman`; when the service token is missing, readable by others or
+shorter than 32 bytes; when single-user variables are set
+(`OPENHUMAN_WORKSPACE`, `OPENHUMAN_CORE_TOKEN`, `OPENHUMAN_DEV_CONNECT`,
+`OPENHUMAN_BACKEND_SESSION_TOKEN`) or a protection is switched off
+(`OPENHUMAN_APPROVAL_GATE`, `OPENHUMAN_SANDBOX`); when `host_shell` is
+allowlisted without a working Docker; and when a clustered node has no
+storage backend that can keep leases exclusive.
+
+Write the service token once, owner-only:
+
+```bash
+openssl rand -hex 32 > /srv/openhuman/service.token
+chmod 600 /srv/openhuman/service.token
+```
+
+## The gateway contract
+
+Every request carries the service token. A request for a user also names the
+user and signs that name:
+
+```text
+Authorization: Bearer <service token>
+X-OpenHuman-User: <your user id>
+X-OpenHuman-User-Sig: t=<unix secs>,v1=<hex hmac-sha256(service token, "<t>.<user id>")>
+```
+
+- Without `X-OpenHuman-User` the request runs on the **operator plane**:
+ `profiles.provision`, `deprovision`, `list`, `status`, `set_credential`,
+ `clear_credential` and `release` (`openhuman.profiles_*` over JSON-RPC).
+- With it, the core checks, in order: the bearer (`401`), a duplicate or
+ unreadable user header (`400`), the signature, which must be within 60
+ seconds of the core's clock (`401`), and the user's profile, which must
+ already be provisioned (`403`). A full node or a storage failure answers
+ `503`.
+- The user's TinyHumans credential (session JWT or API key) goes in once
+ through `profiles.set_credential`; the core uses it for that user's
+ inference and backend calls and never validates or echoes it.
+
+A minimal signer:
+
+```python
+import hashlib, hmac, time
+
+def sign(service_token: str, user_id: str) -> str:
+ t = int(time.time())
+ tag = hmac.new(service_token.encode(), f"{t}.{user_id}".encode(), hashlib.sha256)
+ return f"t={t},v1={tag.hexdigest()}"
+```
+
+### Profile ids
+
+With `profile_ids = "raw"`, a user id matching `^[a-z0-9][a-z0-9_-]{0,63}$`
+is the profile id as is (`local`, `operator` and `h-*` are reserved); any
+other id becomes `h-<32 hex of sha256(user id)>`. `"hashed"` hashes every id,
+which keeps your user ids out of paths and logs. Changing the mode maps users
+onto new, empty profiles.
+
+### Relaying hosted chat platforms
+
+The gateway owns each platform's webhook and the user's account link. For
+each inbound message it calls, as that user:
+
+```json
+{"method": "openhuman.channel_relay_inbound",
+ "params": {"channel": "telegram", "chat_id": "777", "sender_id": "555",
+ "sender_name": "Alice", "message_id": "tg-1", "text": "hello",
+ "client_id": "channel-relay"}}
+```
+
+The answer comes at once (`accepted`, `thread_id`, `request_id`); a
+`message_id` already recorded answers `duplicate: true` and runs nothing, so
+retries are safe. The reply arrives on the user's
+`/events?client_id=channel-relay` stream as a `channel_outbound` event
+carrying `full_response` and the `channel` and `chat_id` to deliver it to.
+
+## One node
+
+On a single node, leave `storage_url` and `advertise_url` unset. The profile
+registry is `profile.toml` files under `<root>/users/`, and each profile's
+lease is a file lock on `<root>/users/<id>/.lease`, which also keeps a
+second process on the same root from opening the same profile.
+
+## A cluster
+
+Several nodes can serve one user base. Each profile is hosted by exactly one
+node at a time, enforced by a **lease** in a shared storage backend; any node
+can host any profile.
+
+1. **One storage backend.** Set `storage_url` (or `OPENHUMAN_STORAGE_URL`) to
+ a driver whose compare-and-swap is atomic across processes: MongoDB
+ (`mongodb://…/<db>`, the `storage-mongodb` build feature) for nodes on
+ several hosts, or SQLite (`sqlite:<path>`, `storage-sqlite`) for several
+ processes on one host. Do not put SQLite on a network filesystem. It holds the
+ profile registry, the leases, the session store, and each profile's
+ records (secrets, auth profiles, approvals, cron, flows) under scope
+ `profile:<id>`.
+2. **One shared volume for `root`.** Thread files, the cost and run ledgers,
+ background completions and each user's `sandbox/` are still files under
+ `<root>/users/<id>/`. Mount `root` on a read-write-many volume (NFS, EFS,
+ CephFS) on every node. Keep memory on a remote engine: profiles use the
+ hosted TinyHumans memory engine, which needs no volume.
+3. **A unique, stable `node_id` per node,** and an `advertise_url` the gateway
+ can reach it on. Setting `advertise_url` marks the node as clustered; the
+ boot guard then insists on a cross-process backend. A stable node id lets
+ a restarted node take its own profiles back at once.
+4. **Its own `operator_dir` per node,** so nodes sharing a root do not share
+ the operator workspace and keyring.
+
+### Routing and the 409
+
+Route users stickily: hash the user id onto a node (consistent hashing keeps
+most users in place when nodes come and go). Stickiness is only for speed;
+the lease is what makes it correct. When a request reaches a node while
+another node holds that user's profile, the core answers:
+
+```text
+HTTP/1.1 409 Conflict
+X-OpenHuman-Profile-Owner: node-b
+
+{"error": "profile_held", "owner": "node-b",
+ "endpoint": "http://10.0.0.12:7788", "retry_after_ms": 21500}
+```
+
+The gateway should forward the request to `endpoint` (and update its routing
+for that user), or, when `endpoint` is null or unreachable, retry after
+`retry_after_ms`. The `409` comes only after the bearer check, so an
+unauthenticated caller learns nothing about which users exist.
+
+To move a user deliberately (draining a node, rebalancing), call
+`profiles.release {"profile_id": ...}` on the node that holds it. It refuses
+while the profile is in use; retry shortly.
+
+### Failover and recovery
+
+- A holder renews each lease every third of `lease_ttl_secs`. A node that
+ crashes or loses the backend stops renewing, and its profiles become
+ available to other nodes once their leases expire (at most
+ `lease_ttl_secs`, 30 seconds by default).
+- The node that takes over a lease that was never released recovers the
+ profile before serving it: turns that were in flight are marked
+ interrupted and orphaned run-ledger rows are settled. A clean hand-over
+ (idle eviction, release, shutdown) recovers nothing.
+- A node that finds its lease changed under it (another node took over, or
+ an operator released it) fences the profile: it stops that profile's
+ running turns and starts no new ones.
+- On a clean shutdown a node releases the leases of its idle profiles at
+ once; a profile still busy keeps its lease, so its next holder recovers its
+ turns.
+
+Known limit: storage writes carry no epoch fence, so a node that is
+partitioned from the backend but still running could write briefly after its
+lease expired. Keep `lease_ttl_secs` well above network hiccups, and treat
+the fence check before each turn and the turn cancellation on loss as the
+mitigation.
+
+## Checklist
+
+- `root` absolute, not world-writable, on a shared RWX volume (cluster).
+- `service.token` mode `0600`, at least 32 bytes, shared with the gateway only.
+- Gateway signs `X-OpenHuman-User` and keeps clocks in sync (±60 s).
+- `storage_url` on MongoDB (or SQLite for processes on one host), with the
+ matching build feature (cluster).
+- `node_id`, `advertise_url` and `operator_dir` unique per node (cluster).
+- Load balancer hashes users stickily and honours `409` redirects.
+- Provision a user (`profiles.provision`) and install their credential
+ (`profiles.set_credential`) before their first request.
diff --git a/docs/library-minimal-recipe.md b/docs/library-minimal-recipe.md
index b534d3e021..79fba31d6d 100644
--- a/docs/library-minimal-recipe.md
+++ b/docs/library-minimal-recipe.md
@@ -55,27 +55,7 @@ and agents can only narrow them, so include `mcp` / `skills` in both the
Cargo features **and** the runtime's `DomainSet` (the builder's default does)
if any agent will declare servers or skills.
-```rust,no_run
-use openhuman_tinyhumans::{
- embed::{Access, AgentSpec, Workspace},
- RuntimeBuilder,
-};
-
-# async fn demo() -> Result<(), Box<dyn std::error::Error>> {
-let runtime = RuntimeBuilder::new()
- .workspace(Workspace::dir("/var/lib/opencompany/openhuman"))
- .api_key(std::env::var("TINYHUMANS_API_KEY")?)
- .build()
- .await?;
-let worker = runtime.agent(
- AgentSpec::new("worker-1")
- .access(Access::full())
- .action_dir("/srv/jobs/1"),
-)?;
-println!("{}", worker.run("Start the job.").await?.reply);
-# Ok(())
-# }
-```
+See the runnable [two_agents example](../crates/openhuman-embed/examples/two_agents.rs), region `two_agents`. It uses the public facade and asserts its behavior against an offline stub.
### Choosing the backend layer
diff --git a/examples/embed_headless.rs b/examples/embed_headless.rs
deleted file mode 100644
index d3bdaa3132..0000000000
--- a/examples/embed_headless.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-//! Embed the OpenHuman core as a library — no HTTP, no background services.
-//!
-//! Demonstrates the library API, `openhuman_embed::Runtime`: build a
-//! fully-initialized core with [`ServiceSet::none`] (no ports bound, no cron/channels/login-gated services) AND
-//! [`DomainSet::harness`] (only the agent + memory + threads + config + security
-//! domain families are live — the gate families flows/skills/mcp/meet/channels/
-//! web3/voice/media and the catch-all `platform` are off, so their controllers
-//! are unknown-method, their agent tools absent, and their stores/subscribers
-//! never initialize). Dispatch RPC methods in-process through
-//! [`Runtime::core_runtime`]'s `invoke` — the exact same path the HTTP `/rpc`
-//! handler and the CLI use. The workspace is ephemeral (the library default),
-//! so running this touches nothing in `~/.openhuman`. Turns belong to agents:
-//! see `Runtime::agent` for the typed path.
-//!
-//! Run with:
-//!
-//! ```bash
-//! cargo run --example embed_headless
-//! ```
-//!
-//! To instead expose the core over HTTP, use `openhuman-rpc`'s host entries
-//! (`openhuman_rpc::host::serve_desktop` / the `openhuman-core serve` CLI),
-//! which serve a runtime like this one over JSON-RPC. Widen the runtime surface
-//! by swapping `DomainSet::harness()` for `DomainSet::full()`.
-
-use openhuman_embed::{DomainSet, HostKind, Runtime, ServiceSet};
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- // Library embedders own logging; a simple env_logger keeps the example
- // self-contained. (`RUST_LOG=info cargo run --example embed_headless`)
- let _ = env_logger::builder().is_test(false).try_init();
-
- // Initialize the core on an ephemeral workspace. `HostKind::Cli` selects
- // the standalone (non-desktop) bootstrap path; `DomainSet::harness()` builds
- // the embeddable agent core; `ServiceSet::none()` means no transport and no
- // background services are started.
- let runtime = Runtime::builder()
- .host_kind(HostKind::Cli)
- .domains(DomainSet::harness())
- .services(ServiceSet::none())
- .build()
- .await?;
- let core = runtime.core_runtime();
-
- // Dispatch a couple of RPC methods in-process — no network involved.
- // `core.version` and `openhuman.ping` (a legacy alias for the built-in
- // `core.ping`) are always available regardless of the DomainSet — they are
- // transport built-ins, not domain controllers — so they succeed even under
- // `harness()`.
- let version = core
- .invoke("core.version", serde_json::json!({}))
- .await
- .map_err(|e| anyhow::anyhow!("core.version failed: {e}"))?;
- println!("core.version -> {version}");
-
- let ping = core
- .invoke("openhuman.ping", serde_json::json!({}))
- .await
- .map_err(|e| anyhow::anyhow!("openhuman.ping failed: {e}"))?;
- println!("openhuman.ping -> {ping}");
-
- Ok(())
-}
diff --git a/examples/embed_kernel.rs b/examples/embed_kernel.rs
deleted file mode 100644
index 824e622c21..0000000000
--- a/examples/embed_kernel.rs
+++ /dev/null
@@ -1,86 +0,0 @@
-//! Embed the OpenHuman core at its **kernel floor**, then opt one subsystem in.
-//!
-//! [`DomainSet::kernel`] is the smallest useful runtime surface: threads,
-//! config, and security — the transport, dispatch, policy and identity a host
-//! needs before it has decided what the core is *for*. Notably `agent` and
-//! `memory` are OFF: they are the two largest subsystems and the ones an
-//! alternative driver would replace, so a host that wants them says so.
-//!
-//! Contrast the two presets:
-//!
-//! - [`DomainSet::harness`] — kernel + `agent` + `memory`. The embeddable agent
-//! core; see `examples/embed_headless.rs`.
-//! - [`DomainSet::kernel`] — the floor. Start here when you want, say, memory
-//! without the agent harness, or when you intend to bind your own driver to a
-//! subsystem slot.
-//!
-//! Because `DomainSet` is a plain struct, opting a family back in is a field
-//! assignment — no builder ceremony:
-//!
-//! ```ignore
-//! let mut domains = DomainSet::kernel();
-//! domains.memory = true; // kernel + memory, nothing else
-//! ```
-//!
-//! What "off" means is uniform across every axis: the family's controllers are
-//! unregistered (unknown-method over `/rpc`, absent from `/schema`), its agent
-//! tools are absent from the tool list rather than present-and-failing, and its
-//! stores and event-bus subscribers never initialize.
-//!
-//! Run with:
-//!
-//! ```bash
-//! cargo run --example embed_kernel
-//! ```
-
-//! Built with the library API (`openhuman_embed::Runtime`) on an ephemeral
-//! workspace, so running it touches nothing in `~/.openhuman`.
-
-use openhuman_embed::{DomainSet, HostKind, Runtime, ServiceSet};
-
-#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- // Kernel floor plus exactly one subsystem: memory. The agent harness stays
- // out, so this process can serve memory reads/writes without ever
- // constructing an agent.
- let mut domains = DomainSet::kernel();
- domains.memory = true;
-
- let runtime = Runtime::builder()
- .host_kind(HostKind::Cli)
- .domains(domains)
- .services(ServiceSet::none())
- .build()
- .await?;
- let core = runtime.core_runtime();
-
- // Always available — `core.*` is kernel transport, not a domain.
- let version = core
- .invoke("core.version", serde_json::json!({}))
- .await
- .map_err(|e| anyhow::anyhow!("core.version failed: {e}"))?;
- println!("core.version -> {version}");
-
- // Enabled: memory was opted in above.
- match core
- .invoke("openhuman.memory_list_namespaces", serde_json::json!({}))
- .await
- {
- Ok(v) => println!("memory_list_namespaces -> {v}"),
- Err(e) => println!("memory_list_namespaces -> error: {e:?}"),
- }
-
- // Disabled: `agent` is off under kernel(), so this is an UNKNOWN METHOD —
- // not a registered handler returning "agent disabled". Absence is the
- // contract: a registered-but-failing method teaches a model the capability
- // exists and makes it retry.
- match core
- .invoke("openhuman.agent_list_definitions", serde_json::json!({}))
- .await
- {
- Ok(v) => println!("agent_list_definitions -> unexpectedly OK: {v}"),
- Err(e) => println!("agent_list_definitions -> unknown method (expected): {e:?}"),
- }
-
- Ok(())
-}
diff --git a/gitbooks/SUMMARY.md b/gitbooks/SUMMARY.md
index 26a45c0b5e..8e6d7a2fd3 100644
--- a/gitbooks/SUMMARY.md
+++ b/gitbooks/SUMMARY.md
@@ -87,7 +87,51 @@
- [Performance and footprint](developing/performance.md)
- [Pluggable engines](developing/engines.md)
- [Jev](developing/jev.md)
-- [Embedding OpenHuman](developing/embedding.md)
+- [Embedding](developing/embed/README.md)
+ - [Installation](developing/embed/installation.md)
+ - [Quickstart](developing/embed/quickstart.md)
+ - [Embedding architecture](developing/embed/architecture.md)
+ - [Concepts](developing/embed/concepts/README.md)
+ - [Runtime](developing/embed/concepts/runtime.md)
+ - [Runtime defaults](developing/embed/concepts/runtime-defaults.md)
+ - [Agents](developing/embed/concepts/agents.md)
+ - [Access and approvals](developing/embed/concepts/access-approvals.md)
+ - [Providers](developing/embed/concepts/providers.md)
+ - [Turns and sessions](developing/embed/concepts/turns-sessions.md)
+ - [Tools](developing/embed/concepts/tools.md)
+ - [MCP](developing/embed/concepts/mcp.md)
+ - [Skills](developing/embed/concepts/skills.md)
+ - [Memory](developing/embed/concepts/memory.md)
+ - [Cron](developing/embed/concepts/cron.md)
+ - [Channels](developing/embed/concepts/channels.md)
+ - [Profiles and SaaS](developing/embed/concepts/profiles-saas.md)
+ - [Completer](developing/embed/concepts/completer.md)
+ - [Hooks and seams](developing/embed/concepts/hooks-seams.md)
+ - [Observability](developing/embed/concepts/observability.md)
+ - [Testing](developing/embed/concepts/testing.md)
+ - [Errors](developing/embed/concepts/errors.md)
+ - [Embedding guides](developing/embed/guides/README.md)
+ - [CLI chatbot](developing/embed/guides/cli-chatbot.md)
+ - [Multiple agents](developing/embed/guides/multi-agent.md)
+ - [SaaS with multiple tenants](developing/embed/guides/saas-multi-tenant.md)
+ - [Deploy a server](developing/embed/guides/deploy-server.md)
+ - [Lean and headless hosts](developing/embed/guides/lean-headless.md)
+ - [Test with a mock backend](developing/embed/guides/mock-backend-testing.md)
+ - [Embedding integrations](developing/embed/integrations/README.md)
+ - [OpenAI-compatible providers and BYOK](developing/embed/integrations/openai-compatible.md)
+ - [TinyHumans managed inference](developing/embed/integrations/tinyhumans-managed.md)
+ - [Local and custom models](developing/embed/integrations/local-models.md)
+ - [MCP servers](developing/embed/integrations/mcp.md)
+ - [Composio](developing/embed/integrations/composio.md)
+ - [Storage drivers](developing/embed/integrations/storage-drivers.md)
+ - [Channels](developing/embed/integrations/channels.md)
+ - [Cookbook](developing/embed/cookbook.md)
+ - [Embedding API reference](developing/embed/api-reference.md)
+ - [API index](developing/embed/api-index.md)
+ - [RuntimeBuilder setters](developing/embed/builder-setters.md)
+ - [Compiled feature matrix](developing/embed/capability-matrix.md)
+ - [Embedding FAQ](developing/embed/faq.md)
+ - [Embedding troubleshooting](developing/embed/troubleshooting.md)
- [SaaS profiles](developing/saas-profiles.md)
- [One TinyHumans API key](developing/tinyhumans-api-key.md)
- [Hooks](developing/hooks.md)
diff --git a/gitbooks/developing/embed/README.md b/gitbooks/developing/embed/README.md
new file mode 100644
index 0000000000..29e568533e
--- /dev/null
+++ b/gitbooks/developing/embed/README.md
@@ -0,0 +1,34 @@
+---
+description: "Run the OpenHuman core inside a Rust application with one Runtime and independently configured Agents."
+---
+
+# Embedding OpenHuman
+
+`openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+
+Build one `Runtime` per process and register the agents your product needs. Each agent can choose its own provider, prompt, working folder, tool scope, skills and MCP servers. Agents share runtime credentials; use `ProfileRuntime` when separate customers need separate credentials and workspaces.
+
+## Start here
+
+- [Installation](installation.md): dependency, Cargo gates, runtime setup and configuration.
+- [Quickstart](quickstart.md): run a verified offline turn, then choose a live provider explicitly.
+- [Architecture](architecture.md): ownership, lifecycle and the library chain.
+- [Concepts](concepts/README.md): the 18 public API concepts and their runtime/agent scope.
+- [Guides](guides/README.md): chatbots, multiple agents, SaaS, server deployment and tests.
+- [Integrations](integrations/README.md): inference, MCP, connectors, storage and channels.
+- [Cookbook](cookbook.md): generated inventory of executable examples.
+- [API reference](api-reference.md): local rustdoc, source links and generated builder knobs.
+
+## Choose the right surface
+
+| Requirement | Start with |
+| --- | --- |
+| One agent with a small host | `Harness` |
+| Several independently configured agents | `Runtime` and `AgentSpec` |
+| Stateless model generation | `Completer` |
+| Authenticated users with isolated credentials and state | `ProfileRuntime` |
+| Public JSON-RPC server or shipped desktop host | The `openhuman-rpc` host layer |
+
+The snippets in this section are injected from compiled, offline-tested Rust examples. Their full source files include the surrounding setup. `pnpm docs:check` checks source drift, local links, the generated API inventory and the published English mirror.
+
+See [FAQ](faq.md) for design choices and [troubleshooting](troubleshooting.md) for setup failures.
diff --git a/gitbooks/developing/embed/api-index.json b/gitbooks/developing/embed/api-index.json
new file mode 100644
index 0000000000..76919ff831
--- /dev/null
+++ b/gitbooks/developing/embed/api-index.json
@@ -0,0 +1,565 @@
+{
+ "schema_version": 1,
+ "exports": [
+ "Access",
+ "Agent",
+ "AgentDefaults",
+ "AgentDefinition",
+ "AgentDefinitionSpec",
+ "AgentError",
+ "AgentLayout",
+ "AgentProgress",
+ "AgentSpec",
+ "AgentTurnOrigin",
+ "ApiKey",
+ "ApprovalDecision",
+ "ApprovalHandler",
+ "ApprovalSubscription",
+ "Approvals",
+ "ApprovalsError",
+ "Auth",
+ "AuthState",
+ "BackendRequest",
+ "BackendTransport",
+ "BackendTransportError",
+ "BaseUrlPurpose",
+ "CancellationToken",
+ "ChannelError",
+ "ChannelListener",
+ "Channels",
+ "ChatMessage",
+ "ChatReply",
+ "Completer",
+ "CompletionObserver",
+ "CompletionRequest",
+ "CompletionResponse",
+ "CompletionTrace",
+ "CompletionUsage",
+ "ComposioHostCredential",
+ "Config",
+ "ConfigSource",
+ "ConfigurationInfo",
+ "ControllerSchema",
+ "CoreAgent",
+ "CoreBuilder",
+ "CoreError",
+ "CoreRuntime",
+ "Cron",
+ "CronError",
+ "DEFAULT_MAX_AGENTS",
+ "DaemonConfig",
+ "DefaultsInfo",
+ "DefinitionBase",
+ "DomainSet",
+ "EventStreamError",
+ "GroupMode",
+ "HTTP_SERVER_COMPILED_IN",
+ "Harness",
+ "HarnessBuilder",
+ "HarnessCore",
+ "HarnessError",
+ "HostKind",
+ "HostTools",
+ "HostTurnTools",
+ "HttpHeader",
+ "InMemorySessionStores",
+ "JobRun",
+ "JobRunRecord",
+ "JobSchedule",
+ "JobSpec",
+ "JobTarget",
+ "LastTurnUsage",
+ "LearningSettings",
+ "McpAuthConfig",
+ "McpServer",
+ "MemoryBinding",
+ "ModelDefaults",
+ "OpenError",
+ "PendingApproval",
+ "PermissionLevel",
+ "PickListenPortError",
+ "ProfileError",
+ "ProfileEvents",
+ "ProfileHandle",
+ "ProfileId",
+ "ProfileIdMode",
+ "ProfileRuntime",
+ "ProfileRuntimeBuilder",
+ "ProfileSummary",
+ "Provider",
+ "Provisioned",
+ "RelayAccepted",
+ "RelayMessage",
+ "RemoveAgent",
+ "Route",
+ "Runtime",
+ "RuntimeBuilder",
+ "RuntimeConfig",
+ "RuntimeDefaults",
+ "RuntimeError",
+ "RuntimeEvent",
+ "RuntimeEventKind",
+ "RuntimeEvents",
+ "RuntimeFlags",
+ "RuntimeInfo",
+ "RuntimeModule",
+ "SaasConfig",
+ "SandboxModeSpec",
+ "ScheduledJob",
+ "ServiceSet",
+ "Session",
+ "SessionStoreProvider",
+ "SkillsPolicy",
+ "StorageInfo",
+ "StreamEvent",
+ "StreamMode",
+ "SystemJobContext",
+ "TelegramChannelSpec",
+ "TokenSource",
+ "Tool",
+ "ToolAttachmentError",
+ "ToolExposure",
+ "ToolGroups",
+ "ToolResult",
+ "ToolScopeSpec",
+ "TransportProfile",
+ "TrustedAccess",
+ "TrustedAutomationSource",
+ "Turn",
+ "TurnContext",
+ "TurnOutcome",
+ "TurnRequest",
+ "TurnStream",
+ "VOICE_COMPILED_IN",
+ "WeightClass",
+ "Workspace",
+ "absolute",
+ "agent_progress",
+ "artifacts",
+ "channels",
+ "chat_surface",
+ "complete",
+ "config",
+ "cron",
+ "embeddings",
+ "events",
+ "identity",
+ "install_backend_transport",
+ "installed_backend_transport",
+ "memory",
+ "modules",
+ "process",
+ "profiles",
+ "providers",
+ "run_from_args",
+ "schema_for_rpc_method",
+ "seams",
+ "session_store",
+ "skill_registry",
+ "stream"
+ ],
+ "builder_setters": [
+ {
+ "name": "access",
+ "signature": "pub fn access(mut self, access: Access) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 343
+ },
+ {
+ "name": "action_dir",
+ "signature": "pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 300
+ },
+ {
+ "name": "agent_defaults",
+ "signature": "pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 151
+ },
+ {
+ "name": "api_key",
+ "signature": "pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 320
+ },
+ {
+ "name": "autonomy",
+ "signature": "pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 186
+ },
+ {
+ "name": "backend_transport",
+ "signature": "pub fn backend_transport(mut self, transport: Arc<dyn BackendTransport>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 225
+ },
+ {
+ "name": "backend_url",
+ "signature": "pub fn backend_url(mut self, url: impl Into<String>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 330
+ },
+ {
+ "name": "config",
+ "signature": "pub fn config(mut self, config: Config) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 444
+ },
+ {
+ "name": "config_source",
+ "signature": "pub fn config_source(mut self, source: ConfigSource) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 308
+ },
+ {
+ "name": "controller_extension",
+ "signature": "pub fn controller_extension(mut self, extension: ControllerExtension) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 415
+ },
+ {
+ "name": "cron",
+ "signature": "pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 211
+ },
+ {
+ "name": "definition_base",
+ "signature": "pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 170
+ },
+ {
+ "name": "domains",
+ "signature": "pub fn domains(mut self, domains: DomainSet) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 374
+ },
+ {
+ "name": "host_kind",
+ "signature": "pub fn host_kind(mut self, host_kind: HostKind) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 391
+ },
+ {
+ "name": "learning",
+ "signature": "pub fn learning(mut self, value: super::LearningSettings) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 206
+ },
+ {
+ "name": "listen",
+ "signature": "pub fn listen(self, host: impl Into<String>, port: u16) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 413
+ },
+ {
+ "name": "listen_host",
+ "signature": "pub fn listen_host(mut self, host: impl Into<String>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 418
+ },
+ {
+ "name": "listen_port",
+ "signature": "pub fn listen_port(mut self, port: u16) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 424
+ },
+ {
+ "name": "live_policy",
+ "signature": "pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 464
+ },
+ {
+ "name": "max_agents",
+ "signature": "pub fn max_agents(mut self, limit: usize) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 263
+ },
+ {
+ "name": "mcp_baseline",
+ "signature": "pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 181
+ },
+ {
+ "name": "memory_engine",
+ "signature": "pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 239
+ },
+ {
+ "name": "model_defaults",
+ "signature": "pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 160
+ },
+ {
+ "name": "modules",
+ "signature": "pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/selection.rs",
+ "line": 156
+ },
+ {
+ "name": "post_turn_hook",
+ "signature": "pub fn post_turn_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 430
+ },
+ {
+ "name": "privacy",
+ "signature": "pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 196
+ },
+ {
+ "name": "provider",
+ "signature": "pub fn provider(mut self, provider: Provider) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 336
+ },
+ {
+ "name": "sandbox",
+ "signature": "pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 165
+ },
+ {
+ "name": "secrets",
+ "signature": "pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 201
+ },
+ {
+ "name": "server_launcher",
+ "signature": "pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 444
+ },
+ {
+ "name": "services",
+ "signature": "pub fn services(mut self, services: ServiceSet) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 362
+ },
+ {
+ "name": "session",
+ "signature": "pub fn session(mut self, session: Session) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 434
+ },
+ {
+ "name": "session_store",
+ "signature": "pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 254
+ },
+ {
+ "name": "skills",
+ "signature": "pub fn skills(mut self, policy: super::SkillsPolicy) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 175
+ },
+ {
+ "name": "storage",
+ "signature": "pub fn storage(mut self, source: impl Into<StorageSource>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 457
+ },
+ {
+ "name": "token",
+ "signature": "pub fn token(mut self, token: TokenSource) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 401
+ },
+ {
+ "name": "tool_groups",
+ "signature": "pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 383
+ },
+ {
+ "name": "tool_hook",
+ "signature": "pub fn tool_hook(mut self, hook: Arc<dyn ToolHook>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 437
+ },
+ {
+ "name": "tool_ranker",
+ "signature": "pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/seams.rs",
+ "line": 422
+ },
+ {
+ "name": "tool_rules",
+ "signature": "pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 191
+ },
+ {
+ "name": "workspace",
+ "signature": "pub fn workspace(mut self, workspace: Workspace) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 273
+ },
+ {
+ "name": "workspace_dir",
+ "signature": "pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self",
+ "source": "crates/openhuman-embed/src/runtime/builder.rs",
+ "line": 287
+ }
+ ],
+ "capabilities": {
+ "schema_version": 1,
+ "configuration_resolved": true,
+ "compiled_features": {
+ "channels": true,
+ "crash-reporting": false,
+ "default": true,
+ "documents": false,
+ "e2e-test-support": false,
+ "file-logging": true,
+ "flows": true,
+ "hosting": false,
+ "http-server": true,
+ "inference": false,
+ "mcp": true,
+ "media": true,
+ "modules": true,
+ "rss-bench": false,
+ "runtime-node": false,
+ "scheduler-gate": true,
+ "skills": true,
+ "storage-file": false,
+ "storage-mongodb": false,
+ "storage-sqlite": false,
+ "tinymemes": true,
+ "voice": false,
+ "web3": false,
+ "whatsapp-web": false
+ },
+ "domains": [
+ "agent",
+ "memory",
+ "threads",
+ "config",
+ "security",
+ "flows",
+ "skills",
+ "channels",
+ "inference",
+ "integrations",
+ "automation",
+ "runtimes",
+ "platform"
+ ],
+ "services": [
+ "harness_init"
+ ],
+ "tool_groups": {
+ "audio": "withheld",
+ "coding": "withheld",
+ "composio": "withheld",
+ "docs": "withheld",
+ "documents": "withheld",
+ "goals": "withheld",
+ "mcp": "withheld",
+ "media": "withheld",
+ "scheduling": "withheld",
+ "skills": "withheld",
+ "storage": "withheld",
+ "system": "withheld",
+ "tasks": "withheld",
+ "web3": "withheld",
+ "workflows": "withheld"
+ },
+ "host_kind": "Library",
+ "max_agents": 1024,
+ "defaults": {
+ "model": {
+ "temperature": 0.7,
+ "max_tokens": null,
+ "top_p": null,
+ "max_iterations": 200
+ },
+ "provider_model": "openrouter/deepseek/deepseek-v4-flash",
+ "routed_provider": false,
+ "sandbox": "None",
+ "approval_gate": true,
+ "include_user_skills": false,
+ "has_skills_root": false,
+ "mcp_servers": 0,
+ "templates": []
+ },
+ "configuration": {
+ "autonomy_enabled": true,
+ "privacy": "Standard",
+ "secrets_encrypted": true,
+ "cron_enabled": true,
+ "learning": {
+ "build_beliefs_every": 10,
+ "learnings_limit": 8
+ },
+ "has_tool_rules": false
+ },
+ "storage": {
+ "source": "workspace",
+ "driver": null,
+ "configured": false
+ },
+ "modules": [],
+ "weight": "custom"
+ },
+ "pages": [
+ "gitbooks/developing/embed/README.md",
+ "gitbooks/developing/embed/api-reference.md",
+ "gitbooks/developing/embed/architecture.md",
+ "gitbooks/developing/embed/concepts/README.md",
+ "gitbooks/developing/embed/concepts/access-approvals.md",
+ "gitbooks/developing/embed/concepts/agents.md",
+ "gitbooks/developing/embed/concepts/channels.md",
+ "gitbooks/developing/embed/concepts/completer.md",
+ "gitbooks/developing/embed/concepts/cron.md",
+ "gitbooks/developing/embed/concepts/errors.md",
+ "gitbooks/developing/embed/concepts/hooks-seams.md",
+ "gitbooks/developing/embed/concepts/mcp.md",
+ "gitbooks/developing/embed/concepts/memory.md",
+ "gitbooks/developing/embed/concepts/observability.md",
+ "gitbooks/developing/embed/concepts/profiles-saas.md",
+ "gitbooks/developing/embed/concepts/providers.md",
+ "gitbooks/developing/embed/concepts/runtime-defaults.md",
+ "gitbooks/developing/embed/concepts/runtime.md",
+ "gitbooks/developing/embed/concepts/skills.md",
+ "gitbooks/developing/embed/concepts/testing.md",
+ "gitbooks/developing/embed/concepts/tools.md",
+ "gitbooks/developing/embed/concepts/turns-sessions.md",
+ "gitbooks/developing/embed/faq.md",
+ "gitbooks/developing/embed/guides/README.md",
+ "gitbooks/developing/embed/guides/cli-chatbot.md",
+ "gitbooks/developing/embed/guides/deploy-server.md",
+ "gitbooks/developing/embed/guides/lean-headless.md",
+ "gitbooks/developing/embed/guides/mock-backend-testing.md",
+ "gitbooks/developing/embed/guides/multi-agent.md",
+ "gitbooks/developing/embed/guides/saas-multi-tenant.md",
+ "gitbooks/developing/embed/installation.md",
+ "gitbooks/developing/embed/integrations/README.md",
+ "gitbooks/developing/embed/integrations/channels.md",
+ "gitbooks/developing/embed/integrations/composio.md",
+ "gitbooks/developing/embed/integrations/local-models.md",
+ "gitbooks/developing/embed/integrations/mcp.md",
+ "gitbooks/developing/embed/integrations/openai-compatible.md",
+ "gitbooks/developing/embed/integrations/storage-drivers.md",
+ "gitbooks/developing/embed/integrations/tinyhumans-managed.md",
+ "gitbooks/developing/embed/quickstart.md",
+ "gitbooks/developing/embed/troubleshooting.md",
+ "crates/openhuman-embed/README.md",
+ "gitbooks/developing/embedding.md",
+ "gitbooks/developing/embed/cookbook.md",
+ "gitbooks/developing/embed/capability-matrix.md",
+ "gitbooks/developing/embed/builder-setters.md",
+ "gitbooks/developing/embed/api-index.md"
+ ]
+}
diff --git a/gitbooks/developing/embed/api-index.md b/gitbooks/developing/embed/api-index.md
new file mode 100644
index 0000000000..3e386b0c6d
--- /dev/null
+++ b/gitbooks/developing/embed/api-index.md
@@ -0,0 +1,268 @@
+# API index
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. [Canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs).
+
+- [`Access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinition`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinitionSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentLayout`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentProgress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentTurnOrigin`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApiKey`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalDecision`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalHandler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalSubscription`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Approvals`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalsError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Auth`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AuthState`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransportError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BaseUrlPurpose`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CancellationToken`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelListener`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatReply`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Completer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionObserver`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionResponse`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionTrace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ComposioHostCredential`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CronError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DEFAULT_MAX_AGENTS`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DaemonConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefaultsInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefinitionBase`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DomainSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`EventStreamError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`GroupMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HTTP_SERVER_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Harness`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessCore`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTurnTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HttpHeader`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`InMemorySessionStores`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRun`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRunRecord`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSchedule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobTarget`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LastTurnUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LearningSettings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpAuthConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpServer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`MemoryBinding`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ModelDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`OpenError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PendingApproval`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PermissionLevel`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PickListenPortError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileHandle`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileId`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileIdMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileSummary`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provisioned`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayAccepted`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RemoveAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Route`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Runtime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEventKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeFlags`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeModule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SaasConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SandboxModeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ScheduledJob`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ServiceSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SessionStoreProvider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SkillsPolicy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StorageInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SystemJobContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TelegramChannelSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TokenSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Tool`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolAttachmentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolExposure`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolGroups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolResult`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolScopeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TransportProfile`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAccess`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAutomationSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Turn`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnOutcome`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnStream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`VOICE_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`WeightClass`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`absolute`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`agent_progress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`artifacts`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`chat_surface`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`complete`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`embeddings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`events`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`identity`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`install_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`installed_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`memory`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`process`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`profiles`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`providers`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`run_from_args`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`schema_for_rpc_method`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`seams`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`skill_registry`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`stream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+
+The compiled capability report describes this build:
+
+```json
+{
+ "schema_version": 1,
+ "configuration_resolved": true,
+ "compiled_features": {
+ "channels": true,
+ "crash-reporting": false,
+ "default": true,
+ "documents": false,
+ "e2e-test-support": false,
+ "file-logging": true,
+ "flows": true,
+ "hosting": false,
+ "http-server": true,
+ "inference": false,
+ "mcp": true,
+ "media": true,
+ "modules": true,
+ "rss-bench": false,
+ "runtime-node": false,
+ "scheduler-gate": true,
+ "skills": true,
+ "storage-file": false,
+ "storage-mongodb": false,
+ "storage-sqlite": false,
+ "tinymemes": true,
+ "voice": false,
+ "web3": false,
+ "whatsapp-web": false
+ },
+ "domains": [
+ "agent",
+ "memory",
+ "threads",
+ "config",
+ "security",
+ "flows",
+ "skills",
+ "channels",
+ "inference",
+ "integrations",
+ "automation",
+ "runtimes",
+ "platform"
+ ],
+ "services": [
+ "harness_init"
+ ],
+ "tool_groups": {
+ "audio": "withheld",
+ "coding": "withheld",
+ "composio": "withheld",
+ "docs": "withheld",
+ "documents": "withheld",
+ "goals": "withheld",
+ "mcp": "withheld",
+ "media": "withheld",
+ "scheduling": "withheld",
+ "skills": "withheld",
+ "storage": "withheld",
+ "system": "withheld",
+ "tasks": "withheld",
+ "web3": "withheld",
+ "workflows": "withheld"
+ },
+ "host_kind": "Library",
+ "max_agents": 1024,
+ "defaults": {
+ "model": {
+ "temperature": 0.7,
+ "max_tokens": null,
+ "top_p": null,
+ "max_iterations": 200
+ },
+ "provider_model": "openrouter/deepseek/deepseek-v4-flash",
+ "routed_provider": false,
+ "sandbox": "None",
+ "approval_gate": true,
+ "include_user_skills": false,
+ "has_skills_root": false,
+ "mcp_servers": 0,
+ "templates": []
+ },
+ "configuration": {
+ "autonomy_enabled": true,
+ "privacy": "Standard",
+ "secrets_encrypted": true,
+ "cron_enabled": true,
+ "learning": {
+ "build_beliefs_every": 10,
+ "learnings_limit": 8
+ },
+ "has_tool_rules": false
+ },
+ "storage": {
+ "source": "workspace",
+ "driver": null,
+ "configured": false
+ },
+ "modules": [],
+ "weight": "custom"
+}
+```
diff --git a/gitbooks/developing/embed/api-reference.md b/gitbooks/developing/embed/api-reference.md
new file mode 100644
index 0000000000..54d363ad22
--- /dev/null
+++ b/gitbooks/developing/embed/api-reference.md
@@ -0,0 +1,54 @@
+---
+description: "Use local rustdoc and source-derived indexes for the complete Embed public surface."
+---
+
+# Embedding API reference
+
+Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+
+The crate is currently `publish = false`; docs.rs links are a publication metadata target, not a claim that a live package reference exists. Local rustdoc and [canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) are the current complete reference.
+
+## Generated inventories
+
+- [API index](api-index.md): names exported by the public facade and a versioned runtime report.
+- [Machine-readable API index](api-index.json): export names, builder signatures, capabilities and page paths.
+- [RuntimeBuilder setters](builder-setters.md): current public consuming setters with source locations.
+- [Compiled feature matrix](capability-matrix.md): the actual core gates from the default-feature capability-report executable.
+- [Cookbook](cookbook.md): example titles, run modes and required named facade features from source headers.
+
+The generated setter list is the authoritative knob inventory. It excludes static presets and borrowed inspection/build/run methods; those belong in local rustdoc. Core compiled gates, runtime module/domain selection and named facade exports are separate availability layers.
+
+## Public surface by purpose
+
+| Purpose | API starting point |
+| --- | --- |
+| Boot and inspect a host | `RuntimeBuilder`, `Runtime`, `RuntimeInfo` |
+| Register and remove scoped agents | `AgentSpec`, `Agent`, `AgentDefinitionSpec`, `RemoveAgent` |
+| Configure execution and decisions | `Access`, `SandboxModeSpec`, `Approvals`, `ApprovalHandler` |
+| Execute or stream native turns | `Turn`, `TurnOutcome`, `TurnStream`, `StreamEvent` |
+| Supply custom model adapters | `Provider` and `providers::ChatModel` |
+| Stateless generation | `Completer`, `CompletionRequest`, structured response helpers |
+| Typed non-turn domains | Memory and cron facades, config/auth/artifacts/chat surface |
+| Replace infrastructure ports | `seams`, `session_store`, memory engine and provider contracts |
+| Serve isolated customer profiles | `ProfileRuntime`, `ProfileHandle`, `SaasConfig` |
+
+## Versioned capability data
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The report's schema version is explicit. Read its fields rather than inferring capabilities from preset names, and handle future schema changes deliberately. It omits endpoint, credential, prompt and workspace values so hosts can expose build metadata without exposing private configuration.
diff --git a/gitbooks/developing/embed/architecture.md b/gitbooks/developing/embed/architecture.md
new file mode 100644
index 0000000000..369b9a2c8c
--- /dev/null
+++ b/gitbooks/developing/embed/architecture.md
@@ -0,0 +1,68 @@
+---
+description: "The host composes infrastructure around one core; agents derive scoped contexts over its runtime."
+---
+
+# Embedding architecture
+
+Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+
+## Ownership boundaries
+
+| Component | Owns |
+| --- | --- |
+| Your application | UI/HTTP transport, user authentication, supplied credentials, application tools and resource lifetimes |
+| OpenHuman core and Embed facade | Runtime composition, per-agent context, policy, approvals, sandbox selection and typed domain calls |
+| TinyAgents | Model/tool loop, parsing, dialects, durable sessions and transcript replay |
+| TinyInference | Native model/provider contracts and generic ordered fallback |
+| TinyTools | Shared tool traits and contract types |
+| Storage and module libraries | Their backend/module implementations; OpenHuman adapts and orchestrates them |
+
+The library chain is core → Embed → TinyHumans → RPC → app/CLI/TUI. Shipped hosts depend on the layer immediately below them and use its curated facades. Embed users should not build new integrations on doc-hidden `__host` internals.
+
+## Runtime composition versus agent scope
+
+Cargo features decide which implementations exist in an artifact. Runtime domains, services, tool groups and module selection narrow those compiled choices. Agent specs narrow the runtime further and add provider, access, prompt, skills, MCP and action-directory choices.
+
+A turn dispatches through the agent's native context, not through JSON-RPC or an operator fallback. Recursive child contexts inherit the parent host overrides, including custom provider and hook composition, while independent sibling agents remain separately scoped.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs), including runtime construction, imports and fixture setup.
+
+## Lifetime and isolation
+
+An agent handle keeps the core alive after the runtime handle is dropped. Explicit removal marks that instance removed, cancels turns and callbacks, denies parked approvals and clears its state/MCP registration. The ID remains reserved through cleanup, including natural last-handle destruction and cancellation of a started removal. Pointer-checked release prevents an old retained instance from removing a newer registry entry.
+
+Agent separation is not credential separation: all ordinary runtime agents share the operator's config path and credential root. Use [profiles](concepts/profiles-saas.md) for independently authenticated users. See [storage architecture](../architecture/storage.md) for scope/driver ownership and [agent harness architecture](../architecture/agent-harness.md) for session execution.
diff --git a/gitbooks/developing/embed/builder-setters.md b/gitbooks/developing/embed/builder-setters.md
new file mode 100644
index 0000000000..f2cded84d6
--- /dev/null
+++ b/gitbooks/developing/embed/builder-setters.md
@@ -0,0 +1,48 @@
+# RuntimeBuilder setters
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+
+- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L343): `pub fn access(mut self, access: Access) -> Self`
+- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L300): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`
+- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L151): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`
+- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L320): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`
+- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L186): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`
+- [`backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L225): `pub fn backend_transport(mut self, transport: Arc<dyn BackendTransport>) -> Self`
+- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L330): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L444): `pub fn config(mut self, config: Config) -> Self`
+- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L308): `pub fn config_source(mut self, source: ConfigSource) -> Self`
+- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L415): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L211): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`
+- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L170): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`
+- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L374): `pub fn domains(mut self, domains: DomainSet) -> Self`
+- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L391): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`
+- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L206): `pub fn learning(mut self, value: super::LearningSettings) -> Self`
+- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L413): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`
+- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L418): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`
+- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L424): `pub fn listen_port(mut self, port: u16) -> Self`
+- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L464): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`
+- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L263): `pub fn max_agents(mut self, limit: usize) -> Self`
+- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L181): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`
+- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L239): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`
+- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L160): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L156): `pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self`
+- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L430): `pub fn post_turn_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self`
+- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L196): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`
+- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L336): `pub fn provider(mut self, provider: Provider) -> Self`
+- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L165): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`
+- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L201): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`
+- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L444): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`
+- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L362): `pub fn services(mut self, services: ServiceSet) -> Self`
+- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L434): `pub fn session(mut self, session: Session) -> Self`
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L254): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`
+- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L175): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`
+- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L457): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`
+- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L401): `pub fn token(mut self, token: TokenSource) -> Self`
+- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L383): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`
+- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L437): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook>) -> Self`
+- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L422): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`
+- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L191): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`
+- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L273): `pub fn workspace(mut self, workspace: Workspace) -> Self`
+- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L287): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`
diff --git a/gitbooks/developing/embed/capability-matrix.md b/gitbooks/developing/embed/capability-matrix.md
new file mode 100644
index 0000000000..aba183fbf7
--- /dev/null
+++ b/gitbooks/developing/embed/capability-matrix.md
@@ -0,0 +1,32 @@
+# Compiled feature matrix
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+
+| Cargo feature | Compiled in this build |
+| --- | --- |
+| `channels` | Yes |
+| `crash-reporting` | No |
+| `default` | Yes |
+| `documents` | No |
+| `e2e-test-support` | No |
+| `file-logging` | Yes |
+| `flows` | Yes |
+| `hosting` | No |
+| `http-server` | Yes |
+| `inference` | No |
+| `mcp` | Yes |
+| `media` | Yes |
+| `modules` | Yes |
+| `rss-bench` | No |
+| `runtime-node` | No |
+| `scheduler-gate` | Yes |
+| `skills` | Yes |
+| `storage-file` | No |
+| `storage-mongodb` | No |
+| `storage-sqlite` | No |
+| `tinymemes` | Yes |
+| `voice` | No |
+| `web3` | No |
+| `whatsapp-web` | No |
diff --git a/gitbooks/developing/embed/concepts/README.md b/gitbooks/developing/embed/concepts/README.md
new file mode 100644
index 0000000000..5262dcd86a
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/README.md
@@ -0,0 +1,26 @@
+---
+description: "The ownership and lifecycle rules behind the Embed public API."
+---
+
+# Concepts
+
+Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+
+- [Runtime](runtime.md): A Runtime owns one initialized core and the process-wide resources that its agents share.
+- [Runtime defaults](runtime-defaults.md): Runtime defaults form the starting point for newly registered agents; explicit agent settings override them.
+- [Agents](agents.md): An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime.
+- [Access and approvals](access-approvals.md): Access configures turn identity and permission policy; the host chooses how parked requests receive decisions.
+- [Providers](providers.md): A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback.
+- [Turns and sessions](turns-sessions.md): A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation.
+- [Tools](tools.md): Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools.
+- [MCP](mcp.md): MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists.
+- [Skills](skills.md): Skills are copied bundles of instructions and resources discovered inside an agent’s own home.
+- [Memory](memory.md): The typed memory facade binds a namespace before learning, retrieving or forgetting records.
+- [Cron](cron.md): Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents.
+- [Channels](channels.md): A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control.
+- [Profiles and SaaS](profiles-saas.md): ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams.
+- [Completer](completer.md): Completer sends stateless model requests without booting a Runtime or entering the agent tool loop.
+- [Hooks and seams](hooks-seams.md): Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries.
+- [Observability](observability.md): Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result.
+- [Testing](testing.md): Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services.
+- [Errors](errors.md): Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances.
diff --git a/gitbooks/developing/embed/concepts/access-approvals.md b/gitbooks/developing/embed/concepts/access-approvals.md
new file mode 100644
index 0000000000..eef15dbe59
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/access-approvals.md
@@ -0,0 +1,80 @@
+---
+description: "Access configures turn identity and permission policy; the host chooses how parked requests receive decisions."
+---
+
+# Access and approvals
+
+`Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+
+The core autonomy policy is disabled by default. Set `config.autonomy.enabled` when you require its command classification, approval gate, allowlist and budget enforcement. Platform isolation and the credential/system-root safety floor have separate responsibilities; a tool group filter is not an operating-system sandbox.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Autonomy policy defaults and installed approval gate | Origin, access tier, grants, trusted roots and scoped decisions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/approvals.rs#approvals -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("approved-marker");
+ let write_provider = support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", marker.display())}).to_string(),
+ )],
+ "approved",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("supervised")
+ .provider(support::route(&write_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: "demo".into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.path().display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(
+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ ),
+ )?;
+ let pending_agent = agent.clone();
+ let turn = tokio::spawn(async move { pending_agent.run("Create a marker").await });
+ let pending = support::eventually("approval", || {
+ agent.approvals().pending().ok()?.into_iter().next()
+ })
+ .await;
+ assert!(!marker.exists(), "execution waits for the host decision");
+ assert_eq!(pending.agent_id.as_deref(), Some("supervised"));
+ agent.approvals().decide(
+ &pending.request_id,
+ openhuman_embed::ApprovalDecision::ApproveOnce,
+ )?;
+ assert_eq!(turn.await??.reply, "approved");
+ assert!(marker.exists());
+ assert!(agent.approvals().pending()?.is_empty());
+ println!("parked write executed only after approval");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified example enables autonomy before building the runtime. It starts a real shell write, observes that no marker exists while the call is parked, and creates it only after `ApproveOnce`. `agent.approvals()` lists and decides only that instance's requests. A removed instance returns an empty pending list and rejects decisions even if the same public ID has been reused.
+
+For asynchronous integration use `AgentSpec::approval_handler` or retain the handle returned by `Agent::handle_approvals`. Dropping a subscription cancels its pending decision future; it does not silently approve the request. Agent removal cancels both builder and live callbacks. Continue with the [approval callback example](../cookbook.md#polling-and-callback-approvals-with-cancellation) and [sandbox guide](../guides/multi-agent.md).
diff --git a/gitbooks/developing/embed/concepts/agents.md b/gitbooks/developing/embed/concepts/agents.md
new file mode 100644
index 0000000000..7037a766eb
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/agents.md
@@ -0,0 +1,59 @@
+---
+description: "An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime."
+---
+
+# Agents
+
+Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+
+Keep `action_dir` separate from the internal workspace. The action directory is where tools act; the agent home stores internal transcripts, skills and other state. The example gives a reviewer and a fixer distinct folders and prompts while sharing one provider connection setup.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Core, shared configuration path and registry capacity | ID, context, prompt, action directory, provider and per-agent stores |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+IDs stay reserved until teardown completes, including while the last handle's destructor is clearing state. `remove_agent(id).await` marks retained handles removed, cancels active turns, denies parked approvals and releases the ID after cleanup. Add `.purge()` only when the agent's persisted home should also be deleted. Cancelling a started removal still performs teardown and a requested purge.
+
+An old polling handle or approval callback never follows a reused ID to its replacement. Active host tools cancel cooperatively and may finish their external work after removal; the host still owns those external lifetimes. See [turns and sessions](turns-sessions.md) and [access and approvals](access-approvals.md).
diff --git a/gitbooks/developing/embed/concepts/channels.md b/gitbooks/developing/embed/concepts/channels.md
new file mode 100644
index 0000000000..6588d7dbe3
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/channels.md
@@ -0,0 +1,93 @@
+---
+description: "A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control."
+---
+
+# Channels
+
+`Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+
+The named Embed `channels` feature is enabled by default. The runtime must also allow the channel family. Create listeners inside the Tokio runtime after their agents have been registered.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Channel implementation, listener registry and runtime domain ceiling | Bound agent, conversation identity and external-message access context |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified Telegram example uses a local Bot API stub, so the channel test does not contact Telegram. Its live mode requires explicit example credentials and remains opt-in.
+
+External messages use `ExternalChannel` origin and a read-only cap. Model-requested writes and other external effects are not parked for approval from the sender. Keep public-chat tools read-only and perform authorized side effects in host code or a separately configured job. When the bound agent is removed, channel work fails as unavailable instead of falling back to the operator. See [channel integration](../integrations/channels.md).
diff --git a/gitbooks/developing/embed/concepts/completer.md b/gitbooks/developing/embed/concepts/completer.md
new file mode 100644
index 0000000000..e97f5077c8
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/completer.md
@@ -0,0 +1,46 @@
+---
+description: "Completer sends stateless model requests without booting a Runtime or entering the agent tool loop."
+---
+
+# Completer
+
+Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+
+A standalone completer does not claim the process runtime slot. An agent-backed completion uses the agent's effective configuration but still has no implicit durable session. Keep conversation state in your application if you need several completion calls to form a conversation.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| No runtime required for a standalone routed Completer | Optional effective agent configuration; no implicit tools or transcript |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/completer.rs#completer -->
+
+```rust
+ let route = support::example_provider(&provider)?;
+ let completer = openhuman_embed::Completer::new(route.route().expect("explicit route").clone());
+ let response = completer
+ .complete(openhuman_embed::CompletionRequest::new(
+ route.model_id().expect("explicit model"),
+ vec![openhuman_embed::ChatMessage::user("Say hello")],
+ ))
+ .await?;
+ assert!(!response.text.is_empty());
+ if support::offline() {
+ assert_eq!(response.text, "completion reply");
+ assert_eq!(support::chat_requests(&provider).await.len(), 1);
+ }
+ println!("{}", response.text);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks that exactly one inference request was made and verifies the returned text. It uses a local provider fixture by default; the source contains the explicit opt-in live route path.
+
+Choose `Agent` when a model should call tools, resume a durable thread or execute with an agent's access context. Choose the structured completion helpers when the host only needs a validated data result. For routes and transport failures see [providers](providers.md) and [errors](errors.md).
diff --git a/gitbooks/developing/embed/concepts/cron.md b/gitbooks/developing/embed/concepts/cron.md
new file mode 100644
index 0000000000..4f2ee929c1
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/cron.md
@@ -0,0 +1,54 @@
+---
+description: "Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents."
+---
+
+# Cron
+
+The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+
+Background scheduling is a runtime service choice. Explicit `run_now` is useful for tests and host-triggered execution without relying on wall-clock scheduling. Keep the agent registered while scheduled work should be available.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cron storage, scheduler service and system-job handlers | Addressed job target and the agent configuration used for its turn |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/cron.rs#cron -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("scheduled"))?;
+ let cron = runtime.cron();
+ let spec = openhuman_embed::JobSpec::agent(
+ "daily",
+ agent.id(),
+ "Say hello",
+ openhuman_embed::JobSchedule::Cron {
+ expr: "0 0 * * *".into(),
+ tz: None,
+ },
+ );
+ let first = cron.upsert(spec.clone())?;
+ assert_eq!(cron.upsert(spec)?.id, first.id);
+ let run = cron.run_now("daily").await?;
+ assert!(run.success, "{}", run.output);
+ if support::offline() {
+ assert!(run.output.contains("hello from the stub"));
+ }
+ assert_eq!(cron.runs("daily", 1)?[0].status, "ok");
+ assert!(cron.remove("daily")?);
+ assert!(cron.list()?.is_empty());
+ println!("cron execution and history verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks stable upsert identity, executes a job immediately, inspects a successful run record, and removes the job. No test waits for a daily schedule to arrive.
+
+Removing or dropping an agent deregisters its context, leaving addressed cron jobs dormant rather than silently running them as the operator. Hosts can register runtime system-job handlers for work they own outside a model turn. Review [runtime configuration](runtime-defaults.md) and [channels](channels.md) when mixing scheduled work with public chat input.
diff --git a/gitbooks/developing/embed/concepts/errors.md b/gitbooks/developing/embed/concepts/errors.md
new file mode 100644
index 0000000000..f7bb71ddfa
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/errors.md
@@ -0,0 +1,61 @@
+---
+description: "Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances."
+---
+
+# Errors
+
+Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+
+A structured `CoreError::Domain` carries a stable kind and `expected_user_state`. Expected stale-session or missing-resource states should be shown as notices rather than treated as internal faults. `Decode` signals a facade/domain shape mismatch; retrying unchanged input does not repair it.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Boot errors, unavailable domains and shared transport setup | Registration errors, scoped domain failures and AgentRemoved on retained handles |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/sandbox_access.rs#sandbox_access -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("attempted-write");
+ let attempted_write = support::tool_call_completion(
+ "write_file",
+ &serde_json::json!({
+ "path": marker.display().to_string(), "content": "example"
+ })
+ .to_string(),
+ );
+ let read_provider = support::scripted_provider(vec![attempted_write], "write refused").await;
+ let read = runtime.agent(
+ AgentSpec::new("read")
+ .provider(support::route(&read_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(openhuman_embed::Access::readonly())
+ .definition(
+ AgentDefinitionSpec::new().sandbox(openhuman_embed::SandboxModeSpec::ReadOnly),
+ ),
+ )?;
+ let full = runtime.agent(AgentSpec::new("full").access(openhuman_embed::Access::full()))?;
+ assert_ne!(read.config().autonomy.level, full.config().autonomy.level);
+ assert!(!read.run("Write a marker").await?.reply.is_empty());
+ assert!(
+ !marker.exists(),
+ "readonly sandbox must refuse the attempted write"
+ );
+ let requests = support::chat_requests(&read_provider).await;
+ assert!(!support::tool_names(&requests[0]).contains(&"write_file".to_string()));
+ println!("readonly sandbox refused a model-requested write");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example's refused write is handled as a tool result while the turn can still finish with a reply. Do not assume every rejected tool action is a failed turn. Conversely, a finished stream can contain an error; always inspect `StreamEvent::Finished`.
+
+Bearer routes refuse non-TLS remote endpoints before sending credentials. `BACKEND_UNAVAILABLE` means the embed-only host has no backend transport installed; check the host layer before rotating keys. Agent removal makes later turns on retained handles return `AgentRemoved`, even when its ID now belongs to another instance. See [troubleshooting](../troubleshooting.md) and [provider integration](../integrations/openai-compatible.md).
diff --git a/gitbooks/developing/embed/concepts/hooks-seams.md b/gitbooks/developing/embed/concepts/hooks-seams.md
new file mode 100644
index 0000000000..cbbe25c8d4
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/hooks-seams.md
@@ -0,0 +1,45 @@
+---
+description: "Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries."
+---
+
+# Hooks and seams
+
+Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+
+Post-turn and tool hooks can be registered runtime-wide or on one agent. Agent hooks compose with parent runtime hooks and do not leak into sibling contexts. Use stable hook names to replace or remove runtime registrations through the live API; changes apply to subsequent turns.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Shared port implementations and named global hook registrations | Scoped hooks and host overrides inherited by recursive child contexts |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/hooks.rs#hooks -->
+
+```rust
+ let count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let agent = runtime.agent(
+ AgentSpec::new("hooked").post_turn_hook(std::sync::Arc::new(Counter(count.clone()))),
+ )?;
+ let sibling = runtime.agent(AgentSpec::new("sibling"))?;
+ assert!(!agent.run("Hello hook").await?.reply.is_empty());
+ support::eventually("post-turn hook", || {
+ (count.load(std::sync::atomic::Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ assert!(!sibling.run("Hello sibling").await?.reply.is_empty());
+ assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
+ println!("post-turn hook isolated to its agent");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example verifies that an agent-local post-turn counter observes the configured agent and not its sibling. Runtime live add/remove behavior is demonstrated in the [runtime events example](../cookbook.md#runtime-lifecycle-events-and-live-hook-registration).
+
+Removing or replacing a builder-installed named hook through the runtime API affects that registration too; the runtime tracks and restores prior process slots when its seam ownership ends. Keep hooks fast, cancellation-aware and free of sensitive logging. Use the generated [setter list](../builder-setters.md) and [API reference](../api-reference.md) for the actual port signatures.
diff --git a/gitbooks/developing/embed/concepts/mcp.md b/gitbooks/developing/embed/concepts/mcp.md
new file mode 100644
index 0000000000..4bc0c350fd
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/mcp.md
@@ -0,0 +1,74 @@
+---
+description: "MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists."
+---
+
+# MCP
+
+MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+
+Enable the named Embed `mcp` Cargo feature for `McpServer` and the agent setter. The default core may already contain MCP code, but a core capability flag does not activate a separately gated Embed API. Runtime domain selection must also allow the MCP family.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Compiled MCP implementation and runtime domain ceiling | Server configuration, auth, discovery and allowed remote tools |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses a real loopback protocol stub: it verifies initialization, `tools/list`, and `tools/call`, then checks that the model saw the remote result. It does not call an external MCP service or require credentials.
+
+Tool allowlists reduce the remote catalog before model disclosure. Server authentication remains host-owned input, and remote tool side effects still pass through the relevant execution/access policy. Removing the agent evicts its MCP host after old-instance teardown, before the ID can be reused. See the [MCP integration](../integrations/mcp.md) for deployment setup.
diff --git a/gitbooks/developing/embed/concepts/memory.md b/gitbooks/developing/embed/concepts/memory.md
new file mode 100644
index 0000000000..02ac00af99
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/memory.md
@@ -0,0 +1,43 @@
+---
+description: "The typed memory facade binds a namespace before learning, retrieving or forgetting records."
+---
+
+# Memory
+
+`Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+
+A custom `memory_engine` can replace the default engine for a host or test. An agent's `MemoryBinding` configures its own memory context, while the runtime owns engine availability. Scope namespaces separately from provider/model choices: changing inference does not move a record to another tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Memory engine seam and available memory domain | MemoryBinding, acting context and bound namespace |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/memory.rs#memory -->
+
+```rust
+ let acme = runtime.memory("team:acme")?;
+ let other = runtime.memory("team:other")?;
+ let params = serde_json::from_value(serde_json::json!({"text":"Acme ships on Fridays"}))?;
+ let learned = acme.learn(params).await?;
+ let hits = acme.get(vec![learned.id.clone()]).await?;
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].meta.namespace.to_string(), "team:acme");
+ assert!(other.get(vec![learned.id.clone()]).await?.is_empty());
+ assert_eq!(other.forget(vec![learned.id.clone()]).await?.forgotten, 0);
+ assert_eq!(acme.forget(vec![learned.id]).await?.forgotten, 1);
+ println!("memory learning, tenant isolation and deletion verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses the reference in-memory engine and proves that another namespace cannot retrieve or forget the first namespace's record. Forgetting succeeds only through the owning namespace. This is a scope test, not a persistence claim; choose a durable engine/backend for application state that must survive restarts.
+
+Background conversation ingestion can run independently of a completed turn. Tests should disable unrelated learning/ingest activity when asserting ephemeral-workspace cleanup. See [runtime defaults](runtime-defaults.md), [storage drivers](../integrations/storage-drivers.md), and the [memory architecture](../../architecture/memory.md).
diff --git a/gitbooks/developing/embed/concepts/observability.md b/gitbooks/developing/embed/concepts/observability.md
new file mode 100644
index 0000000000..26c78c0d28
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/observability.md
@@ -0,0 +1,73 @@
+---
+description: "Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result."
+---
+
+# Observability
+
+Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+
+Runtime events contain lifecycle metadata, not user prompts or model output. Detailed text/tool progress belongs to the explicitly requested turn stream. A bounded event receiver reports lag explicitly rather than silently claiming that it delivered every event.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Runtime sequence, content-safe lifecycle feed and registered-agent filter | Per-call turn correlation and opt-in text/tool progress stream |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/runtime_events.rs#runtime_events -->
+
+```rust
+ let mut events = runtime.events();
+ let count = Arc::new(AtomicUsize::new(0));
+ runtime.post_turn_hook("live-counter", Some(Arc::new(Counter(count.clone()))));
+ let agent = runtime.agent(AgentSpec::new("observed"))?;
+ assert_eq!(agent.run("private payload one").await?.reply, "event reply");
+ support::eventually("runtime hook", || {
+ (count.load(Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ runtime.post_turn_hook("live-counter", None);
+ assert_eq!(agent.run("private payload two").await?.reply, "event reply");
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 1,
+ "removed hook stops observing turns"
+ );
+ runtime.remove_agent(agent.id()).await?;
+ let mut previous = 0;
+ let (mut added, mut started, mut ended) = (0, 0, 0);
+ loop {
+ let event =
+ tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()).await??;
+ assert!(event.sequence > previous);
+ previous = event.sequence;
+ assert_eq!(event.agent_id.as_deref(), Some("observed"));
+ assert!(!serde_json::to_string(&event)?.contains("private payload"));
+ match event.kind {
+ RuntimeEventKind::AgentAdded => added += 1,
+ RuntimeEventKind::TurnStarted => {
+ assert!(event.turn_id.is_some());
+ started += 1;
+ }
+ RuntimeEventKind::TurnEnded { success } => {
+ assert!(success);
+ ended += 1;
+ }
+ RuntimeEventKind::AgentRemoved => break,
+ _ => {}
+ }
+ }
+ assert_eq!((added, started, ended), (1, 2, 2));
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks ordered add/start/end/remove events and confirms that private prompt text is absent from serialized metadata. Approval events are filtered to agents registered on this runtime. Correlation follows the effective origin thread; a request's later decision keeps its original turn correlation after the turn has ended.
+
+When simultaneous turns share an origin thread, approval correlation can be ambiguous and its turn ID is absent rather than guessed. Handle receiver lag by refreshing state, and do not send text from `AgentProgress` to content-free analytics. See [turns and sessions](turns-sessions.md), [approvals](access-approvals.md), and [testing](testing.md).
diff --git a/gitbooks/developing/embed/concepts/profiles-saas.md b/gitbooks/developing/embed/concepts/profiles-saas.md
new file mode 100644
index 0000000000..7c1e8ef868
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/profiles-saas.md
@@ -0,0 +1,61 @@
+---
+description: "ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams."
+---
+
+# Profiles and SaaS
+
+Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+
+Profile mode claims the process separately from ordinary `Runtime` and `Harness`. Its root must satisfy the boot guard: absolute, existing, outside the operator's workspace and not world-writable. Remove single-user workspace/token environment variables before booting a profile server.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| One profile host, shared compiled core and managed backend transport | Per-profile credential, workspace, threads, memory and event access |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example creates Alice and Bob with the same thread name and verifies that each transcript contains only its own note. Handles keep their profiles open; release/idle eviction can close a profile only after those handles are dropped.
+
+Production managed calls need the TinyHumans transport installed by the host layer. `ProfileHandle::call` exposes the reviewed user surface rather than arbitrary operator controllers. Profiles do not make a shared file-system action directory safe automatically; provision external application resources per user too. See [SaaS deployment guide](../guides/saas-multi-tenant.md) and [SaaS architecture](../../saas-profiles.md).
diff --git a/gitbooks/developing/embed/concepts/providers.md b/gitbooks/developing/embed/concepts/providers.md
new file mode 100644
index 0000000000..d04e5f74de
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/providers.md
@@ -0,0 +1,80 @@
+---
+description: "A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback."
+---
+
+# Providers
+
+A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+
+Named workload roles bind an adapter to selections such as `hint:coding`. The example proves that the role-pinned model bypasses the primary fallback chain. These pins are explicit host configuration; they do not ask the model to decide its own provider.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default route/model and native adapter chain | Provider override, model selection and workload hint |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Ordered fallback advances only on eligible provider failures before visible output. Validation or unsupported-input failures stop the chain. Once text, reasoning or tool-call content becomes visible, the chosen stream keeps its identity and a later failure is reported without switching providers. Requests, options, correlation metadata and cancellation remain attached to the selected adapter.
+
+Use HTTPS when sending bearer credentials; loopback HTTP is supported for local test/model servers. Managed inference needs the TinyHumans host transport and a runtime credential. See [OpenAI-compatible integration](../integrations/openai-compatible.md), [managed integration](../integrations/tinyhumans-managed.md), and [local models](../integrations/local-models.md).
diff --git a/gitbooks/developing/embed/concepts/runtime-defaults.md b/gitbooks/developing/embed/concepts/runtime-defaults.md
new file mode 100644
index 0000000000..13a56ef3b5
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/runtime-defaults.md
@@ -0,0 +1,62 @@
+---
+description: "Runtime defaults form the starting point for newly registered agents; explicit agent settings override them."
+---
+
+# Runtime defaults
+
+The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+
+`Runtime::defaults()` returns a snapshot. Runtime default setters affect agents created afterward; existing agents retain the configuration they were built with. Configure an explicit agent override when its behavior must remain independent of future runtime defaults.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default provider, access and generation settings | Explicit override captured when AgentSpec is registered |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks the request bodies actually received by both providers, including model, temperature and maximum tokens. This distinction matters when testing a configuration change: a correct defaults snapshot alone does not prove that inference received those values.
+
+Use the generated [builder setters](../builder-setters.md) for the current knob list. [Configuration and installation](../installation.md) explain runtime configuration discovery; [providers](providers.md) cover route selection and native models.
diff --git a/gitbooks/developing/embed/concepts/runtime.md b/gitbooks/developing/embed/concepts/runtime.md
new file mode 100644
index 0000000000..2270f91ceb
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/runtime.md
@@ -0,0 +1,40 @@
+---
+description: "A Runtime owns one initialized core and the process-wide resources that its agents share."
+---
+
+# Runtime
+
+A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+
+The process guard rejects a second runtime with `RuntimeError::AlreadyRunning`. Independent customer credentials and workspaces require [profiles](profiles-saas.md), rather than several ordinary runtimes. `Harness` is the one-agent shorthand and exposes its underlying runtime and agent if you later need more agents.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cargo gates and selected domains/services | Provider, prompt, working folder and tool scope |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+`RuntimeBuilder::describe()` reports a plan before boot; `Runtime::capabilities()` reports resolved configuration afterward. The versioned metadata excludes credentials, endpoints, prompts and workspace paths. Use its `configuration_resolved` flag when deciding whether to treat an inspection result as effective configuration.
+
+Dropping the runtime handle does not tear down the core while an agent still holds it. Drop listeners, agents and the runtime before restarting the host in the same process. See [architecture](../architecture.md), [defaults](runtime-defaults.md), and the generated [builder setters](../builder-setters.md).
diff --git a/gitbooks/developing/embed/concepts/skills.md b/gitbooks/developing/embed/concepts/skills.md
new file mode 100644
index 0000000000..e95f500cc4
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/skills.md
@@ -0,0 +1,47 @@
+---
+description: "Skills are copied bundles of instructions and resources discovered inside an agent\u2019s own home."
+---
+
+# Skills
+
+A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+
+Enable the named Embed `skills` feature for skill setters and registry access. Library agents hide the operator's user skill directory unless `include_user_skills(true)` is explicitly selected. Treat skill installation as part of the agent's configuration, rather than reading arbitrary operator files into every tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Skill registry seam and default user-skill policy | Copied bundles, discovery context and explicit user-skill opt-in |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/skills.rs#skills -->
+
+```rust
+ let skills = tempfile::tempdir()?;
+ std::fs::create_dir(skills.path().join("review"))?;
+ std::fs::write(skills.path().join("review/SKILL.md"),
+ "---\nname: review\ndescription: Review Rust functions carefully.\n---\nCheck error paths.\n")?;
+ let agent = runtime.agent(AgentSpec::new("skilled").skills_dir(skills.path()))?;
+ let copied = agent
+ .workspace_dir()
+ .join("agents/skilled/skills/review/SKILL.md");
+ assert_eq!(
+ std::fs::read_to_string(&copied)?,
+ std::fs::read_to_string(skills.path().join("review/SKILL.md"))?
+ );
+ assert!(!std::fs::symlink_metadata(copied)?.file_type().is_symlink());
+ assert!(!agent.run("Hello").await?.reply.is_empty());
+ println!("skill bundle copied without symlinks");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example writes a bundle, registers an agent, checks the copied contents and verifies that the destination is not a symlink. Use the same directory layout for production bundles; do not depend on the fixture's temporary directory lifetime.
+
+A resumed session's prompt is frozen, so adding or editing a bundle does not rewrite an existing conversation's recorded prefix. Start a new session when you want updated instructions to become visible. See [turns and sessions](turns-sessions.md) and the generated [builder setters](../builder-setters.md) for runtime policy knobs.
diff --git a/gitbooks/developing/embed/concepts/testing.md b/gitbooks/developing/embed/concepts/testing.md
new file mode 100644
index 0000000000..883138743b
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/testing.md
@@ -0,0 +1,80 @@
+---
+description: "Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services."
+---
+
+# Testing
+
+The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+
+A native `ChatModel<()>` stub is useful for provider selection and cancellation tests without HTTP. Protocol-level stubs remain useful for OpenAI-compatible routing, MCP or messaging transport behavior. Pick the boundary whose behavior your host needs to verify.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Offline configuration, mock backend and injected model/engine ports | Isolated temp action directories, deterministic IDs and scoped assertions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Run the offline example suite with `node scripts/run-embed-examples.mjs`; it clears inherited credentials/workspaces and uses one union feature graph for all examples. Run embed unit/integration tests with `cargo test -p openhuman-embed --features mcp,skills,channels,storage-sqlite --lib --tests -- --test-threads=1`.
+
+Build your Tokio workers with the documented large stack constants for nested agent turns. Use channels, cancellation guards and bounded waits to prove lifecycle transitions instead of sleeps. The [mock-backend guide](../guides/mock-backend-testing.md) covers host fixtures, and [troubleshooting](../troubleshooting.md) distinguishes compile gates from runtime availability.
diff --git a/gitbooks/developing/embed/concepts/tools.md b/gitbooks/developing/embed/concepts/tools.md
new file mode 100644
index 0000000000..b8465163dc
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/tools.md
@@ -0,0 +1,59 @@
+---
+description: "Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools."
+---
+
+# Tools
+
+An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+
+`AgentSpec::tools` is a per-turn factory returning `HostTurnTools`. Factories can attach the turn's context to their executors without sharing mutable tool state across unrelated sessions. Import `Tool` and `ToolResult` from `openhuman_embed` so their types match the vendored implementation used by the core.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Domain/tool-group ceiling and shared execution policy | ToolScopeSpec, advertised host belt, attachments and prompt |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example drives an actual host tool call and inspects the provider's advertised catalog: it contains only `host_ping`, which executes exactly once. A host executor remains responsible for authorizing its own application operations. Catalog visibility narrows what the model sees; it is not a substitute for permission checks or sandboxing.
+
+Runtime tool hooks apply across agents; local hooks observe only their configured agent. Tool attachments can be added and removed for later turns, while existing durable sessions retain recorded declarations. See [hooks](hooks-seams.md), [MCP](mcp.md), and [access and approvals](access-approvals.md).
diff --git a/gitbooks/developing/embed/concepts/turns-sessions.md b/gitbooks/developing/embed/concepts/turns-sessions.md
new file mode 100644
index 0000000000..2e5f7c61b1
--- /dev/null
+++ b/gitbooks/developing/embed/concepts/turns-sessions.md
@@ -0,0 +1,65 @@
+---
+description: "A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation."
+---
+
+# Turns and sessions
+
+`Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+
+`Agent::stream` returns a bounded `TurnStream`. Drain it while the turn is running: progress includes visible deltas and tool lifecycle notifications, followed by one `StreamEvent::Finished` containing the typed final result. Dropping the stream cancels its turn and recursive child work cooperatively.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Session store provider and shared progress/event infrastructure | Durable agent/thread identity, transcript and per-call cancellation |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The stream example checks that deltas precede the final result and that collected and streaming replies agree. A cancellation token passed to a turn is preserved by streaming; cancellation unblocks forwarding even when the consumer has stopped draining a full buffer.
+
+The harness derives transcript paths from the thread and agent IDs without a timestamp. Resumed sessions reuse their recorded system prompt and tool declarations; edits to prompts, skills or integrations apply to new sessions. Compaction seals a generation and opens a child instead of erasing history. See [observability](observability.md) for session IDs versus per-call turn IDs, and [API reference](../api-reference.md) for the session-store port.
diff --git a/gitbooks/developing/embed/cookbook.md b/gitbooks/developing/embed/cookbook.md
new file mode 100644
index 0000000000..6b7caefc55
--- /dev/null
+++ b/gitbooks/developing/embed/cookbook.md
@@ -0,0 +1,181 @@
+# Cookbook
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+
+## Polling and callback approvals with cancellation
+
+Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example approvals`
+
+## Stable capability metadata before and after boot
+
+Stable capability metadata before and after boot.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example capability_report`
+
+## Stateless completion without booting an agent runtime
+
+Stateless completion without booting an agent runtime.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example completer`
+
+## Run and inspect an agent cron job
+
+Run and inspect an agent cron job.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example cron`
+
+## Native custom providers, fallback and workload role pins
+
+Inject deterministic native models and prove fallback and role selection without inference HTTP.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) · offline; no live inference path.
+
+Run: `cargo run -p openhuman-embed --example custom_provider`
+
+## Runtime defaults and per-agent overrides
+
+Runtime defaults and per-agent overrides.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example defaults_overrides`
+
+## A per-agent post-turn hook observes completed turns
+
+A per-agent post-turn hook observes completed turns.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example hooks`
+
+## Host tools and HostOnly keep the advertised tool catalog exact
+
+Host tools and HostOnly keep the advertised tool catalog exact.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example host_tools`
+
+## Lean runtime without background services
+
+Lean runtime without background services.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) · offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.
+
+Run: `cargo run -p openhuman-embed --example lean_headless`
+
+## Connect an actual MCP protocol stub over loopback
+
+Connect an actual MCP protocol stub over loopback.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) · offline with loopback stubs; no live path. · feature: mcp
+
+Run: `cargo run -p openhuman-embed --example mcp --features mcp`
+
+## Tenant scoped memory facade with an in-memory engine
+
+Tenant scoped memory facade with an in-memory engine.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example memory`
+
+## SaaS profiles isolate conversation history
+
+SaaS profiles isolate conversation history.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example profiles`
+
+## Hello agent: a prompt in and a reply out
+
+Hello agent: a prompt in and a reply out.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example run_turn`
+
+## Runtime lifecycle events and live hook registration
+
+Observe ordered metadata and add/remove a runtime-wide hook while agents keep running.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs) · offline with a loopback provider; no live path.
+
+Run: `cargo run -p openhuman-embed --example runtime_events`
+
+## Access tiers and explicit sandbox choices
+
+Access tiers and explicit sandbox choices.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example sandbox_access`
+
+## Embed an agent behind a host-owned HTTP server
+
+Embed an agent behind a host-owned HTTP server.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example server`
+
+## Copy a skill bundle into its agent workspace
+
+Copy a skill bundle into its agent workspace.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL. · feature: skills
+
+Run: `cargo run -p openhuman-embed --example skills --features skills`
+
+## SQLite writes and MongoDB configuration through Embed
+
+Open a real local SQLite backend and describe a MongoDB deployment without connecting.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) · offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb. · feature: storage-sqlite
+
+Run: `cargo run -p openhuman-embed --example storage --features storage-sqlite`
+
+## Streaming progress with a draining receiver
+
+Streaming progress with a draining receiver.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example streaming`
+
+## Structured output parsed and checked against the request
+
+Structured output parsed and checked against the request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/structured_output.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example structured_output`
+
+## Telegram channel answered by its bound agent via a local Bot API
+
+Telegram channel answered by its bound agent via a local Bot API.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) · offline with loopback stubs; no live path. · feature: channels
+
+Run: `cargo run -p openhuman-embed --example telegram --features channels`
+
+## Two agents with independent prompts and working folders
+
+Two agents with independent prompts and working folders.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example two_agents`
diff --git a/gitbooks/developing/embed/faq.md b/gitbooks/developing/embed/faq.md
new file mode 100644
index 0000000000..ec7e19cf55
--- /dev/null
+++ b/gitbooks/developing/embed/faq.md
@@ -0,0 +1,41 @@
+---
+description: "Answers to common host, lifecycle, feature and provider choices."
+---
+
+# Embedding FAQ
+
+## Can I create more than one runtime?
+
+An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See [runtime](concepts/runtime.md) and [profiles](concepts/profiles-saas.md).
+
+## Is an agent clone an independent agent?
+
+No. It is another handle to the same agent instance, context and state. Register a different `AgentSpec` ID for a separate agent. Runtime credentials are still shared, so agent IDs alone do not isolate authenticated customers.
+
+## Does lean mean fewer dependencies?
+
+`RuntimeBuilder::lean()` selects a smaller runtime surface. Cargo still compiles enabled gates; use `--no-default-features` and explicit named gates for graph reduction. The [compiled matrix](capability-matrix.md) reports one fixed default build, and the [lean guide](guides/lean-headless.md) separates those controls.
+
+## Why do MCP or skills methods disappear while the report says they are compiled?
+
+The report describes core Cargo gates. Named Embed gates control facade exports too. Enable Embed's `mcp` or `skills` feature for their setters/re-exports, even when core defaults already compile the implementation. `channels` is named in Embed defaults.
+
+## Can I supply an in-process model without HTTP?
+
+Yes: `Provider::custom` takes the native `ChatModel<()>` contract. A provider can add an ordered fallback chain and explicit workload role pins. [Providers](concepts/providers.md) describes the rule that fallback stops after visible output.
+
+## Do I need the backend for every agent turn?
+
+An explicit BYOK/local/native provider can run independently of hosted inference. Hosted integrations, voice, billing or other backend surfaces need an installed backend transport and a credential. Use the [TinyHumans layer](integrations/tinyhumans-managed.md) for managed calls; Embed alone reports backend unavailable.
+
+## Can an old handle control a replacement with the same ID?
+
+No. Removal binds cancellation, callbacks and polling handles to the original lifecycle. It keeps the ID reserved until teardown/purge completes; later old handles cannot decide replacement approvals or send replacement turns. Dropping a handle does not purge its persisted home.
+
+## Why did a prompt or tool change not affect a resumed thread?
+
+A resumed session reuses recorded system messages and tool declarations. Start a new session for the changed prompt/tool catalog. Compaction preserves prior generations; it does not rewrite the old conversation. See [turns and sessions](concepts/turns-sessions.md).
+
+## Where is the complete builder knob list?
+
+[RuntimeBuilder setters](builder-setters.md) is generated from actual consuming public setters, with source signatures. Host/weight presets and non-setter methods are intentionally documented through [API reference](api-reference.md).
diff --git a/gitbooks/developing/embed/guides/README.md b/gitbooks/developing/embed/guides/README.md
new file mode 100644
index 0000000000..b94b18d716
--- /dev/null
+++ b/gitbooks/developing/embed/guides/README.md
@@ -0,0 +1,17 @@
+---
+description: "Build a chatbot, host multiple agents, serve profiles, or test an embedded runtime."
+icon: code
+---
+
+# Embedding guides
+
+Choose the guide that matches your host:
+
+- [CLI chatbot](cli-chatbot.md): create an agent and collect or stream its reply.
+- [Multiple agents](multi-agent.md): give agents independent prompts, access, and working folders.
+- [SaaS with multiple tenants](saas-multi-tenant.md): isolate user state through profiles.
+- [Deploy a server](deploy-server.md): call an embedded agent from your HTTP host.
+- [Lean and headless hosts](lean-headless.md): select runtime services and Cargo features separately.
+- [Test with a mock backend](mock-backend-testing.md): run the entire example suite offline.
+
+Start with [Embedding](../README.md) for the library boundary and quickstart. See [Integrations](../integrations/README.md) for providers, storage, MCP, and channels.
diff --git a/gitbooks/developing/embed/guides/cli-chatbot.md b/gitbooks/developing/embed/guides/cli-chatbot.md
new file mode 100644
index 0000000000..281c9588e5
--- /dev/null
+++ b/gitbooks/developing/embed/guides/cli-chatbot.md
@@ -0,0 +1,74 @@
+---
+description: "Collect a reply or consume progress events in a Rust command-line host."
+icon: code
+---
+
+# CLI chatbot
+
+Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example run_turn` from the repository root. It uses a loopback provider and temporary state. The [complete run_turn example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) includes imports, runtime construction, and offline setup.
+
+For incremental output, consume `agent.stream(...)` until `StreamEvent::Finished`. Progress includes text deltas; the final event carries the same outcome shape as `run`. Dropping the stream cancels the underlying turn.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+The [complete streaming example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) checks that text arrives before completion and that the offline streamed reply equals a collected reply. [Provider configuration](../integrations/openai-compatible.md) covers explicit live inference.
diff --git a/gitbooks/developing/embed/guides/deploy-server.md b/gitbooks/developing/embed/guides/deploy-server.md
new file mode 100644
index 0000000000..0e5d076d59
--- /dev/null
+++ b/gitbooks/developing/embed/guides/deploy-server.md
@@ -0,0 +1,58 @@
+---
+description: "Invoke agents from a host-owned HTTP service without adding RPC to Embed."
+icon: code
+---
+
+# Deploy a server
+
+Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/server.rs#server -->
+
+```rust
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let agent = runtime.agent(
+ AgentSpec::new("http-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let address = listener.local_addr()?;
+ // A real host should use its HTTP framework and authenticate requests.
+ // This single-request fixture keeps the library dependency direction intact.
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await?;
+ let mut request = vec![0; 4096];
+ let length = socket.read(&mut request).await?;
+ assert!(String::from_utf8_lossy(&request[..length]).starts_with("GET /hello "));
+ let reply = agent.run("Say hello").await?.reply;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ reply.len(),
+ reply
+ );
+ socket.write_all(response.as_bytes()).await?;
+ Ok::<_, anyhow::Error>(())
+ });
+ let reply = reqwest::get(format!("http://{address}/hello"))
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ assert!(!reply.is_empty());
+ if support::offline() {
+ assert_eq!(reply, "hello from the stub");
+ }
+ server.await??;
+ println!("host HTTP request reached the in-process agent");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example server`. The [complete server example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) checks the HTTP response against the deterministic provider reply.
+
+Use your HTTP framework for a deployed service. The example's one-request parser is deliberately small; a deployed host must handle authentication, request limits, cancellation, and shutdown. Select agents from authenticated host state. For multiple users, use [SaaS profiles](saas-multi-tenant.md).
+
+If your host needs OpenHuman's existing JSON-RPC server, depend on `openhuman-rpc`, the layer above Embed. Adding that dependency to Embed would reverse the crate chain. [Channels](../integrations/channels.md) provide another way to deliver messages to bound agents.
diff --git a/gitbooks/developing/embed/guides/lean-headless.md b/gitbooks/developing/embed/guides/lean-headless.md
new file mode 100644
index 0000000000..ddc9c00dd6
--- /dev/null
+++ b/gitbooks/developing/embed/guides/lean-headless.md
@@ -0,0 +1,33 @@
+---
+description: "Control runtime activity separately from compile-time Cargo features."
+icon: code
+---
+
+# Lean and headless hosts
+
+`RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/lean_headless.rs#lean_headless -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.weight, openhuman_embed::WeightClass::Lean);
+ assert!(info.services.is_empty());
+ let agent = runtime.agent(
+ AgentSpec::new("lean").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ assert!(!agent.run("Hello lean runtime").await?.reply.is_empty());
+ println!("lean runtime runs a turn without background services");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example lean_headless`. The [complete lean_headless example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) uses `ServiceSet::none()`, verifies the lean capability report, and completes an actual turn. For a host crate that needs fewer compiled features, disable default features on its Embed dependency and enable only the gates it needs. Verify enabled and disabled builds for that selection.
+
+A headless host also owns process setup: initialize its encryption key before storing credentials, choose its state directory, and keep the runtime alive until shutdown. The example support code uses a random fixture key and temporary credential directory; deployed hosts supply a durable key and durable workspace.
+
+[Storage drivers](../integrations/storage-drivers.md) covers persistent backends. The [complete capability_report example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) reports compiled features and active services without exposing provider keys or URLs.
diff --git a/gitbooks/developing/embed/guides/mock-backend-testing.md b/gitbooks/developing/embed/guides/mock-backend-testing.md
new file mode 100644
index 0000000000..7fb20fac2a
--- /dev/null
+++ b/gitbooks/developing/embed/guides/mock-backend-testing.md
@@ -0,0 +1,48 @@
+---
+description: "Run the embedding examples offline and verify behavior, not just compilation."
+icon: code
+---
+
+# Test with a mock backend
+
+Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+
+The shared support module uses loopback Wiremock servers for backend and inference requests. It disables unrelated online services and supplies isolated keyring state. Examples assert replies, transmitted model settings, tool results, and state isolation. MCP and Telegram use their real protocol shapes against local stubs; SQLite performs real local writes.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+The [complete host_tools example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) checks the advertised catalog, executes a host tool exactly once, and verifies that its result reaches the next model request. This catches a host adapter that advertises a tool but never runs it.
+
+Run a single gated example with `cargo run -p openhuman-embed --example mcp --features mcp`, or use the full runner to select all gates automatically. The individual examples default to offline mode. Only the [explicit live provider options](../integrations/openai-compatible.md) and [MongoDB live option](../integrations/storage-drivers.md) contact configured services.
diff --git a/gitbooks/developing/embed/guides/multi-agent.md b/gitbooks/developing/embed/guides/multi-agent.md
new file mode 100644
index 0000000000..08b48ff1c2
--- /dev/null
+++ b/gitbooks/developing/embed/guides/multi-agent.md
@@ -0,0 +1,85 @@
+---
+description: "Share one runtime while configuring independent agent prompts and working folders."
+icon: code
+---
+
+# Multiple agents
+
+A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+The [complete two_agents example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) sends real turns and checks the provider requests: the reviewer prompt does not contain the fixer prompt. It also checks different action directories and agent homes. Run `cargo run -p openhuman-embed --example two_agents`.
+
+Agents on one runtime share the runtime configuration and credential root. Separate action directories are useful for cooperating agents; use [SaaS profiles](saas-multi-tenant.md) for user isolation.
+
+Runtime defaults can supply a provider and model settings; individual agents override selected fields. The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) verifies both routes and their transmitted temperature and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
diff --git a/gitbooks/developing/embed/guides/saas-multi-tenant.md b/gitbooks/developing/embed/guides/saas-multi-tenant.md
new file mode 100644
index 0000000000..3c328b8e8f
--- /dev/null
+++ b/gitbooks/developing/embed/guides/saas-multi-tenant.md
@@ -0,0 +1,50 @@
+---
+description: "Isolate user credentials, workspaces, and conversation history with ProfileRuntime."
+icon: code
+---
+
+# SaaS with multiple tenants
+
+Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+
+The complete example prepares a temporary SaaS root and initializes the keyring at `SaasConfig::operator_config().workspace_dir` before boot. SaaS validates the operator root, service token, permitted domains, and environment. A process-wide `OPENHUMAN_WORKSPACE` override is rejected. A SaaS core must be the only core in its process.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example profiles`. The [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) installs a loopback backend transport, chats as Alice and Bob, then checks distinct workspaces and same-thread history isolation. No live account or backend is contacted.
+
+Authenticate users in your host before selecting a profile. Keep the operator's configuration and gateway credential separate from user credentials. [Managed inference](../integrations/tinyhumans-managed.md) explains who provides the backend transport.
diff --git a/gitbooks/developing/embed/installation.md b/gitbooks/developing/embed/installation.md
new file mode 100644
index 0000000000..0d3a82145e
--- /dev/null
+++ b/gitbooks/developing/embed/installation.md
@@ -0,0 +1,53 @@
+---
+description: "Add the Embed dependency, choose compile-time gates, and configure the host\u2019s runtime and state deliberately."
+---
+
+# Installation
+
+`openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+
+Run repository commands from its root. Build the facade with `cargo check -p openhuman-embed`; validate a narrow graph with `cargo check -p openhuman-embed --no-default-features`. Runtime weight presets and Cargo features control different things.
+
+## Compile-time gates versus runtime selection
+
+| Choice | What it controls |
+| --- | --- |
+| Cargo default features | Code and dependencies compiled into the artifact |
+| Named Embed feature such as `mcp` or `skills` | Public facade items and the forwarded core gate |
+| `RuntimeBuilder::modules`, domains, services and tool groups | Which compiled families a runtime exposes or starts |
+| Agent tool scope and access | Which subset one agent can use |
+
+Embed defaults forward the core defaults and enable the named Embed `channels` feature. Core defaults can include MCP and skills without enabling Embed's separately gated `McpServer`/agent MCP setter or skill setters. Add `--features mcp,skills` when using those public APIs. A runtime selection cannot enable a Cargo gate that was compiled out; inspect the [generated compiled matrix](capability-matrix.md) and the [source manifest](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/Cargo.toml).
+
+`RuntimeBuilder::lean()` narrows runtime activity; it does not reduce the dependency graph by itself. Pair it with `--no-default-features` for a narrow build and explicitly add the gates you need. Use `scripts/assert-shed.sh` or the repository dependency simulator before claiming a dependency reduction. See [lean/headless guide](guides/lean-headless.md).
+
+## Host runtime and credentials
+
+Build a Tokio multi-thread runtime with `enable_all`, a large worker stack and a bounded blocking pool. The verified examples use the [core runtime constants](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/core/runtime/mod.rs) through their repository support module: currently a 20 MiB worker stack and 64 blocking workers. Tokio's default 2 MiB worker stack is insufficient for nested agent turns. Follow the full example's host setup rather than adding an unconfigured `#[tokio::main]` to a large agent workload.
+
+Initialize the credential master key through `openhuman_embed::process::init_master_key` before persisting a runtime API key. Headless hosts can provide a protected 64-hex-character `OPENHUMAN_KEYRING_MASTER_KEY` or configured key file; keep this credential out of source and logs. The offline examples create disposable fixture keys, not production credentials.
+
+## State, configuration and inspection
+
+`Workspace::Ephemeral` is the library preset's default. `Workspace::Dir` moves both internal state and the credential root together; `workspace_dir` overrides internal state only, leaving the credential root at the resolved config path. Keep the action directory outside the internal workspace. Operator host presets use discovered configuration, while a supplied `Config` is resolved host configuration.
+
+[Runtime defaults](concepts/runtime-defaults.md) explains inheritance. The generated [builder setters](builder-setters.md) is the source-derived list of configuration knobs, and `RuntimeBuilder::describe` reports the pre-build plan without starting services.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The example checks the effective report after boot and proves that credentials, provider URL and workspace path are absent. The generated matrix uses the fixed default-feature report command; it describes that build, not every feature combination a host might compile.
diff --git a/gitbooks/developing/embed/integrations/README.md b/gitbooks/developing/embed/integrations/README.md
new file mode 100644
index 0000000000..4168ac50f5
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/README.md
@@ -0,0 +1,18 @@
+---
+description: "Choose provider, tool, storage, and channel adapters for your host."
+icon: code
+---
+
+# Embedding integrations
+
+An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+
+- [OpenAI-compatible providers and BYOK](openai-compatible.md)
+- [TinyHumans managed inference](tinyhumans-managed.md)
+- [Local models](local-models.md)
+- [MCP servers](mcp.md)
+- [Composio](composio.md)
+- [Storage drivers](storage-drivers.md)
+- [Channels](channels.md)
+
+[Guides](../guides/README.md) show how these pieces fit into a CLI, an HTTP server, or a SaaS host. Every linked executable example defaults to offline mode; a live endpoint requires an explicit choice.
diff --git a/gitbooks/developing/embed/integrations/channels.md b/gitbooks/developing/embed/integrations/channels.md
new file mode 100644
index 0000000000..f4fa9979e5
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/channels.md
@@ -0,0 +1,82 @@
+---
+description: "Bind an incoming channel to an agent and verify the delivered reply."
+icon: code
+---
+
+# Channels
+
+Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example telegram --features channels`. The [complete telegram example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) receives a stub update, runs the bound agent, and checks that the resulting reply was posted to the expected chat id.
+
+Keep channel credentials in host configuration and map messages to the intended identity and conversation. A provider route controls inference; it does not configure a channel or provide a hosted relay. [Managed backend setup](tinyhumans-managed.md) explains that separate transport responsibility.
+
+For a live Telegram host, supply the real Bot API configuration through your application's channel setup. This offline example deliberately has no live channel environment switch. [Deploy a server](../guides/deploy-server.md) covers a host-owned HTTP alternative.
diff --git a/gitbooks/developing/embed/integrations/composio.md b/gitbooks/developing/embed/integrations/composio.md
new file mode 100644
index 0000000000..694e719733
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/composio.md
@@ -0,0 +1,14 @@
+---
+description: "Pin connector credentials per agent while the host supplies backend transport."
+icon: code
+---
+
+# Composio
+
+Composio calls use the host backend transport. Install that transport before booting a managed runtime; see [TinyHumans managed inference](tinyhumans-managed.md). An explicit inference provider route supplies model inference, not the connector transport.
+
+Use `AgentSpec::composio(ComposioHostCredential)` to pin a connector credential to an agent. This keeps the credential selection on the host side instead of asking the model to choose another user's credential. Configure the agent's tool scope and access separately. The connector tools still pass through the host's execution policy.
+
+The repository's [Composio agent integration test](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/tests/composio_agents.rs) verifies two agents using their own pinned credentials against a loopback backend. It checks the outgoing authentication and action results rather than contacting Composio. Run the Embed integration suite through the repository's cancellation-aware runner when changing this adapter.
+
+Account login, linking, and credential acquisition belong to your connected host and connector layer. Keep secrets out of prompts and capability reports. For multiple users, use [SaaS profiles](../guides/saas-multi-tenant.md); independent action directories on a shared library runtime do not establish tenant isolation.
diff --git a/gitbooks/developing/embed/integrations/local-models.md b/gitbooks/developing/embed/integrations/local-models.md
new file mode 100644
index 0000000000..194145321d
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/local-models.md
@@ -0,0 +1,69 @@
+---
+description: "Use a local OpenAI-compatible server or inject a native ChatModel implementation."
+icon: code
+---
+
+# Local and custom models
+
+For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The [OpenAI-compatible example controls](openai-compatible.md) can point a live example at that local server.
+
+A native provider implements `openhuman_embed::providers::ChatModel<()>`. `Provider::custom_with_fallback` tries fallback models when the primary fails before output; validation failures and failures after streamed content do not switch providers. A named role pin can select another native model for a workload.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example custom_provider`. The [complete custom_provider example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) includes the concrete model implementation. It checks one primary failure, one fallback invocation, and a coding role that bypasses the primary chain. These native models are deterministic and make no inference network requests.
+
+For live local inference, configure model availability and authentication in your server. For runtime selection and service controls, see [Lean and headless hosts](../guides/lean-headless.md).
diff --git a/gitbooks/developing/embed/integrations/mcp.md b/gitbooks/developing/embed/integrations/mcp.md
new file mode 100644
index 0000000000..0688ce318e
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/mcp.md
@@ -0,0 +1,63 @@
+---
+description: "Connect a declared MCP server and verify remote discovery and execution."
+icon: code
+---
+
+# MCP servers
+
+Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example mcp --features mcp`. The [complete mcp example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) performs an actual MCP initialize handshake, lists remote tools, calls the forecast tool, and verifies the returned `sunny` result in the next model request.
+
+The immediately available `mcp_list_tools` and `mcp_call_tool` bridge tools work with a cold configured server. Individual per-server tools use a cached catalog and are deferred by default. On a cold first turn, that catalog may still be warming in the background; do not assume `tool_search` already contains the per-server tool name. Use the bridge to discover and call it, and copy returned tool names and arguments.
+
+MCP transport does not bypass the host's execution policy. Configure agent access and approvals for actions exposed by the server. [Mock testing](../guides/mock-backend-testing.md) keeps this protocol path local during development.
diff --git a/gitbooks/developing/embed/integrations/openai-compatible.md b/gitbooks/developing/embed/integrations/openai-compatible.md
new file mode 100644
index 0000000000..ac5b643820
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/openai-compatible.md
@@ -0,0 +1,53 @@
+---
+description: "Route inference to an explicit endpoint and bearer without changing shared host configuration."
+icon: code
+---
+
+# OpenAI-compatible providers and BYOK
+
+Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+
+The runtime and agent routes in this example answer independently. Assertions inspect the actual request bodies, including model, temperature, and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) includes the loopback endpoint setup. Run `cargo run -p openhuman-embed --example defaults_overrides` for its offline assertions.
+
+Examples using `support::example_provider` switch to live inference only with `OPENHUMAN_EXAMPLE_LIVE=1` and all three of `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY`, and `OPENHUMAN_EXAMPLE_MODEL`. These settings are example controls, not replacements for your application's credential configuration. Keep provider keys in your host's secret configuration.
+
+For a non-HTTP implementation, [local and custom models](local-models.md) covers `Provider::custom`, native fallback, and role pins. [Managed inference](tinyhumans-managed.md) uses a different backend transport boundary.
diff --git a/gitbooks/developing/embed/integrations/storage-drivers.md b/gitbooks/developing/embed/integrations/storage-drivers.md
new file mode 100644
index 0000000000..f3449560a0
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/storage-drivers.md
@@ -0,0 +1,84 @@
+---
+description: "Configure SQLite or MongoDB through Embed and inspect the selected backend."
+icon: code
+---
+
+# Storage drivers
+
+Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+
+The SQLite example sets `config.storage.url` to a `sqlite:` URL under a temporary directory, then obtains `Runtime::storage`. It creates a scoped collection, writes a document, reads it back, and deletes it. A configured backend also supplies the default driver-backed session stores; an explicit host session-store adapter takes precedence.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_sqlite -->
+
+```rust
+ let mut config = support::offline_config();
+ config.storage.url = Some(format!(
+ "sqlite:{}",
+ directory.path().join("storage").display()
+ ));
+ let runtime = Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .config(config)
+ .backend_url(backend.uri())
+ .build()
+ .await?;
+ let storage = runtime.storage().expect("configured SQLite backend");
+ assert_eq!(storage.driver(), "sqlite");
+ let scoped = storage.for_scope(&Scope::local())?;
+ let documents = scoped.documents();
+ documents
+ .ensure_collection(&CollectionSpec::new("settings"))
+ .await?;
+ let value = serde_json::json!({"theme":"dark"});
+ documents
+ .put("settings", "demo", value.clone(), Precondition::Absent)
+ .await?;
+ assert_eq!(
+ documents
+ .get("settings", "demo")
+ .await?
+ .expect("stored value")
+ .doc,
+ value
+ );
+ assert!(
+ documents
+ .delete("settings", "demo", Precondition::None)
+ .await?
+ );
+ assert!(documents.get("settings", "demo").await?.is_none());
+ assert_eq!(
+ runtime.capabilities().storage.driver.as_deref(),
+ Some("sqlite")
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example storage --features storage-sqlite`. This performs real local SQLite writes. The [complete storage example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) also describes a MongoDB URL without connecting.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_mongodb -->
+
+```rust
+ // Enable `storage-mongodb` for a deployment that builds this config.
+ // Describing it does not contact MongoDB and never exposes credentials.
+ let mut mongo = support::offline_config();
+ mongo.storage.url = Some("mongodb://app:[email protected]:27017/openhuman".into());
+ let builder = RuntimeBuilder::library().config(mongo);
+ let description = builder.describe();
+ assert_eq!(description.storage.driver.as_deref(), Some("mongodb"));
+ assert!(description.storage.configured);
+ assert!(!serde_json::to_string(&description)?.contains("example-password"));
+ // An explicit environment variable is the only path to a live database.
+ if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_MONGODB_URL") {
+ let live = RuntimeBuilder::library().storage(url).build().await?;
+ assert_eq!(live.storage().expect("MongoDB backend").driver(), "mongodb");
+ }
+```
+
+<!-- END EMBED -->
+
+`RuntimeBuilder::describe()` reports the driver and whether storage is configured, omitting URL credentials. Describing a MongoDB URL does not prove the server is reachable or that the MongoDB driver was compiled. Building a runtime with that URL requires `storage-mongodb` and a reachable server.
+
+The only live database path in this example is `OPENHUMAN_EXAMPLE_MONGODB_URL`. To exercise it deliberately, enable both `storage-sqlite` and `storage-mongodb` and supply your own MongoDB URL. The offline CI runner clears this setting. A deployed host supplies its persistent URL and credentials through its own configuration.
diff --git a/gitbooks/developing/embed/integrations/tinyhumans-managed.md b/gitbooks/developing/embed/integrations/tinyhumans-managed.md
new file mode 100644
index 0000000000..ef5118247f
--- /dev/null
+++ b/gitbooks/developing/embed/integrations/tinyhumans-managed.md
@@ -0,0 +1,52 @@
+---
+description: "Install the host backend transport before using managed inference and hosted services."
+icon: code
+---
+
+# TinyHumans managed inference
+
+Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+
+Supply a library backend key with `RuntimeBuilder::api_key` and initialize the process master key before credential storage. Library mode does not perform user login. Managed inference uses the key as a bearer; backend REST calls resolve it through the backend credential seam. Without an installed transport, hosted backend calls return a typed backend-unavailable error.
+
+The SaaS example uses a deterministic implementation of that transport boundary and installs separate profile credentials. It verifies managed turns without a live service.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+See the [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) and its shared support transport for the full offline setup. For a deployed SDK-backed host, follow the connected layer's setup instead of copying the loopback transport.
+
+Use [OpenAI-compatible routing](openai-compatible.md) when your host wants to send inference directly to a BYOK endpoint. That explicit provider route does not supply hosted backend services.
diff --git a/gitbooks/developing/embed/quickstart.md b/gitbooks/developing/embed/quickstart.md
new file mode 100644
index 0000000000..6b048a8ed7
--- /dev/null
+++ b/gitbooks/developing/embed/quickstart.md
@@ -0,0 +1,53 @@
+---
+description: "Run one agent against a local fixture, then choose a provider and working directory for your host."
+---
+
+# Quickstart
+
+Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+
+## Create an agent and send a turn
+
+The full example constructs the runtime before this excerpt. `AgentSpec` names the agent and gives it a bare prompt with `HostOnly` tools. With no host tools attached, this is a text-only agent: it cannot inherit the operator's built-in tool catalog.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs), including runtime construction, imports and fixture setup.
+
+`Agent::run` returns a `TurnOutcome` containing the reply and session identity. Use `Agent::turn(...).session(...)` for subsequent messages in the same conversation, or [stream progress](concepts/turns-sessions.md) when your interface should display deltas as they arrive.
+
+## Connect your own host
+
+Replace the fixture provider with an explicit OpenAI-compatible `Provider` or a native custom model. Give tools an explicit action directory, decide whether autonomy enforcement should be enabled, and keep runtime state separate from acting-tool folders. Configure the Tokio worker stack and credential master key as described in [installation](installation.md).
+
+The example's live path requires `OPENHUMAN_EXAMPLE_LIVE=1` plus `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY` and `OPENHUMAN_EXAMPLE_MODEL`. Choosing a live path is an explicit decision; setting credentials alone does not turn the default example into a live call.
+
+For managed TinyHumans inference, use the [TinyHumans host integration](integrations/tinyhumans-managed.md), which installs the backend transport. Embed by itself does not install one.
+
+## Extend the example
+
+- Give a reviewer and a fixer separate tools and folders: [multiple agents](guides/multi-agent.md).
+- Serve a request through your own HTTP transport: [deploy a server](guides/deploy-server.md).
+- Attach application functions: [tools](concepts/tools.md).
+- Isolate authenticated customers: [SaaS guide](guides/saas-multi-tenant.md).
+- Keep the setup offline and deterministic: [mock-backend testing](guides/mock-backend-testing.md).
+
+Drop listeners and agent handles before shutting down the runtime. For early removal, await `remove_agent` so retained handles stop admitting turns and the old ID is released only after cleanup.
diff --git a/gitbooks/developing/embed/troubleshooting.md b/gitbooks/developing/embed/troubleshooting.md
new file mode 100644
index 0000000000..244a0b68dd
--- /dev/null
+++ b/gitbooks/developing/embed/troubleshooting.md
@@ -0,0 +1,46 @@
+---
+description: "Diagnose missing features, blocked turns, credentials, state paths and lifecycle failures."
+---
+
+# Embedding troubleshooting
+
+Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+
+| Symptom | Check and next step |
+| --- | --- |
+| `RuntimeError::AlreadyRunning` | Reuse the process runtime; drop old listeners, agents and runtime before restarting. Profiles require their own process mode. |
+| Method or type not found at compile time | Check named Embed Cargo gates, especially `mcp`/`skills`. Core compiled flags alone do not activate those facade exports. |
+| `CoreError::Unavailable` | Inspect effective domains/modules as well as compiled features. Runtime selections can narrow a compiled family. |
+| `BACKEND_UNAVAILABLE` | Install the host backend transport, normally through `openhuman-tinyhumans`, before backend-touching calls. |
+| Credential master-key failure | Initialize process master-key state before persisting a runtime API key; check headless key/file setup without printing its value. |
+| Invalid or insecure provider route | Supply a nonblank endpoint/key and use HTTPS for remote bearer routes. Loopback fixtures are separate from remote endpoints. |
+| Stack overflow on a nested turn | Use the documented Tokio worker stack; the default 2 MiB stack is insufficient. Follow the runnable example support setup. |
+| A write is waiting indefinitely | Poll the same agent's approvals or retain an active callback subscription. Check origin, enabled autonomy and trusted action roots. |
+| Streaming appears stalled | Drain the bounded progress stream while work runs; inspect the final result. Dropping it cancels forwarding and the turn cooperatively. |
+| A skill is absent | Copy a real bundle into the agent's skill directory; symlinked bundles are rejected. New instructions need a new session. |
+| Agent registration returns `DuplicateId` | Another instance or teardown still reserves the ID. Wait for removal/last-handle cleanup to finish. |
+| Retained handle returns `AgentRemoved` | That instance was removed; obtain a newly registered handle rather than reusing the old one. |
+| `Decode` error on a typed facade | Treat it as an API/result-shape mismatch; preserve safe metadata and report a regression. |
+
+## Inspect without exposing credentials
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+Before boot, `RuntimeBuilder::describe` can report a provisional plan; check `configuration_resolved`. After boot, `Runtime::capabilities` describes resolved defaults, storage source/driver and selection without its URL/key. Runtime events provide content-free lifecycle metadata, while explicit turn progress can contain text and should be handled accordingly.
+
+Reproduce behavior with [offline testing](guides/mock-backend-testing.md) before using a live provider. The [error concept](concepts/errors.md) explains structured kinds and expected-user-state errors.
diff --git a/gitbooks/developing/embedding.md b/gitbooks/developing/embedding.md
index 2bda2397ff..de8bf1d715 100644
--- a/gitbooks/developing/embedding.md
+++ b/gitbooks/developing/embedding.md
@@ -1,607 +1,7 @@
----
-description: >-
- How to run the OpenHuman core inside your own Rust program: one Runtime,
- with any number of separately configured Agents on it.
-icon: code
----
-
# Embedding OpenHuman
-`openhuman-embed` is a typed Rust library that runs the OpenHuman core inside your own product. It is the same core that ships in the desktop app and the CLI, without the Tauri shell and the RPC server. You call business rules, agent turns, memory, tools and sandboxing directly from your own binary.
-
-## Adding the dependency
-
-Use the default contributor feature set:
-
-```toml
-[dependencies]
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed" }
-```
-
-Or select a narrower build:
-
-```toml
-[dependencies]
-openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed", default-features = false, features = ["inference", "mcp"] }
-```
-
-Every feature on this crate forwards to the same-named feature on
-`openhuman-core`: `default`, `http-server`, `inference`, `documents`,
-`hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,
-`flows`, `skills`, `mcp`, `crash-reporting`, `channels`,
-`whatsapp-web`, `file-logging`, `scheduler-gate` (eighteen entries including
-`default`). Two of them also gate
-items on this crate's own API: `mcp` gates `HttpHeader`,
-`McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`;
-`skills` gates `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.
-
-Set your product's identity once at startup, before building any client:
-
-```rust
-use openhuman_embed::{set_product_identity, ProductIdentity};
-
-if let Some(identity) = ProductIdentity::new("opencompany") {
- set_product_identity(identity);
-}
-```
-
-## Two steps: a Runtime, then any number of Agents
-
-The library API has two levels. First you build one `Runtime` for the process. It holds features, background services, the backend URL and the TinyHumans API key. Then you add any number of separately configured agents to it. Each agent has its own provider, access tier, working directory, MCP servers and skills.
-
-```rust,no_run
-use openhuman_embed::{Access, AgentSpec, McpServer, Provider, Runtime, Workspace};
-
-# async fn demo() -> Result<(), Box<dyn std::error::Error>> {
-let runtime = Runtime::builder()
- .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 own 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?;
-println!("{}", fix.reply);
-
-// Continue a conversation with the same agent.
-let again = fixer.turn("Now run the tests.").session(&fix.session_id).send().await?;
-println!("{}", again.reply);
-# Ok(())
-# }
-```
-
-An agent owns:
-
-- its provider and model
-- its access tier and turn origin
-- its `action_dir`
-- its MCP servers
-- its skills root (`<workspace>/agents/<id>/skills/`)
-- its system prompt
-- its tool scope and sandbox mode
-- a narrowed domain set or tool-group list
-
-Every turn runs under that agent's own context. Config, domain gating, tool-group filtering and skill discovery all read that agent's settings and never another agent's. Transcripts are keyed by agent id, and a turn resumes only its own thread.
-
-The runtime owns the workspace and credential store, the event bus, the keyring, background services, the registered domain set and the API key. Agents can only narrow the domain set, so enable `mcp` or `skills` at runtime build time if any agent needs them.
-
-Layout under a runtime-owned root:
-
-```text
-<root>/config.toml, auth-profiles.json, core.token
-<root>/workspace/session_db/, session_raw/<session_key>.<agent>[.g<n>].jsonl, agents/<agent>/skills/
-<root>/agents/<agent>/action/ default action_dir
-```
-
-## AgentSpec
-
-`AgentSpec::new(id)` starts from the built-in orchestrator's definition
-(prompt, tools, delegation) applied to a fresh id, except every registered
-tool is visible by default (`ToolScopeSpec::Wildcard`) rather than the
-desktop's own narrower set. Chain builder methods to override:
-
-- `.system_prompt(text)` and `.definition(spec)` for the prompt, tool scope,
- disallowed tools, sandbox mode, iteration cap, temperature, display name
- and delegation blurb (`AgentDefinitionSpec`).
-- `.provider(Provider)` and `.model(id)` for which model answers and where.
-- `.access(Access)` for what the agent may do.
-- `.tool_groups(ToolGroups)` and `.domains(DomainSet)` to narrow further,
- never wider than the runtime's own set.
-- `.mcp(McpServer)` (repeatable) for MCP servers only this agent can call.
-- `.skills_dir(path)` to copy skill bundles into this agent's own root.
-- `.include_user_skills(bool)` to also let the agent see the operator's
- `~/.openhuman/skills` (off by default).
-- `.action_dir(path)` for the agent's read and write root.
-- `.trust(path, access)` to grant a directory outside `action_dir`.
-- `.tools(factory)` to hand the agent real in-process tools built fresh per
- turn, rather than routing host callbacks through an MCP server.
-- `.config(f)` as an escape hatch for config fields the spec does not model.
-
-Agent ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`; avoid the built-in ids
-(`orchestrator`, `summarizer` and so on), which the runtime-wide delegation
-catalog resolves to the shipped definitions.
-
-## Access tiers
-
-`Access` sets two things together on purpose: the autonomy tier that drives
-the security policy, and the turn origin the approval gate checks. Setting
-only the tier produces an agent whose shell, edit and exec tools all
-silently refuse, which reads as a weak model rather than a missing scope.
-
-- `Access::readonly()`: observe only, no writes, no shell, no network side
- effects. Safe default for an untrusted prompt.
-- `Access::supervised()`: act, but park risky operations for a human
- decision. Unlike the desktop default, this turns the autonomy policy on
- for that agent (`Access` sets the policy flag as well as the tier), so the
- approval gate really is live and an unattended harness stalls here until an
- approval answers or the ten-minute TTL denies it. The user-facing default is
- the opposite: `[autonomy] enabled = false`, where the gate is inert. See
- [Approval gate](../features/approval-gate.md).
-- `Access::full()`: act autonomously, no approval pauses. Grants real shell
- and file access under `action_dir`; point it at a directory you are
- willing to have changed. Hard blocks still apply regardless of tier:
- credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and the workspace's own
- internal state stay off limits.
-
-`.trust(path, access)` grants a directory outside the action root, and
-`.allow_tool_install(bool)` opts into OS package installation, off in every
-preset including `full()` because it reaches outside the action directory
-that otherwise bounds the blast radius.
-
-## Provider: BYOK or managed
-
-`Provider::inherit()` uses whatever inference the runtime or the machine is
-already configured with: the account's managed backend, a local Ollama or
-LM Studio, or a configured BYOK provider. `Provider::openai_compatible(url,
-key)` points a turn at a specific OpenAI-compatible endpoint and bearer;
-`/chat/completions` is appended to `url`, so pass the API root. `.model(id)`
-pins the model id on either; it is advisory, because a model that no configured
-provider serves falls back instead of failing.
-
-An agent that names its own `Provider` never touches the runtime's API key.
-One that names none inherits the runtime's default: managed inference on
-the API key when one was supplied, or the machine's own configuration
-otherwise.
-
-## Workspace
-
-`Workspace::Ephemeral` (the default) is a throwaway directory removed when
-the harness or runtime drops; nothing here touches a real install, and
-sessions do not survive the process. `Workspace::dir(path)` is a
-caller-owned directory that persists across runs. `Workspace::Inherit`
-reuses the machine's configured OpenHuman workspace, the same one the
-desktop app and CLI use, resolved the usual way
-(`OPENHUMAN_WORKSPACE`, `active_user.toml`, `~/.openhuman/...`); an inherited
-workspace is the operator's, so the harness will not copy skills into it.
-
-`Workspace::stateless()` keeps nothing durable on disk: every agent's
-transcripts, turn journal, run status, goals and todos go through the
-runtime's session store (`RuntimeBuilder::session_store`, required), a
-`SessionStoreProvider` the host implements over its own database and scopes
-by agent id. It is the shape for a cloud host serving many users from one
-process; see the embed crate's README, "Conversations in a host store".
-
-## Tool scopes and sandbox modes
-
-`AgentDefinitionSpec::tools(ToolScopeSpec::Wildcard)` exposes every
-registered tool (the default); `ToolScopeSpec::Named(vec![...])` restricts
-an agent to exactly those tool names, dropping unknown ones at build time.
-`.disallow_tools([...])` hides specific tools even when the scope would
-include them.
-
-`SandboxModeSpec` confines an agent's shell and file tools:
-
-- `SandboxModeSpec::None` (default): only the access tier and path policy
- apply.
-- `SandboxModeSpec::ReadOnly`: write and execute tools are filtered out
- entirely.
-- `SandboxModeSpec::Sandboxed`: commands run under the platform jail or
- Docker backend.
-
-## MCP servers
-
-`McpServer::stdio(name, command, args)` launches a local subprocess
-speaking newline-delimited JSON-RPC; `McpServer::http(name, endpoint)`
-reaches a remote server over Streamable HTTP. Both support `.env(...)` or `.auth(McpAuthConfig)`. `.allow_tools([...])` and `.deny_tools([...])` narrow which remote tools an agent sees, which is worth doing for a large server because every exposed tool costs prompt budget. `.timeout_secs(n)` and `.description(text)` are also available. Servers declared through `AgentSpec::mcp` are private
-to that agent; other agents on the same runtime do not see them. Servers are fixed at build time. You cannot add one to a running harness.
-
-## Skills
-
-`AgentSpec::skills_dir(dir)` copies skill bundles into
-`<workspace>/agents/<id>/skills/`, visible only to that agent. Bundles are
-copied rather than symlinked because skill discovery rejects symlinked
-bundles. `.include_user_skills(true)` additionally lets the agent discover
-skills the operator installed under `~/.openhuman/skills`; the default
-hides them, because an embedded agent should see what its host installed, not
-what the machine's user did.
-
-## Multi-turn sessions and progress streaming
-
-`agent.turn(message)` returns a builder. `.session(id)` continues an
-existing conversation; without it a fresh session id is minted and returned
-on `TurnOutcome::session_id`. `.model(id)` and `.temperature(t)` override
-those settings for one turn. `.cwd(dir)` roots that turn's filesystem and
-shell tools somewhere other than the agent's configured `action_dir`.
-`.route(Route)` sends one turn to a specific endpoint instead of the
-account's configured route. `.origin(AgentTurnOrigin)` states the calling
-authority explicitly, for a turn that is not a human at a terminal, such as
-a workflow node or a scheduled job.
-
-`.on_progress(sender)` streams tool calls, deltas and turn boundaries as
-they happen. The core awaits every send, so the channel is real
-backpressure: a receiver that stops draining stalls the turn.
-
-```rust,no_run
-# use openhuman_embed::Agent;
-# async fn go(agent: &Agent) -> anyhow::Result<()> {
-let (tx, mut rx) = tokio::sync::mpsc::channel(256);
-let printer = tokio::spawn(async move {
- while let Some(progress) = rx.recv().await {
- eprintln!("[progress] {progress:?}");
- }
-});
-let outcome = agent.turn("go").on_progress(tx).send().await?;
-let _ = tokio::time::timeout(std::time::Duration::from_secs(30), printer).await;
-println!("{}", outcome.reply);
-# Ok(()) }
-```
-
-`.seed(history)` replaces a session's history for one turn with your own `(role, content)` rows instead of reading the transcript. Only a runtime-owned `Agent` can honor it. It silently discards whatever the session held, so pair it with a session id that no other turn shares. `.meter(f)`
-reports what a turn spent, including a turn that ran and then failed.
-
-## Scheduling
-
-OpenHuman's own cron can drive scheduled turns of a runtime's agents, with
-their host tools, and run host code on a schedule. `runtime.cron()` is a typed
-facade over the runtime's job store; jobs are named and `upsert` is idempotent
-by that name, so a host can declare its schedule on every start:
-
-```rust,no_run
-# async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), Box<dyn std::error::Error>> {
-use openhuman_embed::{JobSchedule, JobSpec};
-
-let cron = runtime.cron();
-// One turn of the runtime agent `teeny` every morning.
-cron.upsert(
- JobSpec::agent("morning", "teeny", "Plan the day.", JobSchedule::Cron {
- expr: "0 8 * * *".into(),
- tz: Some("Europe/Berlin".into()),
- })
- .retries(0) // exactly one attempt: the turn has side effects
- .single_flight(true) // skip (and record) a slot that comes due mid-run
-)?;
-// Host code on a schedule; its result is the run's recorded result.
-runtime.on_system_job("digest", |_ctx| async { Ok(()) })?;
-cron.upsert(JobSpec::system("digest", "digest", JobSchedule::Every { ms: 15 * 60_000 }))?;
-
-let run = cron.run_now("morning").await?; // same path as a scheduled run
-println!("{} {}", run.success, run.output);
-# Ok(()) }
-```
-
-- **Jobs fire only while the scheduler runs.** Build the runtime with
- `.services(ServiceSet { cron: true, ..ServiceSet::none() })`; `build()` then
- starts the selected services and dropping the runtime (and its agents) stops
- them. `Runtime::start_services` / `stop_services` give explicit control.
- Without the scheduler, jobs are stored and `run_now` still works.
-- **An agent job runs as the agent.** When `agent_id` names an agent alive on
- the runtime, the turn uses its definition and system prompt, its
- `AgentSpec::tools` and attached tools, its provider and its own context
- (`agent::host_agents` resolves it for the core's cron and workflow drivers).
- Any other id resolves through the core's agent registries. The turn's origin
- is `TrustedAutomation { Cron }`, not the agent's own access origin. Agent jobs
- may not run more often than every five minutes.
-- **A system job runs the host's handler.** `on_system_job(name, handler)`
- registers an async `Fn(SystemJobContext) -> Result<(), String>`; when the job
- comes due the scheduler still publishes `CronSystemJobDue` on the bus, then
- awaits the handler and records `ok` or `error` with its message.
-- **Retries and overlap.** A failed run is retried `retries` times with
- backoff; unset keeps `reliability.scheduler_retries` (2), and `0` is one
- attempt. Two runs of one job never overlap: each due job is dispatched on
- its own task, so a long job no longer holds up the others, `run_now` is
- refused while a run is active, and a slot that comes due mid-run is skipped.
- With `single_flight` that skip is recorded as a `skipped` run.
-- `cron.list()`, `cron.remove(name)` and `cron.runs(name, limit)` cover the
- rest. Shell jobs and workflow schedule triggers are not managed here.
-
-## Channels
-
-A runtime agent can answer a messaging channel. `runtime.channels()` starts a
-channel listener bound to one agent, so every message on it is a turn of that
-agent rather than of the orchestrator:
-
-```rust,no_run
-# async fn demo(runtime: &openhuman_embed::Runtime) -> Result<(), Box<dyn std::error::Error>> {
-use openhuman_embed::{AgentSpec, TelegramChannelSpec};
-
-let agent = runtime.agent(AgentSpec::new("teeny-chat").system_prompt("You are Teeny."))?;
-let telegram = runtime.channels().telegram(
- TelegramChannelSpec::new("123456:bot-token", "teeny-chat")
- .allow_everyone() // or .allowed_users(["alice", "4242"])
- .mention_only(true), // in groups, answer only when mentioned
-)?;
-// The bot answers until the listener is stopped or dropped.
-# let _ = (agent, telegram);
-# Ok(()) }
-```
-
-- **The agent answers as itself.** Each message runs with the agent's system
- prompt, tool scope, `AgentSpec::tools` belt and attachments, provider and
- context. History is per chat, kept by the channel the same way it is for the
- orchestrator. Typing indicators, streamed drafts and the reply work as for
- any channel. Call `telegram()` from inside the tokio runtime; it spawns the
- listener there.
-- **Bind to an agent that exists.** `telegram()` refuses an id with no live
- agent on the runtime (`ChannelError::UnknownAgent`). If the agent is dropped
- while the bot is running, each message gets a short "not available" reply and
- an error is logged. The message is never handed to the orchestrator.
-- **Turns are untrusted and read-only.** Anyone who can message the bot writes
- the turn's text, so it runs as `AgentTurnOrigin::ExternalChannel` and is
- capped at `PermissionLevel::ReadOnly`. A tool that writes, executes or has an
- external effect is withheld from the turn's tool list or refused at once with
- a tool error. It never waits on an approval, because the only person who
- could answer one is the sender. Give a public agent read-only host tools, and
- do anything with side effects outside the chat turn (a cron job, host code).
-- **Under the hood** this is the core's channel runtime for that one bot,
- started under the runtime's context with
- `agent.channel_agents = { telegram = "<agent id>" }`. A core started from a
- config file can bind a channel the same way: any channel name works as the
- key, and the agent is resolved through `agent::host_agents`.
-
-## Harness: the one-agent shorthand
-
-`Harness` is a `Runtime` plus exactly one agent, built from one set of
-inputs, for a host that only ever needs one:
-
-```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(())
-# }
-```
-
-`harness.runtime()` and `harness.agent()` hand out the underlying `Runtime`
-and `Agent`, so a host that outgrows one agent adds more on the same
-runtime rather than rebuilding.
-
-## Many users in one process: ProfileRuntime
-
-A `Runtime` serves one operator, and its agents share that operator's
-credentials. A server that already authenticates its own users and needs each
-of them isolated (their own workspace, credential, threads, memory and
-security policy) uses `ProfileRuntime` instead. It is the hosted SaaS mode's
-profile host, driven in-process without the JSON-RPC gateway: one profile per
-user, laid out like the desktop's `users/<id>/`.
-
-```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?;
-let reply = handle.chat("t1", "Remind me to water the ferns.").await?;
-println!("{}", reply.text);
-
-// A message alice sent the product's Telegram bot: it lands on her
-// `channel:telegram/555/777` thread, and the reply arrives on her events
-// as `channel_outbound` for you to deliver.
-let mut events = handle.events();
-handle
- .relay_inbound(RelayMessage::new("telegram", "777", "555", "tg-1", "hi"))
- .await?;
-# let _ = events.recv().await; Ok(()) }
-```
-
-What to know before reaching for it:
-
-- **It locks the process into SaaS mode.** Building a `ProfileRuntime` fails
- if any core already runs in the process, and afterwards
- `Runtime::builder()`, `Harness` and a second `ProfileRuntime` all refuse to
- boot. Give it a process of its own.
-- **The boot guard runs.** The root must be absolute, existing, not
- world-writable and outside `~/.openhuman`, and single-user environment
- variables (`OPENHUMAN_WORKSPACE`, `OPENHUMAN_CORE_TOKEN`, ...) must be
- unset. A missing service token file is written for you (owner-only,
- random), since nothing serves a gateway here.
-- **A thread id is unique per profile.** Two users' `t1` are two
- conversations; nothing about one is visible to the other, including its
- events (`ProfileHandle::events` only yields that profile's).
-- **A handle keeps its profile open.** While a `ProfileHandle` (or a clone)
- is alive, the profile is not evicted and `release` refuses it. Drop the
- handles to let idle eviction (`idle_evict_secs`, `max_profiles_open`) close
- it.
-- **Inference is managed.** A profile's config is forced and names no
- endpoint, so its turns go through the installed backend transport
- (`openhuman_tinyhumans::install`) with the profile's own credential.
-- **Calls go through the user surface.** `ProfileHandle::call` reaches only
- the reviewed `USER_METHODS` (threads, web chat, relay, the user's memory),
- as a gateway request would.
-
-The same host also runs as a server behind a gateway, across several nodes;
-see [SaaS profiles](saas-profiles.md) for deploying it.
-
-## Connecting to the hosted backend
-
-`openhuman-embed` alone installs no backend transport: agents, memory,
-skills, tools and RPC all run, and every hosted-backend surface (billing,
-integration tools, channel relay, cloud voice) answers with a typed
-`BACKEND_UNAVAILABLE:` error. `openhuman-tinyhumans::RuntimeBuilder` mirrors
-`openhuman_embed::RuntimeBuilder` method for method and installs the
-SDK-backed transport on `build()`:
-
-```rust
-use openhuman_tinyhumans::{embed::Workspace, RuntimeBuilder};
-
-let runtime = RuntimeBuilder::new()
- .workspace(Workspace::Ephemeral)
- .api_key("th_...")
- .build()
- .await?;
-```
-
-Hosts that boot the core themselves rather than through either builder (the
-desktop shell, the TUI, the CLI, test fixtures) call `install` once before
-the first backend-touching dispatch:
-
-```rust
-openhuman_tinyhumans::install(openhuman_tinyhumans::InstallOptions::default())?;
-```
-
-That call also registers the seven hosted RPC proxy domains (billing, team,
-referral, announcements, webhooks, channel linking and backend-brokered OAuth)
-into the core's controller registry. See
-[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans
-API key unlocks once it is installed this way.
-
-## Library mode has no user login
-
-`RuntimeBuilder::api_key` installs a TinyHumans API key into the runtime's
-credential store before the core boots. Managed inference then sends it as
-`Authorization: Bearer <key>` to the TinyHumans endpoint, 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, no session JWT, nothing to expire. An
-agent that names its own `Provider` never touches the key at all.
-
-## One runtime per process
-
-The keyring master key, the RPC bearer, the global event bus and the
-process's domain subscribers are process-scoped. A second runtime would
-silently share them while believing it had a separate workspace.
-`RuntimeBuilder::build` returns `RuntimeError::AlreadyRunning` instead.
-Within one process, add agents, not runtimes.
-
-Build the tokio runtime yourself instead of using `#[tokio::main]`. A turn
-is a large async state machine, and a nested sub-agent overflows
-tokio's default 2 MiB worker stack:
-
-```rust,no_run
-use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
-
-let runtime = tokio::runtime::Builder::new_multi_thread()
- .enable_all()
- .thread_stack_size(AGENT_WORKER_STACK_BYTES)
- .max_blocking_threads(MAX_BLOCKING_THREADS)
- .build()
- .expect("tokio runtime");
-```
-
-## A narrow build, measured
-
-[`docs/library-minimal-recipe.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-minimal-recipe.md) measures a headless recipe aimed at
-100 to 1,000 live agents on a 2 GB RAM / 2 vCPU box:
-
-```bash
-cargo build --release \
- -p openhuman-embed \
- --no-default-features --features "skills,flows"
-```
-
-Stripped binary size: 51.0 MiB with no optional gates at all, about 60.4 MiB
-with `skills,flows` enabled (the recipe above), against 115.9 MiB unstripped
-with every gate on. See [Performance](performance.md) for how that build
-size relates to per-agent memory and cold-start time when many agents share
-one process.
-
-## Examples to run
-
-Against any OpenAI-compatible endpoint:
-
-```bash
-OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-OPENHUMAN_EXAMPLE_API_KEY=sk-... \
-OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
- cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"
-```
-
-Or against the machine's own configured inference, in its real workspace:
-
-```bash
-OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."
-```
-
-Two agents on one runtime, BYOK or managed:
-
-```bash
-OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \
-OPENHUMAN_EXAMPLE_API_KEY=sk-... \
-OPENHUMAN_EXAMPLE_MODEL=gpt-5 \
- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-
-OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_... \
- cargo run -p openhuman-embed --example two_agents -- "Describe this directory."
-```
-
-Two users on one thread id, each with their own SaaS profile, fully offline
-(a local mock answers inference):
-
-```bash
-cargo run -p openhuman-embed --example profiles
-```
-
-`OPENHUMAN_EXAMPLE_BACKEND_URL` points non-inference backend calls
-somewhere specific, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill
-bundles. The repository-root `examples/embed_headless.rs` and
-`examples/embed_kernel.rs` drive `CoreBuilder` from `openhuman-core`
-directly, without this crate; run them with `cargo run --example
-embed_headless`.
-
-Tests worth reading alongside the examples, all under
-`crates/openhuman-embed/tests/`: `harness_embed.rs` proves
-`Harness` runs a real turn against a mocked provider with nothing else
-bound; `runtime_agents.rs` runs three agents with different
-providers, access tiers, skills, MCP servers and working directories on one
-runtime; `saas_profiles.rs` keeps two `ProfileRuntime` users apart on one
-thread id and relays a platform message onto a user's channel thread;
-`public_api.rs` pins the host-facing embedding contract at
-compile time. Run them with:
+The embedding documentation now lives in the [Embedding section](embed/README.md).
-```bash
-cargo test -p openhuman-embed --features inference,mcp,skills
-```
+Start with [installation](embed/installation.md) and the [quickstart](embed/quickstart.md), then use the [concepts](embed/concepts/README.md), [guides](embed/guides/README.md), [integrations](embed/integrations/README.md) and generated [cookbook](embed/cookbook.md).
-See also: [Jev](jev.md) for the decision model an embedded agent's tool
-search can use, [Pluggable engines](engines.md) for the inference, memory
-and search backends an agent chooses by config, and
-[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans
-API key unlocks in library mode.
+The public library uses one Runtime per process with independently configured Agents. For isolated authenticated users, read [profiles and SaaS](embed/concepts/profiles-saas.md).
diff --git a/gitbooks/developing/saas-profiles.md b/gitbooks/developing/saas-profiles.md
index 7e58e026f1..02d6c66014 100644
--- a/gitbooks/developing/saas-profiles.md
+++ b/gitbooks/developing/saas-profiles.md
@@ -16,7 +16,7 @@ token and the user id the gateway names.
This page covers deploying that service. The in-process variant, for a Rust
server that wants the same isolation without a gateway, is
-[`ProfileRuntime`](embedding.md#many-users-in-one-process-profileruntime).
+[`ProfileRuntime`](embed/concepts/profiles-saas.md).
The internals are in
[`profiles/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/profiles/README.md).
diff --git a/llms-full.txt b/llms-full.txt
new file mode 100644
index 0000000000..1658cc4d62
--- /dev/null
+++ b/llms-full.txt
@@ -0,0 +1,3018 @@
+# OpenHuman Embed
+
+> Embed OpenHuman runtimes and independently configured agents in Rust applications.
+
+- [Embedding OpenHuman](gitbooks/developing/embed/README.md): `openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+- [Embedding API reference](gitbooks/developing/embed/api-reference.md): Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+- [Embedding architecture](gitbooks/developing/embed/architecture.md): Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+- [Concepts](gitbooks/developing/embed/concepts/README.md): Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+- [Access and approvals](gitbooks/developing/embed/concepts/access-approvals.md): `Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+- [Agents](gitbooks/developing/embed/concepts/agents.md): Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+- [Channels](gitbooks/developing/embed/concepts/channels.md): `Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+- [Completer](gitbooks/developing/embed/concepts/completer.md): Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+- [Cron](gitbooks/developing/embed/concepts/cron.md): The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+- [Errors](gitbooks/developing/embed/concepts/errors.md): Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+- [Hooks and seams](gitbooks/developing/embed/concepts/hooks-seams.md): Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+- [MCP](gitbooks/developing/embed/concepts/mcp.md): MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+- [Memory](gitbooks/developing/embed/concepts/memory.md): `Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+- [Observability](gitbooks/developing/embed/concepts/observability.md): Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+- [Profiles and SaaS](gitbooks/developing/embed/concepts/profiles-saas.md): Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+- [Providers](gitbooks/developing/embed/concepts/providers.md): A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+- [Runtime defaults](gitbooks/developing/embed/concepts/runtime-defaults.md): The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+- [Runtime](gitbooks/developing/embed/concepts/runtime.md): A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+- [Skills](gitbooks/developing/embed/concepts/skills.md): A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+- [Testing](gitbooks/developing/embed/concepts/testing.md): The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+- [Tools](gitbooks/developing/embed/concepts/tools.md): An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+- [Turns and sessions](gitbooks/developing/embed/concepts/turns-sessions.md): `Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+- [Embedding FAQ](gitbooks/developing/embed/faq.md): An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See runtime and profiles.
+- [Embedding guides](gitbooks/developing/embed/guides/README.md): Choose the guide that matches your host:
+- [CLI chatbot](gitbooks/developing/embed/guides/cli-chatbot.md): Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+- [Deploy a server](gitbooks/developing/embed/guides/deploy-server.md): Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+- [Lean and headless hosts](gitbooks/developing/embed/guides/lean-headless.md): `RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+- [Test with a mock backend](gitbooks/developing/embed/guides/mock-backend-testing.md): Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+- [Multiple agents](gitbooks/developing/embed/guides/multi-agent.md): A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+- [SaaS with multiple tenants](gitbooks/developing/embed/guides/saas-multi-tenant.md): Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+- [Installation](gitbooks/developing/embed/installation.md): `openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+- [Embedding integrations](gitbooks/developing/embed/integrations/README.md): An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+- [Channels](gitbooks/developing/embed/integrations/channels.md): Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+- [Composio](gitbooks/developing/embed/integrations/composio.md): Composio calls use the host backend transport. Install that transport before booting a managed runtime; see TinyHumans managed inference. An explicit inference provider route supplies model inference, not the connector transport.
+- [Local and custom models](gitbooks/developing/embed/integrations/local-models.md): For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The OpenAI-compatible example controls can point a live example at that local server.
+- [MCP servers](gitbooks/developing/embed/integrations/mcp.md): Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+- [OpenAI-compatible providers and BYOK](gitbooks/developing/embed/integrations/openai-compatible.md): Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+- [Storage drivers](gitbooks/developing/embed/integrations/storage-drivers.md): Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+- [TinyHumans managed inference](gitbooks/developing/embed/integrations/tinyhumans-managed.md): Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+- [Quickstart](gitbooks/developing/embed/quickstart.md): Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+- [Embedding troubleshooting](gitbooks/developing/embed/troubleshooting.md): Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+- [OpenHuman Embed](crates/openhuman-embed/README.md): A typed Rust facade for running the OpenHuman core inside your application: one Runtime per process, with independently configured Agents.
+- [Embedding OpenHuman](gitbooks/developing/embedding.md): The embedding documentation now lives in the Embedding section.
+- [Cookbook](gitbooks/developing/embed/cookbook.md): Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+- [Compiled feature matrix](gitbooks/developing/embed/capability-matrix.md): This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+- [RuntimeBuilder setters](gitbooks/developing/embed/builder-setters.md): Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+- [API index](gitbooks/developing/embed/api-index.md): Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. Canonical facade source.
+- [Embed examples](crates/openhuman-embed/examples/README.md): Cookbook
+
+<!-- Source: gitbooks/developing/embed/README.md -->
+---
+description: "Run the OpenHuman core inside a Rust application with one Runtime and independently configured Agents."
+---
+
+# Embedding OpenHuman
+
+`openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+
+Build one `Runtime` per process and register the agents your product needs. Each agent can choose its own provider, prompt, working folder, tool scope, skills and MCP servers. Agents share runtime credentials; use `ProfileRuntime` when separate customers need separate credentials and workspaces.
+
+## Start here
+
+- [Installation](installation.md): dependency, Cargo gates, runtime setup and configuration.
+- [Quickstart](quickstart.md): run a verified offline turn, then choose a live provider explicitly.
+- [Architecture](architecture.md): ownership, lifecycle and the library chain.
+- [Concepts](concepts/README.md): the 18 public API concepts and their runtime/agent scope.
+- [Guides](guides/README.md): chatbots, multiple agents, SaaS, server deployment and tests.
+- [Integrations](integrations/README.md): inference, MCP, connectors, storage and channels.
+- [Cookbook](cookbook.md): generated inventory of executable examples.
+- [API reference](api-reference.md): local rustdoc, source links and generated builder knobs.
+
+## Choose the right surface
+
+| Requirement | Start with |
+| --- | --- |
+| One agent with a small host | `Harness` |
+| Several independently configured agents | `Runtime` and `AgentSpec` |
+| Stateless model generation | `Completer` |
+| Authenticated users with isolated credentials and state | `ProfileRuntime` |
+| Public JSON-RPC server or shipped desktop host | The `openhuman-rpc` host layer |
+
+The snippets in this section are injected from compiled, offline-tested Rust examples. Their full source files include the surrounding setup. `pnpm docs:check` checks source drift, local links, the generated API inventory and the published English mirror.
+
+See [FAQ](faq.md) for design choices and [troubleshooting](troubleshooting.md) for setup failures.
+
+<!-- Source: gitbooks/developing/embed/api-reference.md -->
+---
+description: "Use local rustdoc and source-derived indexes for the complete Embed public surface."
+---
+
+# Embedding API reference
+
+Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+
+The crate is currently `publish = false`; docs.rs links are a publication metadata target, not a claim that a live package reference exists. Local rustdoc and [canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs) are the current complete reference.
+
+## Generated inventories
+
+- [API index](api-index.md): names exported by the public facade and a versioned runtime report.
+- [Machine-readable API index](api-index.json): export names, builder signatures, capabilities and page paths.
+- [RuntimeBuilder setters](builder-setters.md): current public consuming setters with source locations.
+- [Compiled feature matrix](capability-matrix.md): the actual core gates from the default-feature capability-report executable.
+- [Cookbook](cookbook.md): example titles, run modes and required named facade features from source headers.
+
+The generated setter list is the authoritative knob inventory. It excludes static presets and borrowed inspection/build/run methods; those belong in local rustdoc. Core compiled gates, runtime module/domain selection and named facade exports are separate availability layers.
+
+## Public surface by purpose
+
+| Purpose | API starting point |
+| --- | --- |
+| Boot and inspect a host | `RuntimeBuilder`, `Runtime`, `RuntimeInfo` |
+| Register and remove scoped agents | `AgentSpec`, `Agent`, `AgentDefinitionSpec`, `RemoveAgent` |
+| Configure execution and decisions | `Access`, `SandboxModeSpec`, `Approvals`, `ApprovalHandler` |
+| Execute or stream native turns | `Turn`, `TurnOutcome`, `TurnStream`, `StreamEvent` |
+| Supply custom model adapters | `Provider` and `providers::ChatModel` |
+| Stateless generation | `Completer`, `CompletionRequest`, structured response helpers |
+| Typed non-turn domains | Memory and cron facades, config/auth/artifacts/chat surface |
+| Replace infrastructure ports | `seams`, `session_store`, memory engine and provider contracts |
+| Serve isolated customer profiles | `ProfileRuntime`, `ProfileHandle`, `SaasConfig` |
+
+## Versioned capability data
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The report's schema version is explicit. Read its fields rather than inferring capabilities from preset names, and handle future schema changes deliberately. It omits endpoint, credential, prompt and workspace values so hosts can expose build metadata without exposing private configuration.
+
+<!-- Source: gitbooks/developing/embed/architecture.md -->
+---
+description: "The host composes infrastructure around one core; agents derive scoped contexts over its runtime."
+---
+
+# Embedding architecture
+
+Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+
+## Ownership boundaries
+
+| Component | Owns |
+| --- | --- |
+| Your application | UI/HTTP transport, user authentication, supplied credentials, application tools and resource lifetimes |
+| OpenHuman core and Embed facade | Runtime composition, per-agent context, policy, approvals, sandbox selection and typed domain calls |
+| TinyAgents | Model/tool loop, parsing, dialects, durable sessions and transcript replay |
+| TinyInference | Native model/provider contracts and generic ordered fallback |
+| TinyTools | Shared tool traits and contract types |
+| Storage and module libraries | Their backend/module implementations; OpenHuman adapts and orchestrates them |
+
+The library chain is core → Embed → TinyHumans → RPC → app/CLI/TUI. Shipped hosts depend on the layer immediately below them and use its curated facades. Embed users should not build new integrations on doc-hidden `__host` internals.
+
+## Runtime composition versus agent scope
+
+Cargo features decide which implementations exist in an artifact. Runtime domains, services, tool groups and module selection narrow those compiled choices. Agent specs narrow the runtime further and add provider, access, prompt, skills, MCP and action-directory choices.
+
+A turn dispatches through the agent's native context, not through JSON-RPC or an operator fallback. Recursive child contexts inherit the parent host overrides, including custom provider and hook composition, while independent sibling agents remain separately scoped.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs), including runtime construction, imports and fixture setup.
+
+## Lifetime and isolation
+
+An agent handle keeps the core alive after the runtime handle is dropped. Explicit removal marks that instance removed, cancels turns and callbacks, denies parked approvals and clears its state/MCP registration. The ID remains reserved through cleanup, including natural last-handle destruction and cancellation of a started removal. Pointer-checked release prevents an old retained instance from removing a newer registry entry.
+
+Agent separation is not credential separation: all ordinary runtime agents share the operator's config path and credential root. Use [profiles](concepts/profiles-saas.md) for independently authenticated users. See [storage architecture](../architecture/storage.md) for scope/driver ownership and [agent harness architecture](../architecture/agent-harness.md) for session execution.
+
+<!-- Source: gitbooks/developing/embed/concepts/README.md -->
+---
+description: "The ownership and lifecycle rules behind the Embed public API."
+---
+
+# Concepts
+
+Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+
+- [Runtime](runtime.md): A Runtime owns one initialized core and the process-wide resources that its agents share.
+- [Runtime defaults](runtime-defaults.md): Runtime defaults form the starting point for newly registered agents; explicit agent settings override them.
+- [Agents](agents.md): An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime.
+- [Access and approvals](access-approvals.md): Access configures turn identity and permission policy; the host chooses how parked requests receive decisions.
+- [Providers](providers.md): A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback.
+- [Turns and sessions](turns-sessions.md): A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation.
+- [Tools](tools.md): Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools.
+- [MCP](mcp.md): MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists.
+- [Skills](skills.md): Skills are copied bundles of instructions and resources discovered inside an agent’s own home.
+- [Memory](memory.md): The typed memory facade binds a namespace before learning, retrieving or forgetting records.
+- [Cron](cron.md): Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents.
+- [Channels](channels.md): A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control.
+- [Profiles and SaaS](profiles-saas.md): ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams.
+- [Completer](completer.md): Completer sends stateless model requests without booting a Runtime or entering the agent tool loop.
+- [Hooks and seams](hooks-seams.md): Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries.
+- [Observability](observability.md): Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result.
+- [Testing](testing.md): Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services.
+- [Errors](errors.md): Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances.
+
+<!-- Source: gitbooks/developing/embed/concepts/access-approvals.md -->
+---
+description: "Access configures turn identity and permission policy; the host chooses how parked requests receive decisions."
+---
+
+# Access and approvals
+
+`Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+
+The core autonomy policy is disabled by default. Set `config.autonomy.enabled` when you require its command classification, approval gate, allowlist and budget enforcement. Platform isolation and the credential/system-root safety floor have separate responsibilities; a tool group filter is not an operating-system sandbox.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Autonomy policy defaults and installed approval gate | Origin, access tier, grants, trusted roots and scoped decisions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/approvals.rs#approvals -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("approved-marker");
+ let write_provider = support::scripted_provider(
+ vec![support::tool_call_completion(
+ "shell",
+ &serde_json::json!({"command": format!("touch {}", marker.display())}).to_string(),
+ )],
+ "approved",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("supervised")
+ .provider(support::route(&write_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(
+ openhuman_embed::Access::supervised()
+ .origin(openhuman_embed::AgentTurnOrigin::WebChat {
+ thread_id: "demo".into(),
+ client_id: "host".into(),
+ request_id: None,
+ })
+ .auto_approve(Vec::<String>::new())
+ .auto_approve_all(false)
+ .trust(
+ scratch.path().display().to_string(),
+ openhuman_embed::TrustedAccess::ReadWrite,
+ ),
+ )
+ .definition(
+ AgentDefinitionSpec::new().tools(ToolScopeSpec::Named(vec!["shell".into()])),
+ ),
+ )?;
+ let pending_agent = agent.clone();
+ let turn = tokio::spawn(async move { pending_agent.run("Create a marker").await });
+ let pending = support::eventually("approval", || {
+ agent.approvals().pending().ok()?.into_iter().next()
+ })
+ .await;
+ assert!(!marker.exists(), "execution waits for the host decision");
+ assert_eq!(pending.agent_id.as_deref(), Some("supervised"));
+ agent.approvals().decide(
+ &pending.request_id,
+ openhuman_embed::ApprovalDecision::ApproveOnce,
+ )?;
+ assert_eq!(turn.await??.reply, "approved");
+ assert!(marker.exists());
+ assert!(agent.approvals().pending()?.is_empty());
+ println!("parked write executed only after approval");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified example enables autonomy before building the runtime. It starts a real shell write, observes that no marker exists while the call is parked, and creates it only after `ApproveOnce`. `agent.approvals()` lists and decides only that instance's requests. A removed instance returns an empty pending list and rejects decisions even if the same public ID has been reused.
+
+For asynchronous integration use `AgentSpec::approval_handler` or retain the handle returned by `Agent::handle_approvals`. Dropping a subscription cancels its pending decision future; it does not silently approve the request. Agent removal cancels both builder and live callbacks. Continue with the [approval callback example](../cookbook.md#polling-and-callback-approvals-with-cancellation) and [sandbox guide](../guides/multi-agent.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/agents.md -->
+---
+description: "An Agent combines one identity, derived context and independently configured tool/model behavior on a shared Runtime."
+---
+
+# Agents
+
+Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+
+Keep `action_dir` separate from the internal workspace. The action directory is where tools act; the agent home stores internal transcripts, skills and other state. The example gives a reviewer and a fixer distinct folders and prompts while sharing one provider connection setup.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Core, shared configuration path and registry capacity | ID, context, prompt, action directory, provider and per-agent stores |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+IDs stay reserved until teardown completes, including while the last handle's destructor is clearing state. `remove_agent(id).await` marks retained handles removed, cancels active turns, denies parked approvals and releases the ID after cleanup. Add `.purge()` only when the agent's persisted home should also be deleted. Cancelling a started removal still performs teardown and a requested purge.
+
+An old polling handle or approval callback never follows a reused ID to its replacement. Active host tools cancel cooperatively and may finish their external work after removal; the host still owns those external lifetimes. See [turns and sessions](turns-sessions.md) and [access and approvals](access-approvals.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/channels.md -->
+---
+description: "A channel listener binds external messages to one registered agent and keeps transport lifecycle under host control."
+---
+
+# Channels
+
+`Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+
+The named Embed `channels` feature is enabled by default. The runtime must also allow the channel family. Create listeners inside the Tokio runtime after their agents have been registered.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Channel implementation, listener registry and runtime domain ceiling | Bound agent, conversation identity and external-message access context |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The verified Telegram example uses a local Bot API stub, so the channel test does not contact Telegram. Its live mode requires explicit example credentials and remains opt-in.
+
+External messages use `ExternalChannel` origin and a read-only cap. Model-requested writes and other external effects are not parked for approval from the sender. Keep public-chat tools read-only and perform authorized side effects in host code or a separately configured job. When the bound agent is removed, channel work fails as unavailable instead of falling back to the operator. See [channel integration](../integrations/channels.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/completer.md -->
+---
+description: "Completer sends stateless model requests without booting a Runtime or entering the agent tool loop."
+---
+
+# Completer
+
+Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+
+A standalone completer does not claim the process runtime slot. An agent-backed completion uses the agent's effective configuration but still has no implicit durable session. Keep conversation state in your application if you need several completion calls to form a conversation.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| No runtime required for a standalone routed Completer | Optional effective agent configuration; no implicit tools or transcript |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/completer.rs#completer -->
+
+```rust
+ let route = support::example_provider(&provider)?;
+ let completer = openhuman_embed::Completer::new(route.route().expect("explicit route").clone());
+ let response = completer
+ .complete(openhuman_embed::CompletionRequest::new(
+ route.model_id().expect("explicit model"),
+ vec![openhuman_embed::ChatMessage::user("Say hello")],
+ ))
+ .await?;
+ assert!(!response.text.is_empty());
+ if support::offline() {
+ assert_eq!(response.text, "completion reply");
+ assert_eq!(support::chat_requests(&provider).await.len(), 1);
+ }
+ println!("{}", response.text);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks that exactly one inference request was made and verifies the returned text. It uses a local provider fixture by default; the source contains the explicit opt-in live route path.
+
+Choose `Agent` when a model should call tools, resume a durable thread or execute with an agent's access context. Choose the structured completion helpers when the host only needs a validated data result. For routes and transport failures see [providers](providers.md) and [errors](errors.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/cron.md -->
+---
+description: "Cron provides durable named jobs, explicit run-now execution and job history addressed to registered agents."
+---
+
+# Cron
+
+The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+
+Background scheduling is a runtime service choice. Explicit `run_now` is useful for tests and host-triggered execution without relying on wall-clock scheduling. Keep the agent registered while scheduled work should be available.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cron storage, scheduler service and system-job handlers | Addressed job target and the agent configuration used for its turn |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/cron.rs#cron -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("scheduled"))?;
+ let cron = runtime.cron();
+ let spec = openhuman_embed::JobSpec::agent(
+ "daily",
+ agent.id(),
+ "Say hello",
+ openhuman_embed::JobSchedule::Cron {
+ expr: "0 0 * * *".into(),
+ tz: None,
+ },
+ );
+ let first = cron.upsert(spec.clone())?;
+ assert_eq!(cron.upsert(spec)?.id, first.id);
+ let run = cron.run_now("daily").await?;
+ assert!(run.success, "{}", run.output);
+ if support::offline() {
+ assert!(run.output.contains("hello from the stub"));
+ }
+ assert_eq!(cron.runs("daily", 1)?[0].status, "ok");
+ assert!(cron.remove("daily")?);
+ assert!(cron.list()?.is_empty());
+ println!("cron execution and history verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks stable upsert identity, executes a job immediately, inspects a successful run record, and removes the job. No test waits for a daily schedule to arrive.
+
+Removing or dropping an agent deregisters its context, leaving addressed cron jobs dormant rather than silently running them as the operator. Hosts can register runtime system-job handlers for work they own outside a model turn. Review [runtime configuration](runtime-defaults.md) and [channels](channels.md) when mixing scheduled work with public chat input.
+
+<!-- Source: gitbooks/developing/embed/concepts/errors.md -->
+---
+description: "Typed errors distinguish build availability, expected domain states, host setup failures and removed agent instances."
+---
+
+# Errors
+
+Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+
+A structured `CoreError::Domain` carries a stable kind and `expected_user_state`. Expected stale-session or missing-resource states should be shown as notices rather than treated as internal faults. `Decode` signals a facade/domain shape mismatch; retrying unchanged input does not repair it.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Boot errors, unavailable domains and shared transport setup | Registration errors, scoped domain failures and AgentRemoved on retained handles |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/sandbox_access.rs#sandbox_access -->
+
+```rust
+ let scratch = tempfile::tempdir()?;
+ let marker = scratch.path().join("attempted-write");
+ let attempted_write = support::tool_call_completion(
+ "write_file",
+ &serde_json::json!({
+ "path": marker.display().to_string(), "content": "example"
+ })
+ .to_string(),
+ );
+ let read_provider = support::scripted_provider(vec![attempted_write], "write refused").await;
+ let read = runtime.agent(
+ AgentSpec::new("read")
+ .provider(support::route(&read_provider, "fixture"))
+ .action_dir(scratch.path())
+ .access(openhuman_embed::Access::readonly())
+ .definition(
+ AgentDefinitionSpec::new().sandbox(openhuman_embed::SandboxModeSpec::ReadOnly),
+ ),
+ )?;
+ let full = runtime.agent(AgentSpec::new("full").access(openhuman_embed::Access::full()))?;
+ assert_ne!(read.config().autonomy.level, full.config().autonomy.level);
+ assert!(!read.run("Write a marker").await?.reply.is_empty());
+ assert!(
+ !marker.exists(),
+ "readonly sandbox must refuse the attempted write"
+ );
+ let requests = support::chat_requests(&read_provider).await;
+ assert!(!support::tool_names(&requests[0]).contains(&"write_file".to_string()));
+ println!("readonly sandbox refused a model-requested write");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example's refused write is handled as a tool result while the turn can still finish with a reply. Do not assume every rejected tool action is a failed turn. Conversely, a finished stream can contain an error; always inspect `StreamEvent::Finished`.
+
+Bearer routes refuse non-TLS remote endpoints before sending credentials. `BACKEND_UNAVAILABLE` means the embed-only host has no backend transport installed; check the host layer before rotating keys. Agent removal makes later turns on retained handles return `AgentRemoved`, even when its ID now belongs to another instance. See [troubleshooting](../troubleshooting.md) and [provider integration](../integrations/openai-compatible.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/hooks-seams.md -->
+---
+description: "Host seams replace infrastructure ports; hooks observe or control selected turn and tool boundaries."
+---
+
+# Hooks and seams
+
+Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+
+Post-turn and tool hooks can be registered runtime-wide or on one agent. Agent hooks compose with parent runtime hooks and do not leak into sibling contexts. Use stable hook names to replace or remove runtime registrations through the live API; changes apply to subsequent turns.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Shared port implementations and named global hook registrations | Scoped hooks and host overrides inherited by recursive child contexts |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/hooks.rs#hooks -->
+
+```rust
+ let count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let agent = runtime.agent(
+ AgentSpec::new("hooked").post_turn_hook(std::sync::Arc::new(Counter(count.clone()))),
+ )?;
+ let sibling = runtime.agent(AgentSpec::new("sibling"))?;
+ assert!(!agent.run("Hello hook").await?.reply.is_empty());
+ support::eventually("post-turn hook", || {
+ (count.load(std::sync::atomic::Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ assert!(!sibling.run("Hello sibling").await?.reply.is_empty());
+ assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1);
+ println!("post-turn hook isolated to its agent");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example verifies that an agent-local post-turn counter observes the configured agent and not its sibling. Runtime live add/remove behavior is demonstrated in the [runtime events example](../cookbook.md#runtime-lifecycle-events-and-live-hook-registration).
+
+Removing or replacing a builder-installed named hook through the runtime API affects that registration too; the runtime tracks and restores prior process slots when its seam ownership ends. Keep hooks fast, cancellation-aware and free of sensitive logging. Use the generated [setter list](../builder-setters.md) and [API reference](../api-reference.md) for the actual port signatures.
+
+<!-- Source: gitbooks/developing/embed/concepts/mcp.md -->
+---
+description: "MCP servers add remote tool discovery and execution to one agent, with explicit server configuration and tool allowlists."
+---
+
+# MCP
+
+MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+
+Enable the named Embed `mcp` Cargo feature for `McpServer` and the agent setter. The default core may already contain MCP code, but a core capability flag does not activate a separately gated Embed API. Runtime domain selection must also allow the MCP family.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Compiled MCP implementation and runtime domain ceiling | Server configuration, auth, discovery and allowed remote tools |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses a real loopback protocol stub: it verifies initialization, `tools/list`, and `tools/call`, then checks that the model saw the remote result. It does not call an external MCP service or require credentials.
+
+Tool allowlists reduce the remote catalog before model disclosure. Server authentication remains host-owned input, and remote tool side effects still pass through the relevant execution/access policy. Removing the agent evicts its MCP host after old-instance teardown, before the ID can be reused. See the [MCP integration](../integrations/mcp.md) for deployment setup.
+
+<!-- Source: gitbooks/developing/embed/concepts/memory.md -->
+---
+description: "The typed memory facade binds a namespace before learning, retrieving or forgetting records."
+---
+
+# Memory
+
+`Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+
+A custom `memory_engine` can replace the default engine for a host or test. An agent's `MemoryBinding` configures its own memory context, while the runtime owns engine availability. Scope namespaces separately from provider/model choices: changing inference does not move a record to another tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Memory engine seam and available memory domain | MemoryBinding, acting context and bound namespace |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/memory.rs#memory -->
+
+```rust
+ let acme = runtime.memory("team:acme")?;
+ let other = runtime.memory("team:other")?;
+ let params = serde_json::from_value(serde_json::json!({"text":"Acme ships on Fridays"}))?;
+ let learned = acme.learn(params).await?;
+ let hits = acme.get(vec![learned.id.clone()]).await?;
+ assert_eq!(hits.len(), 1);
+ assert_eq!(hits[0].meta.namespace.to_string(), "team:acme");
+ assert!(other.get(vec![learned.id.clone()]).await?.is_empty());
+ assert_eq!(other.forget(vec![learned.id.clone()]).await?.forgotten, 0);
+ assert_eq!(acme.forget(vec![learned.id]).await?.forgotten, 1);
+ println!("memory learning, tenant isolation and deletion verified");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example uses the reference in-memory engine and proves that another namespace cannot retrieve or forget the first namespace's record. Forgetting succeeds only through the owning namespace. This is a scope test, not a persistence claim; choose a durable engine/backend for application state that must survive restarts.
+
+Background conversation ingestion can run independently of a completed turn. Tests should disable unrelated learning/ingest activity when asserting ephemeral-workspace cleanup. See [runtime defaults](runtime-defaults.md), [storage drivers](../integrations/storage-drivers.md), and the [memory architecture](../../architecture/memory.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/observability.md -->
+---
+description: "Runtime metadata events track lifecycle and approvals; turn streams carry per-turn progress and the final result."
+---
+
+# Observability
+
+Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+
+Runtime events contain lifecycle metadata, not user prompts or model output. Detailed text/tool progress belongs to the explicitly requested turn stream. A bounded event receiver reports lag explicitly rather than silently claiming that it delivered every event.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Runtime sequence, content-safe lifecycle feed and registered-agent filter | Per-call turn correlation and opt-in text/tool progress stream |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/runtime_events.rs#runtime_events -->
+
+```rust
+ let mut events = runtime.events();
+ let count = Arc::new(AtomicUsize::new(0));
+ runtime.post_turn_hook("live-counter", Some(Arc::new(Counter(count.clone()))));
+ let agent = runtime.agent(AgentSpec::new("observed"))?;
+ assert_eq!(agent.run("private payload one").await?.reply, "event reply");
+ support::eventually("runtime hook", || {
+ (count.load(Ordering::SeqCst) == 1).then_some(())
+ })
+ .await;
+ runtime.post_turn_hook("live-counter", None);
+ assert_eq!(agent.run("private payload two").await?.reply, "event reply");
+ assert_eq!(
+ count.load(Ordering::SeqCst),
+ 1,
+ "removed hook stops observing turns"
+ );
+ runtime.remove_agent(agent.id()).await?;
+ let mut previous = 0;
+ let (mut added, mut started, mut ended) = (0, 0, 0);
+ loop {
+ let event =
+ tokio::time::timeout(std::time::Duration::from_secs(5), events.recv()).await??;
+ assert!(event.sequence > previous);
+ previous = event.sequence;
+ assert_eq!(event.agent_id.as_deref(), Some("observed"));
+ assert!(!serde_json::to_string(&event)?.contains("private payload"));
+ match event.kind {
+ RuntimeEventKind::AgentAdded => added += 1,
+ RuntimeEventKind::TurnStarted => {
+ assert!(event.turn_id.is_some());
+ started += 1;
+ }
+ RuntimeEventKind::TurnEnded { success } => {
+ assert!(success);
+ ended += 1;
+ }
+ RuntimeEventKind::AgentRemoved => break,
+ _ => {}
+ }
+ }
+ assert_eq!((added, started, ended), (1, 2, 2));
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks ordered add/start/end/remove events and confirms that private prompt text is absent from serialized metadata. Approval events are filtered to agents registered on this runtime. Correlation follows the effective origin thread; a request's later decision keeps its original turn correlation after the turn has ended.
+
+When simultaneous turns share an origin thread, approval correlation can be ambiguous and its turn ID is absent rather than guessed. Handle receiver lag by refreshing state, and do not send text from `AgentProgress` to content-free analytics. See [turns and sessions](turns-sessions.md), [approvals](access-approvals.md), and [testing](testing.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/profiles-saas.md -->
+---
+description: "ProfileRuntime isolates authenticated users by workspace, credentials, conversations and event streams."
+---
+
+# Profiles and SaaS
+
+Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+
+Profile mode claims the process separately from ordinary `Runtime` and `Harness`. Its root must satisfy the boot guard: absolute, existing, outside the operator's workspace and not world-writable. Remove single-user workspace/token environment variables before booting a profile server.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| One profile host, shared compiled core and managed backend transport | Per-profile credential, workspace, threads, memory and event access |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example creates Alice and Bob with the same thread name and verifies that each transcript contains only its own note. Handles keep their profiles open; release/idle eviction can close a profile only after those handles are dropped.
+
+Production managed calls need the TinyHumans transport installed by the host layer. `ProfileHandle::call` exposes the reviewed user surface rather than arbitrary operator controllers. Profiles do not make a shared file-system action directory safe automatically; provision external application resources per user too. See [SaaS deployment guide](../guides/saas-multi-tenant.md) and [SaaS architecture](../../saas-profiles.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/providers.md -->
+---
+description: "A provider supplies a route or native ChatModel implementation, with agent overrides and optional ordered fallback."
+---
+
+# Providers
+
+A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+
+Named workload roles bind an adapter to selections such as `hint:coding`. The example proves that the role-pinned model bypasses the primary fallback chain. These pins are explicit host configuration; they do not ask the model to decide its own provider.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default route/model and native adapter chain | Provider override, model selection and workload hint |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Ordered fallback advances only on eligible provider failures before visible output. Validation or unsupported-input failures stop the chain. Once text, reasoning or tool-call content becomes visible, the chosen stream keeps its identity and a later failure is reported without switching providers. Requests, options, correlation metadata and cancellation remain attached to the selected adapter.
+
+Use HTTPS when sending bearer credentials; loopback HTTP is supported for local test/model servers. Managed inference needs the TinyHumans host transport and a runtime credential. See [OpenAI-compatible integration](../integrations/openai-compatible.md), [managed integration](../integrations/tinyhumans-managed.md), and [local models](../integrations/local-models.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/runtime-defaults.md -->
+---
+description: "Runtime defaults form the starting point for newly registered agents; explicit agent settings override them."
+---
+
+# Runtime defaults
+
+The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+
+`Runtime::defaults()` returns a snapshot. Runtime default setters affect agents created afterward; existing agents retain the configuration they were built with. Configure an explicit agent override when its behavior must remain independent of future runtime defaults.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Default provider, access and generation settings | Explicit override captured when AgentSpec is registered |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example checks the request bodies actually received by both providers, including model, temperature and maximum tokens. This distinction matters when testing a configuration change: a correct defaults snapshot alone does not prove that inference received those values.
+
+Use the generated [builder setters](../builder-setters.md) for the current knob list. [Configuration and installation](../installation.md) explain runtime configuration discovery; [providers](providers.md) cover route selection and native models.
+
+<!-- Source: gitbooks/developing/embed/concepts/runtime.md -->
+---
+description: "A Runtime owns one initialized core and the process-wide resources that its agents share."
+---
+
+# Runtime
+
+A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+
+The process guard rejects a second runtime with `RuntimeError::AlreadyRunning`. Independent customer credentials and workspaces require [profiles](profiles-saas.md), rather than several ordinary runtimes. `Harness` is the one-agent shorthand and exposes its underlying runtime and agent if you later need more agents.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Cargo gates and selected domains/services | Provider, prompt, working folder and tool scope |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+`RuntimeBuilder::describe()` reports a plan before boot; `Runtime::capabilities()` reports resolved configuration afterward. The versioned metadata excludes credentials, endpoints, prompts and workspace paths. Use its `configuration_resolved` flag when deciding whether to treat an inspection result as effective configuration.
+
+Dropping the runtime handle does not tear down the core while an agent still holds it. Drop listeners, agents and the runtime before restarting the host in the same process. See [architecture](../architecture.md), [defaults](runtime-defaults.md), and the generated [builder setters](../builder-setters.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/skills.md -->
+---
+description: "Skills are copied bundles of instructions and resources discovered inside an agent\u2019s own home."
+---
+
+# Skills
+
+A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+
+Enable the named Embed `skills` feature for skill setters and registry access. Library agents hide the operator's user skill directory unless `include_user_skills(true)` is explicitly selected. Treat skill installation as part of the agent's configuration, rather than reading arbitrary operator files into every tenant.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Skill registry seam and default user-skill policy | Copied bundles, discovery context and explicit user-skill opt-in |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/skills.rs#skills -->
+
+```rust
+ let skills = tempfile::tempdir()?;
+ std::fs::create_dir(skills.path().join("review"))?;
+ std::fs::write(skills.path().join("review/SKILL.md"),
+ "---\nname: review\ndescription: Review Rust functions carefully.\n---\nCheck error paths.\n")?;
+ let agent = runtime.agent(AgentSpec::new("skilled").skills_dir(skills.path()))?;
+ let copied = agent
+ .workspace_dir()
+ .join("agents/skilled/skills/review/SKILL.md");
+ assert_eq!(
+ std::fs::read_to_string(&copied)?,
+ std::fs::read_to_string(skills.path().join("review/SKILL.md"))?
+ );
+ assert!(!std::fs::symlink_metadata(copied)?.file_type().is_symlink());
+ assert!(!agent.run("Hello").await?.reply.is_empty());
+ println!("skill bundle copied without symlinks");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example writes a bundle, registers an agent, checks the copied contents and verifies that the destination is not a symlink. Use the same directory layout for production bundles; do not depend on the fixture's temporary directory lifetime.
+
+A resumed session's prompt is frozen, so adding or editing a bundle does not rewrite an existing conversation's recorded prefix. Start a new session when you want updated instructions to become visible. See [turns and sessions](turns-sessions.md) and the generated [builder setters](../builder-setters.md) for runtime policy knobs.
+
+<!-- Source: gitbooks/developing/embed/concepts/testing.md -->
+---
+description: "Deterministic local providers and explicit observations prove behavior without contacting real inference or backend services."
+---
+
+# Testing
+
+The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+
+A native `ChatModel<()>` stub is useful for provider selection and cancellation tests without HTTP. Protocol-level stubs remain useful for OpenAI-compatible routing, MCP or messaging transport behavior. Pick the boundary whose behavior your host needs to verify.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Offline configuration, mock backend and injected model/engine ports | Isolated temp action directories, deterministic IDs and scoped assertions |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+Run the offline example suite with `node scripts/run-embed-examples.mjs`; it clears inherited credentials/workspaces and uses one union feature graph for all examples. Run embed unit/integration tests with `cargo test -p openhuman-embed --features mcp,skills,channels,storage-sqlite --lib --tests -- --test-threads=1`.
+
+Build your Tokio workers with the documented large stack constants for nested agent turns. Use channels, cancellation guards and bounded waits to prove lifecycle transitions instead of sleeps. The [mock-backend guide](../guides/mock-backend-testing.md) covers host fixtures, and [troubleshooting](../troubleshooting.md) distinguishes compile gates from runtime availability.
+
+<!-- Source: gitbooks/developing/embed/concepts/tools.md -->
+---
+description: "Tool catalogs expose only the allowed execution surface; host tools use the same native Tool contract as built-in tools."
+---
+
+# Tools
+
+An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+
+`AgentSpec::tools` is a per-turn factory returning `HostTurnTools`. Factories can attach the turn's context to their executors without sharing mutable tool state across unrelated sessions. Import `Tool` and `ToolResult` from `openhuman_embed` so their types match the vendored implementation used by the core.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Domain/tool-group ceiling and shared execution policy | ToolScopeSpec, advertised host belt, attachments and prompt |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The example drives an actual host tool call and inspects the provider's advertised catalog: it contains only `host_ping`, which executes exactly once. A host executor remains responsible for authorizing its own application operations. Catalog visibility narrows what the model sees; it is not a substitute for permission checks or sandboxing.
+
+Runtime tool hooks apply across agents; local hooks observe only their configured agent. Tool attachments can be added and removed for later turns, while existing durable sessions retain recorded declarations. See [hooks](hooks-seams.md), [MCP](mcp.md), and [access and approvals](access-approvals.md).
+
+<!-- Source: gitbooks/developing/embed/concepts/turns-sessions.md -->
+---
+description: "A turn is one native model/tool loop; a session is the durable identity that makes subsequent turns a conversation."
+---
+
+# Turns and sessions
+
+`Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+
+`Agent::stream` returns a bounded `TurnStream`. Drain it while the turn is running: progress includes visible deltas and tool lifecycle notifications, followed by one `StreamEvent::Finished` containing the typed final result. Dropping the stream cancels its turn and recursive child work cooperatively.
+
+## Runtime and agent scope
+
+| Runtime responsibility | Agent or call responsibility |
+| --- | --- |
+| Session store provider and shared progress/event infrastructure | Durable agent/thread identity, transcript and per-call cancellation |
+
+## Verified example
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs). The full file includes imports, runtime setup and local fixtures used by this excerpt.
+
+## Behavior to account for
+
+The stream example checks that deltas precede the final result and that collected and streaming replies agree. A cancellation token passed to a turn is preserved by streaming; cancellation unblocks forwarding even when the consumer has stopped draining a full buffer.
+
+The harness derives transcript paths from the thread and agent IDs without a timestamp. Resumed sessions reuse their recorded system prompt and tool declarations; edits to prompts, skills or integrations apply to new sessions. Compaction seals a generation and opens a child instead of erasing history. See [observability](observability.md) for session IDs versus per-call turn IDs, and [API reference](../api-reference.md) for the session-store port.
+
+<!-- Source: gitbooks/developing/embed/faq.md -->
+---
+description: "Answers to common host, lifecycle, feature and provider choices."
+---
+
+# Embedding FAQ
+
+## Can I create more than one runtime?
+
+An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See [runtime](concepts/runtime.md) and [profiles](concepts/profiles-saas.md).
+
+## Is an agent clone an independent agent?
+
+No. It is another handle to the same agent instance, context and state. Register a different `AgentSpec` ID for a separate agent. Runtime credentials are still shared, so agent IDs alone do not isolate authenticated customers.
+
+## Does lean mean fewer dependencies?
+
+`RuntimeBuilder::lean()` selects a smaller runtime surface. Cargo still compiles enabled gates; use `--no-default-features` and explicit named gates for graph reduction. The [compiled matrix](capability-matrix.md) reports one fixed default build, and the [lean guide](guides/lean-headless.md) separates those controls.
+
+## Why do MCP or skills methods disappear while the report says they are compiled?
+
+The report describes core Cargo gates. Named Embed gates control facade exports too. Enable Embed's `mcp` or `skills` feature for their setters/re-exports, even when core defaults already compile the implementation. `channels` is named in Embed defaults.
+
+## Can I supply an in-process model without HTTP?
+
+Yes: `Provider::custom` takes the native `ChatModel<()>` contract. A provider can add an ordered fallback chain and explicit workload role pins. [Providers](concepts/providers.md) describes the rule that fallback stops after visible output.
+
+## Do I need the backend for every agent turn?
+
+An explicit BYOK/local/native provider can run independently of hosted inference. Hosted integrations, voice, billing or other backend surfaces need an installed backend transport and a credential. Use the [TinyHumans layer](integrations/tinyhumans-managed.md) for managed calls; Embed alone reports backend unavailable.
+
+## Can an old handle control a replacement with the same ID?
+
+No. Removal binds cancellation, callbacks and polling handles to the original lifecycle. It keeps the ID reserved until teardown/purge completes; later old handles cannot decide replacement approvals or send replacement turns. Dropping a handle does not purge its persisted home.
+
+## Why did a prompt or tool change not affect a resumed thread?
+
+A resumed session reuses recorded system messages and tool declarations. Start a new session for the changed prompt/tool catalog. Compaction preserves prior generations; it does not rewrite the old conversation. See [turns and sessions](concepts/turns-sessions.md).
+
+## Where is the complete builder knob list?
+
+[RuntimeBuilder setters](builder-setters.md) is generated from actual consuming public setters, with source signatures. Host/weight presets and non-setter methods are intentionally documented through [API reference](api-reference.md).
+
+<!-- Source: gitbooks/developing/embed/guides/README.md -->
+---
+description: "Build a chatbot, host multiple agents, serve profiles, or test an embedded runtime."
+icon: code
+---
+
+# Embedding guides
+
+Choose the guide that matches your host:
+
+- [CLI chatbot](cli-chatbot.md): create an agent and collect or stream its reply.
+- [Multiple agents](multi-agent.md): give agents independent prompts, access, and working folders.
+- [SaaS with multiple tenants](saas-multi-tenant.md): isolate user state through profiles.
+- [Deploy a server](deploy-server.md): call an embedded agent from your HTTP host.
+- [Lean and headless hosts](lean-headless.md): select runtime services and Cargo features separately.
+- [Test with a mock backend](mock-backend-testing.md): run the entire example suite offline.
+
+Start with [Embedding](../README.md) for the library boundary and quickstart. See [Integrations](../integrations/README.md) for providers, storage, MCP, and channels.
+
+<!-- Source: gitbooks/developing/embed/guides/cli-chatbot.md -->
+---
+description: "Collect a reply or consume progress events in a Rust command-line host."
+icon: code
+---
+
+# CLI chatbot
+
+Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example run_turn` from the repository root. It uses a loopback provider and temporary state. The [complete run_turn example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) includes imports, runtime construction, and offline setup.
+
+For incremental output, consume `agent.stream(...)` until `StreamEvent::Finished`. Progress includes text deltas; the final event carries the same outcome shape as `run`. Dropping the stream cancels the underlying turn.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/streaming.rs#streaming -->
+
+```rust
+ let agent = runtime.agent(AgentSpec::new("streamer"))?;
+ let mut stream = agent.stream("Hello streaming");
+ let mut count = 0;
+ let mut deltas = String::new();
+ let mut finished = None;
+ while let Some(event) = stream.recv().await {
+ match event {
+ openhuman_embed::StreamEvent::Progress(progress) => {
+ println!("{progress:?}");
+ if let openhuman_embed::AgentProgress::TextDelta { delta, .. } = progress {
+ assert!(finished.is_none(), "text deltas precede Finished");
+ deltas.push_str(&delta);
+ }
+ count += 1;
+ }
+ openhuman_embed::StreamEvent::Finished(result) => finished = Some(result?),
+ }
+ }
+ let outcome = finished.expect("stream ends with an outcome");
+ assert!(!outcome.reply.is_empty());
+ assert!(
+ !deltas.is_empty(),
+ "stream must publish visible text before Finished"
+ );
+ assert_eq!(deltas, outcome.reply);
+ if support::offline() {
+ let regular = agent.run("Hello streaming").await?;
+ assert_eq!(
+ outcome.reply, regular.reply,
+ "streaming and collected turns agree"
+ );
+ }
+ println!("progress events: {count}");
+```
+
+<!-- END EMBED -->
+
+The [complete streaming example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) checks that text arrives before completion and that the offline streamed reply equals a collected reply. [Provider configuration](../integrations/openai-compatible.md) covers explicit live inference.
+
+<!-- Source: gitbooks/developing/embed/guides/deploy-server.md -->
+---
+description: "Invoke agents from a host-owned HTTP service without adding RPC to Embed."
+icon: code
+---
+
+# Deploy a server
+
+Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/server.rs#server -->
+
+```rust
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let agent = runtime.agent(
+ AgentSpec::new("http-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
+ let address = listener.local_addr()?;
+ // A real host should use its HTTP framework and authenticate requests.
+ // This single-request fixture keeps the library dependency direction intact.
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await?;
+ let mut request = vec![0; 4096];
+ let length = socket.read(&mut request).await?;
+ assert!(String::from_utf8_lossy(&request[..length]).starts_with("GET /hello "));
+ let reply = agent.run("Say hello").await?.reply;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
+ reply.len(),
+ reply
+ );
+ socket.write_all(response.as_bytes()).await?;
+ Ok::<_, anyhow::Error>(())
+ });
+ let reply = reqwest::get(format!("http://{address}/hello"))
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ assert!(!reply.is_empty());
+ if support::offline() {
+ assert_eq!(reply, "hello from the stub");
+ }
+ server.await??;
+ println!("host HTTP request reached the in-process agent");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example server`. The [complete server example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) checks the HTTP response against the deterministic provider reply.
+
+Use your HTTP framework for a deployed service. The example's one-request parser is deliberately small; a deployed host must handle authentication, request limits, cancellation, and shutdown. Select agents from authenticated host state. For multiple users, use [SaaS profiles](saas-multi-tenant.md).
+
+If your host needs OpenHuman's existing JSON-RPC server, depend on `openhuman-rpc`, the layer above Embed. Adding that dependency to Embed would reverse the crate chain. [Channels](../integrations/channels.md) provide another way to deliver messages to bound agents.
+
+<!-- Source: gitbooks/developing/embed/guides/lean-headless.md -->
+---
+description: "Control runtime activity separately from compile-time Cargo features."
+icon: code
+---
+
+# Lean and headless hosts
+
+`RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/lean_headless.rs#lean_headless -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.weight, openhuman_embed::WeightClass::Lean);
+ assert!(info.services.is_empty());
+ let agent = runtime.agent(
+ AgentSpec::new("lean").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ assert!(!agent.run("Hello lean runtime").await?.reply.is_empty());
+ println!("lean runtime runs a turn without background services");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example lean_headless`. The [complete lean_headless example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) uses `ServiceSet::none()`, verifies the lean capability report, and completes an actual turn. For a host crate that needs fewer compiled features, disable default features on its Embed dependency and enable only the gates it needs. Verify enabled and disabled builds for that selection.
+
+A headless host also owns process setup: initialize its encryption key before storing credentials, choose its state directory, and keep the runtime alive until shutdown. The example support code uses a random fixture key and temporary credential directory; deployed hosts supply a durable key and durable workspace.
+
+[Storage drivers](../integrations/storage-drivers.md) covers persistent backends. The [complete capability_report example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) reports compiled features and active services without exposing provider keys or URLs.
+
+<!-- Source: gitbooks/developing/embed/guides/mock-backend-testing.md -->
+---
+description: "Run the embedding examples offline and verify behavior, not just compilation."
+icon: code
+---
+
+# Test with a mock backend
+
+Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+
+The shared support module uses loopback Wiremock servers for backend and inference requests. It disables unrelated online services and supplies isolated keyring state. Examples assert replies, transmitted model settings, tool results, and state isolation. MCP and Telegram use their real protocol shapes against local stubs; SQLite performs real local writes.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/host_tools.rs#host_tools -->
+
+```rust
+ let calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let recorded_calls = calls.clone();
+ let tool_provider = support::scripted_provider(
+ vec![support::tool_call_completion("host_ping", "{}")],
+ "pong complete",
+ )
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("host-tools")
+ .provider(support::route(&tool_provider, "fixture"))
+ .definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Use host_ping")
+ .tools(ToolScopeSpec::HostOnly),
+ )
+ .tools(move |_| {
+ openhuman_embed::HostTurnTools::advertised(vec![Box::new(Ping(
+ recorded_calls.clone(),
+ ))])
+ }),
+ )?;
+ assert_eq!(agent.run("Ping").await?.reply, "pong complete");
+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
+ let requests = support::chat_requests(&tool_provider).await;
+ assert_eq!(support::tool_names(&requests[0]), vec!["host_ping"]);
+ assert!(support::tool_results(&requests[1]).contains("pong"));
+ println!("host_ping executed once; only host tools advertised");
+```
+
+<!-- END EMBED -->
+
+The [complete host_tools example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) checks the advertised catalog, executes a host tool exactly once, and verifies that its result reaches the next model request. This catches a host adapter that advertises a tool but never runs it.
+
+Run a single gated example with `cargo run -p openhuman-embed --example mcp --features mcp`, or use the full runner to select all gates automatically. The individual examples default to offline mode. Only the [explicit live provider options](../integrations/openai-compatible.md) and [MongoDB live option](../integrations/storage-drivers.md) contact configured services.
+
+<!-- Source: gitbooks/developing/embed/guides/multi-agent.md -->
+---
+description: "Share one runtime while configuring independent agent prompts and working folders."
+icon: code
+---
+
+# Multiple agents
+
+A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/two_agents.rs#two_agents -->
+
+```rust
+ let reviewer_dir = tempfile::tempdir()?;
+ let fixer_dir = tempfile::tempdir()?;
+ let reviewer = runtime.agent(
+ AgentSpec::new("reviewer")
+ .system_prompt("REVIEWER_PROMPT: review code")
+ .action_dir(reviewer_dir.path())
+ .access(openhuman_embed::Access::readonly()),
+ )?;
+ let fixer = runtime.agent(
+ AgentSpec::new("fixer")
+ .system_prompt("FIXER_PROMPT: explain fixes")
+ .action_dir(fixer_dir.path())
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_ne!(reviewer.action_dir(), fixer.action_dir());
+ assert_ne!(reviewer.home_dir(), fixer.home_dir());
+ assert_ne!(reviewer.workspace_dir(), reviewer.action_dir());
+ assert!(!reviewer.run("Review").await?.reply.is_empty());
+ assert!(!fixer.run("Explain").await?.reply.is_empty());
+ if support::offline() {
+ let requests = support::chat_requests(&provider).await;
+ assert_eq!(requests.len(), 2);
+ assert!(String::from_utf8_lossy(&requests[0].body).contains("REVIEWER_PROMPT"));
+ assert!(!String::from_utf8_lossy(&requests[0].body).contains("FIXER_PROMPT"));
+ assert!(String::from_utf8_lossy(&requests[1].body).contains("FIXER_PROMPT"));
+ }
+ println!("two distinct prompts and action workspaces verified");
+```
+
+<!-- END EMBED -->
+
+The [complete two_agents example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) sends real turns and checks the provider requests: the reviewer prompt does not contain the fixer prompt. It also checks different action directories and agent homes. Run `cargo run -p openhuman-embed --example two_agents`.
+
+Agents on one runtime share the runtime configuration and credential root. Separate action directories are useful for cooperating agents; use [SaaS profiles](saas-multi-tenant.md) for user isolation.
+
+Runtime defaults can supply a provider and model settings; individual agents override selected fields. The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) verifies both routes and their transmitted temperature and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+<!-- Source: gitbooks/developing/embed/guides/saas-multi-tenant.md -->
+---
+description: "Isolate user credentials, workspaces, and conversation history with ProfileRuntime."
+icon: code
+---
+
+# SaaS with multiple tenants
+
+Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+
+The complete example prepares a temporary SaaS root and initializes the keyring at `SaasConfig::operator_config().workspace_dir` before boot. SaaS validates the operator root, service token, permitted domains, and environment. A process-wide `OPENHUMAN_WORKSPACE` override is rejected. A SaaS core must be the only core in its process.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example profiles`. The [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) installs a loopback backend transport, chats as Alice and Bob, then checks distinct workspaces and same-thread history isolation. No live account or backend is contacted.
+
+Authenticate users in your host before selecting a profile. Keep the operator's configuration and gateway credential separate from user credentials. [Managed inference](../integrations/tinyhumans-managed.md) explains who provides the backend transport.
+
+<!-- Source: gitbooks/developing/embed/installation.md -->
+---
+description: "Add the Embed dependency, choose compile-time gates, and configure the host\u2019s runtime and state deliberately."
+---
+
+# Installation
+
+`openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+
+Run repository commands from its root. Build the facade with `cargo check -p openhuman-embed`; validate a narrow graph with `cargo check -p openhuman-embed --no-default-features`. Runtime weight presets and Cargo features control different things.
+
+## Compile-time gates versus runtime selection
+
+| Choice | What it controls |
+| --- | --- |
+| Cargo default features | Code and dependencies compiled into the artifact |
+| Named Embed feature such as `mcp` or `skills` | Public facade items and the forwarded core gate |
+| `RuntimeBuilder::modules`, domains, services and tool groups | Which compiled families a runtime exposes or starts |
+| Agent tool scope and access | Which subset one agent can use |
+
+Embed defaults forward the core defaults and enable the named Embed `channels` feature. Core defaults can include MCP and skills without enabling Embed's separately gated `McpServer`/agent MCP setter or skill setters. Add `--features mcp,skills` when using those public APIs. A runtime selection cannot enable a Cargo gate that was compiled out; inspect the [generated compiled matrix](capability-matrix.md) and the [source manifest](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/Cargo.toml).
+
+`RuntimeBuilder::lean()` narrows runtime activity; it does not reduce the dependency graph by itself. Pair it with `--no-default-features` for a narrow build and explicitly add the gates you need. Use `scripts/assert-shed.sh` or the repository dependency simulator before claiming a dependency reduction. See [lean/headless guide](guides/lean-headless.md).
+
+## Host runtime and credentials
+
+Build a Tokio multi-thread runtime with `enable_all`, a large worker stack and a bounded blocking pool. The verified examples use the [core runtime constants](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/core/runtime/mod.rs) through their repository support module: currently a 20 MiB worker stack and 64 blocking workers. Tokio's default 2 MiB worker stack is insufficient for nested agent turns. Follow the full example's host setup rather than adding an unconfigured `#[tokio::main]` to a large agent workload.
+
+Initialize the credential master key through `openhuman_embed::process::init_master_key` before persisting a runtime API key. Headless hosts can provide a protected 64-hex-character `OPENHUMAN_KEYRING_MASTER_KEY` or configured key file; keep this credential out of source and logs. The offline examples create disposable fixture keys, not production credentials.
+
+## State, configuration and inspection
+
+`Workspace::Ephemeral` is the library preset's default. `Workspace::Dir` moves both internal state and the credential root together; `workspace_dir` overrides internal state only, leaving the credential root at the resolved config path. Keep the action directory outside the internal workspace. Operator host presets use discovered configuration, while a supplied `Config` is resolved host configuration.
+
+[Runtime defaults](concepts/runtime-defaults.md) explains inheritance. The generated [builder setters](builder-setters.md) is the source-derived list of configuration knobs, and `RuntimeBuilder::describe` reports the pre-build plan without starting services.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+The example checks the effective report after boot and proves that credentials, provider URL and workspace path are absent. The generated matrix uses the fixed default-feature report command; it describes that build, not every feature combination a host might compile.
+
+<!-- Source: gitbooks/developing/embed/integrations/README.md -->
+---
+description: "Choose provider, tool, storage, and channel adapters for your host."
+icon: code
+---
+
+# Embedding integrations
+
+An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+
+- [OpenAI-compatible providers and BYOK](openai-compatible.md)
+- [TinyHumans managed inference](tinyhumans-managed.md)
+- [Local models](local-models.md)
+- [MCP servers](mcp.md)
+- [Composio](composio.md)
+- [Storage drivers](storage-drivers.md)
+- [Channels](channels.md)
+
+[Guides](../guides/README.md) show how these pieces fit into a CLI, an HTTP server, or a SaaS host. Every linked executable example defaults to offline mode; a live endpoint requires an explicit choice.
+
+<!-- Source: gitbooks/developing/embed/integrations/channels.md -->
+---
+description: "Bind an incoming channel to an agent and verify the delivered reply."
+icon: code
+---
+
+# Channels
+
+Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/telegram.rs#telegram -->
+
+```rust
+ let bot = wiremock::MockServer::start().await;
+ let token = "123456:EXAMPLE";
+ let updates = format!("/bot{token}/getUpdates");
+ wiremock::Mock::given(wiremock::matchers::path(updates.clone())).respond_with(
+ wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok":true,"result":[{
+ "update_id":1,"message":{"message_id":1,"date":0,"text":"hello channel",
+ "from":{"id":99,"is_bot":false,"username":"alice"},"chat":{"id":4242,"type":"private"}}
+ }]}))).up_to_n_times(1).with_priority(1).mount(&bot).await;
+ wiremock::Mock::given(wiremock::matchers::path(updates))
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":[]}))
+ .set_delay(std::time::Duration::from_millis(100)),
+ )
+ .with_priority(2)
+ .mount(&bot)
+ .await;
+ wiremock::Mock::given(wiremock::matchers::any())
+ .respond_with(
+ wiremock::ResponseTemplate::new(200)
+ .set_body_json(serde_json::json!({"ok":true,"result":{
+ "message_id":2,"id":1,"is_bot":true,"username":"example_bot"}})),
+ )
+ .with_priority(10)
+ .mount(&bot)
+ .await;
+ std::env::set_var("OPENHUMAN_TELEGRAM_BOT_API_BASE", bot.uri());
+ let agent = runtime.agent(
+ AgentSpec::new("channel-agent").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let listener = runtime.channels().telegram(
+ openhuman_embed::TelegramChannelSpec::new(token, agent.id()).allowed_users(["alice"]),
+ )?;
+ let mut sent = false;
+ for _ in 0..200 {
+ let requests = bot.received_requests().await.unwrap_or_default();
+ sent = requests.iter().any(|request| {
+ request.url.path().ends_with("/sendMessage")
+ && serde_json::from_slice::<serde_json::Value>(&request.body).is_ok_and(|body| {
+ body["chat_id"].to_string().contains("4242")
+ && body["text"]
+ .as_str()
+ .is_some_and(|text| text.contains("hello from the stub"))
+ })
+ });
+ if sent {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ listener.stop();
+ assert!(
+ sent,
+ "the bound agent must send a reply to the stub Bot API"
+ );
+ std::env::remove_var("OPENHUMAN_TELEGRAM_BOT_API_BASE");
+ println!("Telegram update answered in the correct chat");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example telegram --features channels`. The [complete telegram example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) receives a stub update, runs the bound agent, and checks that the resulting reply was posted to the expected chat id.
+
+Keep channel credentials in host configuration and map messages to the intended identity and conversation. A provider route controls inference; it does not configure a channel or provide a hosted relay. [Managed backend setup](tinyhumans-managed.md) explains that separate transport responsibility.
+
+For a live Telegram host, supply the real Bot API configuration through your application's channel setup. This offline example deliberately has no live channel environment switch. [Deploy a server](../guides/deploy-server.md) covers a host-owned HTTP alternative.
+
+<!-- Source: gitbooks/developing/embed/integrations/composio.md -->
+---
+description: "Pin connector credentials per agent while the host supplies backend transport."
+icon: code
+---
+
+# Composio
+
+Composio calls use the host backend transport. Install that transport before booting a managed runtime; see [TinyHumans managed inference](tinyhumans-managed.md). An explicit inference provider route supplies model inference, not the connector transport.
+
+Use `AgentSpec::composio(ComposioHostCredential)` to pin a connector credential to an agent. This keeps the credential selection on the host side instead of asking the model to choose another user's credential. Configure the agent's tool scope and access separately. The connector tools still pass through the host's execution policy.
+
+The repository's [Composio agent integration test](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/tests/composio_agents.rs) verifies two agents using their own pinned credentials against a loopback backend. It checks the outgoing authentication and action results rather than contacting Composio. Run the Embed integration suite through the repository's cancellation-aware runner when changing this adapter.
+
+Account login, linking, and credential acquisition belong to your connected host and connector layer. Keep secrets out of prompts and capability reports. For multiple users, use [SaaS profiles](../guides/saas-multi-tenant.md); independent action directories on a shared library runtime do not establish tenant isolation.
+
+<!-- Source: gitbooks/developing/embed/integrations/local-models.md -->
+---
+description: "Use a local OpenAI-compatible server or inject a native ChatModel implementation."
+icon: code
+---
+
+# Local and custom models
+
+For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The [OpenAI-compatible example controls](openai-compatible.md) can point a live example at that local server.
+
+A native provider implements `openhuman_embed::providers::ChatModel<()>`. `Provider::custom_with_fallback` tries fallback models when the primary fails before output; validation failures and failures after streamed content do not switch providers. A named role pin can select another native model for a workload.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/custom_provider.rs#custom_provider -->
+
+```rust
+ let provider = Provider::custom_with_fallback(
+ Arc::new(LocalModel {
+ reply: None,
+ calls: failed.clone(),
+ }),
+ vec![Arc::new(LocalModel {
+ reply: Some("fallback answer"),
+ calls: fallback.clone(),
+ })],
+ )
+ .model("local-custom")
+ .role(
+ "coding",
+ Arc::new(LocalModel {
+ reply: Some("coding answer"),
+ calls: pinned.clone(),
+ }),
+ );
+ let runtime = Runtime::builder()
+ .config(support::offline_config())
+ .backend_url(backend.uri())
+ .provider(provider)
+ .build()
+ .await?;
+ let definition = || {
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly")
+ .tools(ToolScopeSpec::HostOnly)
+ };
+ let regular = runtime.agent(AgentSpec::new("fallback-agent").definition(definition()))?;
+ assert_eq!(regular.run("Hello").await?.reply, "fallback answer");
+ assert_eq!(failed.load(Ordering::SeqCst), 1);
+ assert_eq!(fallback.load(Ordering::SeqCst), 1);
+ let coding = runtime.agent(
+ AgentSpec::new("coding-agent")
+ .model("hint:coding")
+ .definition(definition()),
+ )?;
+ assert_eq!(
+ coding.run("Explain a function").await?.reply,
+ "coding answer"
+ );
+ assert_eq!(pinned.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ failed.load(Ordering::SeqCst),
+ 1,
+ "coding bypasses the primary chain"
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example custom_provider`. The [complete custom_provider example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) includes the concrete model implementation. It checks one primary failure, one fallback invocation, and a coding role that bypasses the primary chain. These native models are deterministic and make no inference network requests.
+
+For live local inference, configure model availability and authentication in your server. For runtime selection and service controls, see [Lean and headless hosts](../guides/lean-headless.md).
+
+<!-- Source: gitbooks/developing/embed/integrations/mcp.md -->
+---
+description: "Connect a declared MCP server and verify remote discovery and execution."
+icon: code
+---
+
+# MCP servers
+
+Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/mcp.rs#mcp -->
+
+```rust
+ let mcp = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(McpStub)
+ .mount(&mcp)
+ .await;
+ let discovery = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::path("/v1/chat/completions"))
+ .respond_with(ForecastModel(std::sync::atomic::AtomicUsize::new(0)))
+ .mount(&discovery)
+ .await;
+ let agent = runtime.agent(
+ AgentSpec::new("mcp-client")
+ .provider(support::route(&discovery, "fixture"))
+ .mcp(
+ openhuman_embed::McpServer::http("forecast", format!("{}/mcp", mcp.uri()))
+ .allow_tools(["forecast"]),
+ )
+ .access(openhuman_embed::Access::full()),
+ )?;
+ assert_eq!(
+ agent
+ .run("List the forecast server tools, then call its forecast tool")
+ .await?
+ .reply,
+ "sunny verified"
+ );
+ let requests = mcp.received_requests().await.expect("MCP requests");
+ let methods: Vec<String> = requests
+ .iter()
+ .filter_map(|r| {
+ serde_json::from_slice::<serde_json::Value>(&r.body).ok()?["method"]
+ .as_str()
+ .map(str::to_string)
+ })
+ .collect();
+ assert!(methods.iter().any(|m| m == "initialize"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/list"), "{methods:?}");
+ assert!(methods.iter().any(|m| m == "tools/call"), "{methods:?}");
+ let requests = support::chat_requests(&discovery).await;
+ assert!(support::tool_results(&requests[1]).contains("forecast"));
+ assert!(support::tool_results(&requests[2]).contains("sunny"));
+ println!("MCP handshake, discovery and remote execution verified");
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example mcp --features mcp`. The [complete mcp example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) performs an actual MCP initialize handshake, lists remote tools, calls the forecast tool, and verifies the returned `sunny` result in the next model request.
+
+The immediately available `mcp_list_tools` and `mcp_call_tool` bridge tools work with a cold configured server. Individual per-server tools use a cached catalog and are deferred by default. On a cold first turn, that catalog may still be warming in the background; do not assume `tool_search` already contains the per-server tool name. Use the bridge to discover and call it, and copy returned tool names and arguments.
+
+MCP transport does not bypass the host's execution policy. Configure agent access and approvals for actions exposed by the server. [Mock testing](../guides/mock-backend-testing.md) keeps this protocol path local during development.
+
+<!-- Source: gitbooks/developing/embed/integrations/openai-compatible.md -->
+---
+description: "Route inference to an explicit endpoint and bearer without changing shared host configuration."
+icon: code
+---
+
+# OpenAI-compatible providers and BYOK
+
+Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+
+The runtime and agent routes in this example answer independently. Assertions inspect the actual request bodies, including model, temperature, and token limits.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/defaults_overrides.rs#defaults_overrides -->
+
+```rust
+ let inherited = runtime.agent(AgentSpec::new("inherited"))?;
+ let override_provider = support::provider("override reply").await;
+ let overridden = runtime.agent(
+ AgentSpec::new("overridden")
+ .provider(support::route(&override_provider, "override-model"))
+ .access(openhuman_embed::Access::readonly())
+ .model_defaults(openhuman_embed::ModelDefaults {
+ temperature: Some(0.8),
+ max_tokens: Some(128),
+ ..Default::default()
+ }),
+ )?;
+ let inherited_reply = inherited.run("Hello default").await?;
+ let overridden_reply = overridden.run("Hello override").await?;
+ if support::offline() {
+ assert_eq!(inherited_reply.reply, "hello from the stub");
+ let requests = support::chat_requests(&provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "fixture");
+ assert_eq!(body["temperature"], 0.4);
+ assert_eq!(body["max_tokens"], 256);
+ }
+ assert_eq!(overridden_reply.reply, "override reply");
+ let requests = support::chat_requests(&override_provider).await;
+ let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
+ assert_eq!(body["model"], "override-model");
+ assert_eq!(body["temperature"], 0.8);
+ assert_eq!(body["max_tokens"], 128);
+ assert_eq!(runtime.defaults().model.temperature, Some(0.4));
+ println!("default and override routes answered independently");
+```
+
+<!-- END EMBED -->
+
+The [complete defaults_overrides example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) includes the loopback endpoint setup. Run `cargo run -p openhuman-embed --example defaults_overrides` for its offline assertions.
+
+Examples using `support::example_provider` switch to live inference only with `OPENHUMAN_EXAMPLE_LIVE=1` and all three of `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY`, and `OPENHUMAN_EXAMPLE_MODEL`. These settings are example controls, not replacements for your application's credential configuration. Keep provider keys in your host's secret configuration.
+
+For a non-HTTP implementation, [local and custom models](local-models.md) covers `Provider::custom`, native fallback, and role pins. [Managed inference](tinyhumans-managed.md) uses a different backend transport boundary.
+
+<!-- Source: gitbooks/developing/embed/integrations/storage-drivers.md -->
+---
+description: "Configure SQLite or MongoDB through Embed and inspect the selected backend."
+icon: code
+---
+
+# Storage drivers
+
+Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+
+The SQLite example sets `config.storage.url` to a `sqlite:` URL under a temporary directory, then obtains `Runtime::storage`. It creates a scoped collection, writes a document, reads it back, and deletes it. A configured backend also supplies the default driver-backed session stores; an explicit host session-store adapter takes precedence.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_sqlite -->
+
+```rust
+ let mut config = support::offline_config();
+ config.storage.url = Some(format!(
+ "sqlite:{}",
+ directory.path().join("storage").display()
+ ));
+ let runtime = Runtime::builder()
+ .workspace(Workspace::Ephemeral)
+ .config(config)
+ .backend_url(backend.uri())
+ .build()
+ .await?;
+ let storage = runtime.storage().expect("configured SQLite backend");
+ assert_eq!(storage.driver(), "sqlite");
+ let scoped = storage.for_scope(&Scope::local())?;
+ let documents = scoped.documents();
+ documents
+ .ensure_collection(&CollectionSpec::new("settings"))
+ .await?;
+ let value = serde_json::json!({"theme":"dark"});
+ documents
+ .put("settings", "demo", value.clone(), Precondition::Absent)
+ .await?;
+ assert_eq!(
+ documents
+ .get("settings", "demo")
+ .await?
+ .expect("stored value")
+ .doc,
+ value
+ );
+ assert!(
+ documents
+ .delete("settings", "demo", Precondition::None)
+ .await?
+ );
+ assert!(documents.get("settings", "demo").await?.is_none());
+ assert_eq!(
+ runtime.capabilities().storage.driver.as_deref(),
+ Some("sqlite")
+ );
+```
+
+<!-- END EMBED -->
+
+Run `cargo run -p openhuman-embed --example storage --features storage-sqlite`. This performs real local SQLite writes. The [complete storage example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) also describes a MongoDB URL without connecting.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/storage.rs#storage_mongodb -->
+
+```rust
+ // Enable `storage-mongodb` for a deployment that builds this config.
+ // Describing it does not contact MongoDB and never exposes credentials.
+ let mut mongo = support::offline_config();
+ mongo.storage.url = Some("mongodb://app:[email protected]:27017/openhuman".into());
+ let builder = RuntimeBuilder::library().config(mongo);
+ let description = builder.describe();
+ assert_eq!(description.storage.driver.as_deref(), Some("mongodb"));
+ assert!(description.storage.configured);
+ assert!(!serde_json::to_string(&description)?.contains("example-password"));
+ // An explicit environment variable is the only path to a live database.
+ if let Ok(url) = std::env::var("OPENHUMAN_EXAMPLE_MONGODB_URL") {
+ let live = RuntimeBuilder::library().storage(url).build().await?;
+ assert_eq!(live.storage().expect("MongoDB backend").driver(), "mongodb");
+ }
+```
+
+<!-- END EMBED -->
+
+`RuntimeBuilder::describe()` reports the driver and whether storage is configured, omitting URL credentials. Describing a MongoDB URL does not prove the server is reachable or that the MongoDB driver was compiled. Building a runtime with that URL requires `storage-mongodb` and a reachable server.
+
+The only live database path in this example is `OPENHUMAN_EXAMPLE_MONGODB_URL`. To exercise it deliberately, enable both `storage-sqlite` and `storage-mongodb` and supply your own MongoDB URL. The offline CI runner clears this setting. A deployed host supplies its persistent URL and credentials through its own configuration.
+
+<!-- Source: gitbooks/developing/embed/integrations/tinyhumans-managed.md -->
+---
+description: "Install the host backend transport before using managed inference and hosted services."
+icon: code
+---
+
+# TinyHumans managed inference
+
+Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+
+Supply a library backend key with `RuntimeBuilder::api_key` and initialize the process master key before credential storage. Library mode does not perform user login. Managed inference uses the key as a bearer; backend REST calls resolve it through the backend credential seam. Without an installed transport, hosted backend calls return a typed backend-unavailable error.
+
+The SaaS example uses a deterministic implementation of that transport boundary and installs separate profile credentials. It verifies managed turns without a live service.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/profiles.rs#profiles -->
+
+```rust
+ let profiles = openhuman_embed::ProfileRuntime::build(config).await?;
+ let mut handles = Vec::new();
+ for (user, text) in [("alice", "Alice private note"), ("bob", "Bob private note")] {
+ let profile = profiles.provision(user).await?;
+ profiles
+ .set_credential(
+ &profile.profile_id,
+ openhuman_embed::profiles::ProfileCredentialKind::ApiKey,
+ &format!("{user}-fixture"),
+ )
+ .await?;
+ let handle = profiles.open(user).await?;
+ let reply = handle.chat("shared-thread", text).await?;
+ assert!(reply.text.contains(text), "{}", reply.text);
+ handles.push(handle);
+ }
+ assert_ne!(handles[0].workspace_dir(), handles[1].workspace_dir());
+ for (index, own, other) in [
+ (0, "Alice private note", "Bob private note"),
+ (1, "Bob private note", "Alice private note"),
+ ] {
+ let messages = handles[index].messages("shared-thread").await?;
+ let text = serde_json::to_string(&messages)?;
+ assert!(text.contains(own));
+ assert!(!text.contains(other));
+ }
+ drop(handles);
+ profiles.shutdown().await;
+ println!("two profiles keep same-thread conversations separate");
+```
+
+<!-- END EMBED -->
+
+See the [complete profiles example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) and its shared support transport for the full offline setup. For a deployed SDK-backed host, follow the connected layer's setup instead of copying the loopback transport.
+
+Use [OpenAI-compatible routing](openai-compatible.md) when your host wants to send inference directly to a BYOK endpoint. That explicit provider route does not supply hosted backend services.
+
+<!-- Source: gitbooks/developing/embed/quickstart.md -->
+---
+description: "Run one agent against a local fixture, then choose a provider and working directory for your host."
+---
+
+# Quickstart
+
+Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+
+## Create an agent and send a turn
+
+The full example constructs the runtime before this excerpt. `AgentSpec` names the agent and gives it a bare prompt with `HostOnly` tools. With no host tools attached, this is a text-only agent: it cannot inherit the operator's built-in tool catalog.
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/run_turn.rs#run_turn -->
+
+```rust
+ let agent = runtime.agent(
+ AgentSpec::new("hello").definition(
+ AgentDefinitionSpec::new()
+ .bare_prompt("Reply briefly.")
+ .tools(ToolScopeSpec::HostOnly),
+ ),
+ )?;
+ let outcome = agent.run("Say hello").await?;
+ assert!(!outcome.reply.is_empty());
+ if support::offline() {
+ assert_eq!(outcome.reply, "hello from the stub");
+ }
+ println!("{}", outcome.reply);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs), including runtime construction, imports and fixture setup.
+
+`Agent::run` returns a `TurnOutcome` containing the reply and session identity. Use `Agent::turn(...).session(...)` for subsequent messages in the same conversation, or [stream progress](concepts/turns-sessions.md) when your interface should display deltas as they arrive.
+
+## Connect your own host
+
+Replace the fixture provider with an explicit OpenAI-compatible `Provider` or a native custom model. Give tools an explicit action directory, decide whether autonomy enforcement should be enabled, and keep runtime state separate from acting-tool folders. Configure the Tokio worker stack and credential master key as described in [installation](installation.md).
+
+The example's live path requires `OPENHUMAN_EXAMPLE_LIVE=1` plus `OPENHUMAN_EXAMPLE_BASE_URL`, `OPENHUMAN_EXAMPLE_API_KEY` and `OPENHUMAN_EXAMPLE_MODEL`. Choosing a live path is an explicit decision; setting credentials alone does not turn the default example into a live call.
+
+For managed TinyHumans inference, use the [TinyHumans host integration](integrations/tinyhumans-managed.md), which installs the backend transport. Embed by itself does not install one.
+
+## Extend the example
+
+- Give a reviewer and a fixer separate tools and folders: [multiple agents](guides/multi-agent.md).
+- Serve a request through your own HTTP transport: [deploy a server](guides/deploy-server.md).
+- Attach application functions: [tools](concepts/tools.md).
+- Isolate authenticated customers: [SaaS guide](guides/saas-multi-tenant.md).
+- Keep the setup offline and deterministic: [mock-backend testing](guides/mock-backend-testing.md).
+
+Drop listeners and agent handles before shutting down the runtime. For early removal, await `remove_agent` so retained handles stop admitting turns and the old ID is released only after cleanup.
+
+<!-- Source: gitbooks/developing/embed/troubleshooting.md -->
+---
+description: "Diagnose missing features, blocked turns, credentials, state paths and lifecycle failures."
+---
+
+# Embedding troubleshooting
+
+Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+
+| Symptom | Check and next step |
+| --- | --- |
+| `RuntimeError::AlreadyRunning` | Reuse the process runtime; drop old listeners, agents and runtime before restarting. Profiles require their own process mode. |
+| Method or type not found at compile time | Check named Embed Cargo gates, especially `mcp`/`skills`. Core compiled flags alone do not activate those facade exports. |
+| `CoreError::Unavailable` | Inspect effective domains/modules as well as compiled features. Runtime selections can narrow a compiled family. |
+| `BACKEND_UNAVAILABLE` | Install the host backend transport, normally through `openhuman-tinyhumans`, before backend-touching calls. |
+| Credential master-key failure | Initialize process master-key state before persisting a runtime API key; check headless key/file setup without printing its value. |
+| Invalid or insecure provider route | Supply a nonblank endpoint/key and use HTTPS for remote bearer routes. Loopback fixtures are separate from remote endpoints. |
+| Stack overflow on a nested turn | Use the documented Tokio worker stack; the default 2 MiB stack is insufficient. Follow the runnable example support setup. |
+| A write is waiting indefinitely | Poll the same agent's approvals or retain an active callback subscription. Check origin, enabled autonomy and trusted action roots. |
+| Streaming appears stalled | Drain the bounded progress stream while work runs; inspect the final result. Dropping it cancels forwarding and the turn cooperatively. |
+| A skill is absent | Copy a real bundle into the agent's skill directory; symlinked bundles are rejected. New instructions need a new session. |
+| Agent registration returns `DuplicateId` | Another instance or teardown still reserves the ID. Wait for removal/last-handle cleanup to finish. |
+| Retained handle returns `AgentRemoved` | That instance was removed; obtain a newly registered handle rather than reusing the old one. |
+| `Decode` error on a typed facade | Treat it as an API/result-shape mismatch; preserve safe metadata and report a regression. |
+
+## Inspect without exposing credentials
+
+<!-- BEGIN EMBED: crates/openhuman-embed/examples/capability_report.rs#capability_report -->
+
+```rust
+ let info = runtime.capabilities();
+ assert_eq!(info.schema_version, 1);
+ assert!(info.defaults.routed_provider);
+ let serialized = serde_json::to_string(&info)?;
+ assert!(!serialized.contains("sk-test"));
+ assert!(!serialized.contains(&provider.uri()));
+ assert!(!serialized.contains(&runtime.workspace_dir().display().to_string()));
+ println!("{}", serde_json::to_string_pretty(&info)?);
+```
+
+<!-- END EMBED -->
+
+[Complete runnable example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs), including runtime construction, imports and fixture setup.
+
+Before boot, `RuntimeBuilder::describe` can report a provisional plan; check `configuration_resolved`. After boot, `Runtime::capabilities` describes resolved defaults, storage source/driver and selection without its URL/key. Runtime events provide content-free lifecycle metadata, while explicit turn progress can contain text and should be handled accordingly.
+
+Reproduce behavior with [offline testing](guides/mock-backend-testing.md) before using a live provider. The [error concept](concepts/errors.md) explains structured kinds and expected-user-state errors.
+
+<!-- Source: crates/openhuman-embed/README.md -->
+# OpenHuman Embed
+
+A typed Rust facade for running the OpenHuman core inside your application: one Runtime per process, with independently configured Agents.
+
+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).
+
+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.
+
+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.
+
+<!-- Source: gitbooks/developing/embedding.md -->
+# Embedding OpenHuman
+
+The embedding documentation now lives in the [Embedding section](embed/README.md).
+
+Start with [installation](embed/installation.md) and the [quickstart](embed/quickstart.md), then use the [concepts](embed/concepts/README.md), [guides](embed/guides/README.md), [integrations](embed/integrations/README.md) and generated [cookbook](embed/cookbook.md).
+
+The public library uses one Runtime per process with independently configured Agents. For isolated authenticated users, read [profiles and SaaS](embed/concepts/profiles-saas.md).
+
+<!-- Source: gitbooks/developing/embed/cookbook.md -->
+# Cookbook
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+
+## Polling and callback approvals with cancellation
+
+Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example approvals`
+
+## Stable capability metadata before and after boot
+
+Stable capability metadata before and after boot.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example capability_report`
+
+## Stateless completion without booting an agent runtime
+
+Stateless completion without booting an agent runtime.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example completer`
+
+## Run and inspect an agent cron job
+
+Run and inspect an agent cron job.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example cron`
+
+## Native custom providers, fallback and workload role pins
+
+Inject deterministic native models and prove fallback and role selection without inference HTTP.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs) · offline; no live inference path.
+
+Run: `cargo run -p openhuman-embed --example custom_provider`
+
+## Runtime defaults and per-agent overrides
+
+Runtime defaults and per-agent overrides.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example defaults_overrides`
+
+## A per-agent post-turn hook observes completed turns
+
+A per-agent post-turn hook observes completed turns.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example hooks`
+
+## Host tools and HostOnly keep the advertised tool catalog exact
+
+Host tools and HostOnly keep the advertised tool catalog exact.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example host_tools`
+
+## Lean runtime without background services
+
+Lean runtime without background services.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs) · offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.
+
+Run: `cargo run -p openhuman-embed --example lean_headless`
+
+## Connect an actual MCP protocol stub over loopback
+
+Connect an actual MCP protocol stub over loopback.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs) · offline with loopback stubs; no live path. · feature: mcp
+
+Run: `cargo run -p openhuman-embed --example mcp --features mcp`
+
+## Tenant scoped memory facade with an in-memory engine
+
+Tenant scoped memory facade with an in-memory engine.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example memory`
+
+## SaaS profiles isolate conversation history
+
+SaaS profiles isolate conversation history.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example profiles`
+
+## Hello agent: a prompt in and a reply out
+
+Hello agent: a prompt in and a reply out.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example run_turn`
+
+## Runtime lifecycle events and live hook registration
+
+Observe ordered metadata and add/remove a runtime-wide hook while agents keep running.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs) · offline with a loopback provider; no live path.
+
+Run: `cargo run -p openhuman-embed --example runtime_events`
+
+## Access tiers and explicit sandbox choices
+
+Access tiers and explicit sandbox choices.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example sandbox_access`
+
+## Embed an agent behind a host-owned HTTP server
+
+Embed an agent behind a host-owned HTTP server.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example server`
+
+## Copy a skill bundle into its agent workspace
+
+Copy a skill bundle into its agent workspace.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL. · feature: skills
+
+Run: `cargo run -p openhuman-embed --example skills --features skills`
+
+## SQLite writes and MongoDB configuration through Embed
+
+Open a real local SQLite backend and describe a MongoDB deployment without connecting.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs) · offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb. · feature: storage-sqlite
+
+Run: `cargo run -p openhuman-embed --example storage --features storage-sqlite`
+
+## Streaming progress with a draining receiver
+
+Streaming progress with a draining receiver.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example streaming`
+
+## Structured output parsed and checked against the request
+
+Structured output parsed and checked against the request.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/structured_output.rs) · offline with loopback stubs; no live path.
+
+Run: `cargo run -p openhuman-embed --example structured_output`
+
+## Telegram channel answered by its bound agent via a local Bot API
+
+Telegram channel answered by its bound agent via a local Bot API.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs) · offline with loopback stubs; no live path. · feature: channels
+
+Run: `cargo run -p openhuman-embed --example telegram --features channels`
+
+## Two agents with independent prompts and working folders
+
+Two agents with independent prompts and working folders.
+
+[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) · offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.
+
+Run: `cargo run -p openhuman-embed --example two_agents`
+
+<!-- Source: gitbooks/developing/embed/capability-matrix.md -->
+# Compiled feature matrix
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+
+| Cargo feature | Compiled in this build |
+| --- | --- |
+| `channels` | Yes |
+| `crash-reporting` | No |
+| `default` | Yes |
+| `documents` | No |
+| `e2e-test-support` | No |
+| `file-logging` | Yes |
+| `flows` | Yes |
+| `hosting` | No |
+| `http-server` | Yes |
+| `inference` | No |
+| `mcp` | Yes |
+| `media` | Yes |
+| `modules` | Yes |
+| `rss-bench` | No |
+| `runtime-node` | No |
+| `scheduler-gate` | Yes |
+| `skills` | Yes |
+| `storage-file` | No |
+| `storage-mongodb` | No |
+| `storage-sqlite` | No |
+| `tinymemes` | Yes |
+| `voice` | No |
+| `web3` | No |
+| `whatsapp-web` | No |
+
+<!-- Source: gitbooks/developing/embed/builder-setters.md -->
+# RuntimeBuilder setters
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+
+- [`access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L343): `pub fn access(mut self, access: Access) -> Self`
+- [`action_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L300): `pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self`
+- [`agent_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L151): `pub fn agent_defaults(mut self, defaults: super::AgentDefaults) -> Self`
+- [`api_key`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L320): `pub fn api_key(mut self, key: impl Into<ApiKey>) -> Self`
+- [`autonomy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L186): `pub fn autonomy(mut self, value: openhuman_core::config::schema::AutonomyConfig) -> Self`
+- [`backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L225): `pub fn backend_transport(mut self, transport: Arc<dyn BackendTransport>) -> Self`
+- [`backend_url`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L330): `pub fn backend_url(mut self, url: impl Into<String>) -> Self`
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L444): `pub fn config(mut self, config: Config) -> Self`
+- [`config_source`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L308): `pub fn config_source(mut self, source: ConfigSource) -> Self`
+- [`controller_extension`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L415): `pub fn controller_extension(mut self, extension: ControllerExtension) -> Self`
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L211): `pub fn cron(mut self, value: openhuman_core::config::schema::CronConfig) -> Self`
+- [`definition_base`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L170): `pub fn definition_base(mut self, definition: crate::AgentDefinitionSpec) -> Self`
+- [`domains`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L374): `pub fn domains(mut self, domains: DomainSet) -> Self`
+- [`host_kind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L391): `pub fn host_kind(mut self, host_kind: HostKind) -> Self`
+- [`learning`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L206): `pub fn learning(mut self, value: super::LearningSettings) -> Self`
+- [`listen`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L413): `pub fn listen(self, host: impl Into<String>, port: u16) -> Self`
+- [`listen_host`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L418): `pub fn listen_host(mut self, host: impl Into<String>) -> Self`
+- [`listen_port`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L424): `pub fn listen_port(mut self, port: u16) -> Self`
+- [`live_policy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L464): `pub fn live_policy(mut self, policy: Arc<SecurityPolicy>) -> Self`
+- [`max_agents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L263): `pub fn max_agents(mut self, limit: usize) -> Self`
+- [`mcp_baseline`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L181): `pub fn mcp_baseline(mut self, servers: impl IntoIterator<Item = crate::McpServer>) -> Self`
+- [`memory_engine`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L239): `pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self`
+- [`model_defaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L160): `pub fn model_defaults(mut self, model: super::ModelDefaults) -> Self`
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/selection.rs#L156): `pub fn modules(mut self, modules: impl IntoIterator<Item = RuntimeModule>) -> Self`
+- [`post_turn_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L430): `pub fn post_turn_hook(mut self, hook: Arc<dyn PostTurnHook>) -> Self`
+- [`privacy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L196): `pub fn privacy(mut self, value: openhuman_core::config::schema::PrivacyConfig) -> Self`
+- [`provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L336): `pub fn provider(mut self, provider: Provider) -> Self`
+- [`sandbox`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L165): `pub fn sandbox(mut self, mode: crate::SandboxModeSpec) -> Self`
+- [`secrets`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L201): `pub fn secrets(mut self, value: openhuman_core::config::schema::SecretsConfig) -> Self`
+- [`server_launcher`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L444): `pub fn server_launcher(mut self, launcher: ServerLauncher) -> Self`
+- [`services`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L362): `pub fn services(mut self, services: ServiceSet) -> Self`
+- [`session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L434): `pub fn session(mut self, session: Session) -> Self`
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L254): `pub fn session_store(mut self, provider: Arc<dyn SessionStoreProvider>) -> Self`
+- [`skills`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L175): `pub fn skills(mut self, policy: super::SkillsPolicy) -> Self`
+- [`storage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L457): `pub fn storage(mut self, source: impl Into<StorageSource>) -> Self`
+- [`token`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L401): `pub fn token(mut self, token: TokenSource) -> Self`
+- [`tool_groups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L383): `pub fn tool_groups(mut self, tool_groups: ToolGroups) -> Self`
+- [`tool_hook`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L437): `pub fn tool_hook(mut self, hook: Arc<dyn ToolHook>) -> Self`
+- [`tool_ranker`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/seams.rs#L422): `pub fn tool_ranker(mut self, ranker: Arc<dyn ToolRanker>) -> Self`
+- [`tool_rules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L191): `pub fn tool_rules(mut self, value: tinytools::ToolRules) -> Self`
+- [`workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L273): `pub fn workspace(mut self, workspace: Workspace) -> Self`
+- [`workspace_dir`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/runtime/builder.rs#L287): `pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self`
+
+<!-- Source: gitbooks/developing/embed/api-index.md -->
+# API index
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. [Canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs).
+
+- [`Access`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Agent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinition`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentDefinitionSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentLayout`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentProgress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AgentTurnOrigin`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApiKey`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalDecision`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalHandler`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalSubscription`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Approvals`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ApprovalsError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Auth`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`AuthState`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BackendTransportError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`BaseUrlPurpose`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CancellationToken`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChannelListener`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ChatReply`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Completer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionObserver`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionResponse`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionTrace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CompletionUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ComposioHostCredential`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ConfigurationInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ControllerSchema`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CoreRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`CronError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DEFAULT_MAX_AGENTS`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DaemonConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefaultsInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DefinitionBase`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`DomainSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`EventStreamError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`GroupMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HTTP_SERVER_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Harness`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessCore`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HarnessError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HostTurnTools`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`HttpHeader`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`InMemorySessionStores`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRun`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobRunRecord`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSchedule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`JobTarget`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LastTurnUsage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`LearningSettings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpAuthConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`McpServer`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`MemoryBinding`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ModelDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`OpenError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PendingApproval`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PermissionLevel`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`PickListenPortError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileHandle`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileId`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileIdMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileRuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ProfileSummary`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Provisioned`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayAccepted`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RelayMessage`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RemoveAgent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Route`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Runtime`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeBuilder`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeDefaults`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEventKind`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeEvents`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeFlags`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`RuntimeModule`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SaasConfig`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SandboxModeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ScheduledJob`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ServiceSet`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Session`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SessionStoreProvider`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SkillsPolicy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StorageInfo`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamEvent`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`StreamMode`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`SystemJobContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TelegramChannelSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TokenSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Tool`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolAttachmentError`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolExposure`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolGroups`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolResult`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`ToolScopeSpec`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TransportProfile`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAccess`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TrustedAutomationSource`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Turn`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnContext`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnOutcome`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnRequest`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`TurnStream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`VOICE_COMPILED_IN`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`WeightClass`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`Workspace`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`absolute`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`agent_progress`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`artifacts`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`channels`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`chat_surface`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`complete`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`config`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`cron`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`embeddings`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`events`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`identity`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`install_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`installed_backend_transport`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`memory`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`modules`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`process`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`profiles`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`providers`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`run_from_args`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`schema_for_rpc_method`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`seams`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`session_store`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`skill_registry`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+- [`stream`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)
+
+The compiled capability report describes this build:
+
+```json
+{
+ "schema_version": 1,
+ "configuration_resolved": true,
+ "compiled_features": {
+ "channels": true,
+ "crash-reporting": false,
+ "default": true,
+ "documents": false,
+ "e2e-test-support": false,
+ "file-logging": true,
+ "flows": true,
+ "hosting": false,
+ "http-server": true,
+ "inference": false,
+ "mcp": true,
+ "media": true,
+ "modules": true,
+ "rss-bench": false,
+ "runtime-node": false,
+ "scheduler-gate": true,
+ "skills": true,
+ "storage-file": false,
+ "storage-mongodb": false,
+ "storage-sqlite": false,
+ "tinymemes": true,
+ "voice": false,
+ "web3": false,
+ "whatsapp-web": false
+ },
+ "domains": [
+ "agent",
+ "memory",
+ "threads",
+ "config",
+ "security",
+ "flows",
+ "skills",
+ "channels",
+ "inference",
+ "integrations",
+ "automation",
+ "runtimes",
+ "platform"
+ ],
+ "services": [
+ "harness_init"
+ ],
+ "tool_groups": {
+ "audio": "withheld",
+ "coding": "withheld",
+ "composio": "withheld",
+ "docs": "withheld",
+ "documents": "withheld",
+ "goals": "withheld",
+ "mcp": "withheld",
+ "media": "withheld",
+ "scheduling": "withheld",
+ "skills": "withheld",
+ "storage": "withheld",
+ "system": "withheld",
+ "tasks": "withheld",
+ "web3": "withheld",
+ "workflows": "withheld"
+ },
+ "host_kind": "Library",
+ "max_agents": 1024,
+ "defaults": {
+ "model": {
+ "temperature": 0.7,
+ "max_tokens": null,
+ "top_p": null,
+ "max_iterations": 200
+ },
+ "provider_model": "openrouter/deepseek/deepseek-v4-flash",
+ "routed_provider": false,
+ "sandbox": "None",
+ "approval_gate": true,
+ "include_user_skills": false,
+ "has_skills_root": false,
+ "mcp_servers": 0,
+ "templates": []
+ },
+ "configuration": {
+ "autonomy_enabled": true,
+ "privacy": "Standard",
+ "secrets_encrypted": true,
+ "cron_enabled": true,
+ "learning": {
+ "build_beliefs_every": 10,
+ "learnings_limit": 8
+ },
+ "has_tool_rules": false
+ },
+ "storage": {
+ "source": "workspace",
+ "driver": null,
+ "configured": false
+ },
+ "modules": [],
+ "weight": "custom"
+}
+```
+
+<!-- Source: crates/openhuman-embed/examples/README.md -->
+# Embed examples
+
+<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->
+
+[Cookbook](../../../gitbooks/developing/embed/cookbook.md)
+
+- [Polling and callback approvals with cancellation](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/approvals.rs): Allow and deny real parked writes, then cancel an in-flight callback without losing its pending request. (offline with loopback stubs; no live path.)
+- [Stable capability metadata before and after boot](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/capability_report.rs): Stable capability metadata before and after boot. (offline with loopback stubs; no live path.)
+- [Stateless completion without booting an agent runtime](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/completer.rs): Stateless completion without booting an agent runtime. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Run and inspect an agent cron job](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/cron.rs): Run and inspect an agent cron job. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Native custom providers, fallback and workload role pins](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/custom_provider.rs): Inject deterministic native models and prove fallback and role selection without inference HTTP. (offline; no live inference path.)
+- [Runtime defaults and per-agent overrides](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/defaults_overrides.rs): Runtime defaults and per-agent overrides. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [A per-agent post-turn hook observes completed turns](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/hooks.rs): A per-agent post-turn hook observes completed turns. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Host tools and HostOnly keep the advertised tool catalog exact](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/host_tools.rs): Host tools and HostOnly keep the advertised tool catalog exact. (offline with loopback stubs; no live path.)
+- [Lean runtime without background services](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/lean_headless.rs): Lean runtime without background services. (offline with loopback stubs; optional live via OPENHUMAN_EXAMPLE_LIVE.)
+- [Connect an actual MCP protocol stub over loopback](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/mcp.rs): Connect an actual MCP protocol stub over loopback. (offline with loopback stubs; no live path.; feature: mcp)
+- [Tenant scoped memory facade with an in-memory engine](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/memory.rs): Tenant scoped memory facade with an in-memory engine. (offline with loopback stubs; no live path.)
+- [SaaS profiles isolate conversation history](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/profiles.rs): SaaS profiles isolate conversation history. (offline with loopback stubs; no live path.)
+- [Hello agent: a prompt in and a reply out](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs): Hello agent: a prompt in and a reply out. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Runtime lifecycle events and live hook registration](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/runtime_events.rs): Observe ordered metadata and add/remove a runtime-wide hook while agents keep running. (offline with a loopback provider; no live path.)
+- [Access tiers and explicit sandbox choices](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/sandbox_access.rs): Access tiers and explicit sandbox choices. (offline with loopback stubs; no live path.)
+- [Embed an agent behind a host-owned HTTP server](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/server.rs): Embed an agent behind a host-owned HTTP server. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Copy a skill bundle into its agent workspace](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/skills.rs): Copy a skill bundle into its agent workspace. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.; feature: skills)
+- [SQLite writes and MongoDB configuration through Embed](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/storage.rs): Open a real local SQLite backend and describe a MongoDB deployment without connecting. (offline; optional live MongoDB with OPENHUMAN_EXAMPLE_MONGODB_URL and storage-mongodb.; feature: storage-sqlite)
+- [Streaming progress with a draining receiver](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/streaming.rs): Streaming progress with a draining receiver. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
+- [Structured output parsed and checked against the request](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/structured_output.rs): Structured output parsed and checked against the request. (offline with loopback stubs; no live path.)
+- [Telegram channel answered by its bound agent via a local Bot API](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/telegram.rs): Telegram channel answered by its bound agent via a local Bot API. (offline with loopback stubs; no live path.; feature: channels)
+- [Two agents with independent prompts and working folders](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs): Two agents with independent prompts and working folders. (offline; optional live via OPENHUMAN_EXAMPLE_LIVE=1 and BASE_URL/API_KEY/MODEL.)
diff --git a/llms.txt b/llms.txt
new file mode 100644
index 0000000000..8575ad66f3
--- /dev/null
+++ b/llms.txt
@@ -0,0 +1,52 @@
+# OpenHuman Embed
+
+> Embed OpenHuman runtimes and independently configured agents in Rust applications.
+
+- [Embedding OpenHuman](gitbooks/developing/embed/README.md): `openhuman-embed` runs the OpenHuman core inside your Rust program. Your host owns the user interface, server transport and authentication flow; the core owns agent turns, memory, tools, approvals and execution policy. Calling its typed facades does not require a JSON-RPC server or the desktop shell.
+- [Embedding API reference](gitbooks/developing/embed/api-reference.md): Generate usable local Rust API documentation with `cargo doc -p openhuman-embed --no-deps --open`. Include `--features mcp,skills,channels,storage-sqlite` for the facade gates used by the offline examples, or select the feature set your host actually builds. For all exported optional surfaces use `--all-features`.
+- [Embedding architecture](gitbooks/developing/embed/architecture.md): Embed is the library facade above `openhuman-core`. The TinyHumans layer installs the backend SDK transport and owns product login/session behavior; the RPC layer adds JSON-RPC, server listeners and shipped host boot. A Rust embedder can stay at the facade when it owns those concerns itself.
+- [Concepts](gitbooks/developing/embed/concepts/README.md): Start with Runtime and agents to understand which settings are shared. Then follow the lifecycle of a request through provider selection, tools, approvals and its durable session. The scope tables distinguish runtime composition from the state a host must isolate per agent or profile.
+- [Access and approvals](gitbooks/developing/embed/concepts/access-approvals.md): `Access` groups permission level, origin, standing grants and trusted roots. Choose an origin and tier together: a trusted local host request and an external channel message are different security contexts. `Access::full()` configures both access fields. A sandbox is an additional execution boundary, configured through `AgentDefinitionSpec`.
+- [Agents](gitbooks/developing/embed/concepts/agents.md): Register an `AgentSpec` with `Runtime::agent`. Its ID selects the agent's home, durable session identity and addressed cron/channel work. An `Agent` clone refers to the same instance; it does not copy state or start another core. Runtime-wide credentials remain shared, so two agents are not two authenticated customers.
+- [Channels](gitbooks/developing/embed/concepts/channels.md): `Runtime::channels` creates listeners addressed to a live agent ID. A listener owns its transport task; dropping or stopping it ends that listener. The agent supplies the prompt, provider and tools used for every incoming message instead of handing messages to an operator agent.
+- [Completer](gitbooks/developing/embed/concepts/completer.md): Use `Completer` for one-shot text or structured generation when you do not need an agent, its tool loop or persistent transcript. It takes an explicit route and a `CompletionRequest`; the caller supplies the model and messages for every request.
+- [Cron](gitbooks/developing/embed/concepts/cron.md): The typed `Cron` facade creates named jobs with `JobSpec` and `JobSchedule`. `upsert` preserves a job's identity when the same name is configured again; `runs` exposes execution history. An agent-targeted job resolves the configured agent ID and executes with that agent's provider, prompt, tools and derived context.
+- [Errors](gitbooks/developing/embed/concepts/errors.md): Match the error type at its boundary: `RuntimeError` describes boot/configuration, `AgentError` describes registration/layout, and `CoreError` describes typed facade calls and turns. A missing compiled or selected domain is `CoreError::Unavailable`; it is a capability decision the host can reflect in its UI.
+- [Hooks and seams](gitbooks/developing/embed/concepts/hooks-seams.md): Runtime builders accept host-owned ports for storage, sessions, memory, tools and controller extensions. These are composition seams: the host supplies an implementation of the owning library's contract, while OpenHuman retains access policy, approvals and lifecycle.
+- [MCP](gitbooks/developing/embed/concepts/mcp.md): MCP connects a native agent turn to tools served over an MCP protocol transport. Configure a server on `AgentSpec::mcp`, with its transport, authentication and allowed tool names. Another agent on the same runtime does not inherit that server configuration.
+- [Memory](gitbooks/developing/embed/concepts/memory.md): `Runtime::memory(namespace)` returns a facade bound to that namespace. The caller establishes scope before sending record data; namespace identity is not taken from model arguments or record metadata. Learning and deletion use the selected memory engine contract.
+- [Observability](gitbooks/developing/embed/concepts/observability.md): Subscribe with `Runtime::events` before starting work you want to observe. Each event has a sequence number and runtime identity, with an agent ID and per-call turn ID where applicable. Repeated calls on the same durable session receive different turn IDs; the session ID is not the observation ID.
+- [Profiles and SaaS](gitbooks/developing/embed/concepts/profiles-saas.md): Ordinary runtime agents share an operator's configuration path and credentials. Use `ProfileRuntime` when one server serves different authenticated users who must not share those resources. Provision a profile, install its credential, and retain a `ProfileHandle` while serving that user's requests.
+- [Providers](gitbooks/developing/embed/concepts/providers.md): A runtime provider is the default inference choice for its agents. An agent can override it with an OpenAI-compatible route or a native `ChatModel<()>` through `Provider::custom`. The `providers` facade exposes the request/response contracts so custom adapters do not need to implement an HTTP server.
+- [Runtime defaults](gitbooks/developing/embed/concepts/runtime-defaults.md): The runtime's default provider, access policy and `ModelDefaults` reduce repeated setup. `AgentSpec` can override those defaults for a reviewer, a coding agent or another workload without changing its siblings. Temperature and token limits are forwarded to the selected native model request, rather than being merely descriptive builder values.
+- [Runtime](gitbooks/developing/embed/concepts/runtime.md): A `Runtime` boots the in-process core once. It owns the selected domains, background services, module host and runtime defaults. Its agents share that core while using separately derived contexts. Build one runtime and pass an `Arc<Runtime>` to the parts of your application that register agents.
+- [Skills](gitbooks/developing/embed/concepts/skills.md): A skill bundle contains `SKILL.md` plus any referenced resources. `AgentSpec::skills_dir` copies bundles into the agent's `agents/<id>/skills/` tree. Copying is intentional: discovery rejects symlinked bundles, so linking a shared directory does not install it.
+- [Testing](gitbooks/developing/embed/concepts/testing.md): The runnable examples default to loopback fixtures. They assert request bodies, tool results, file effects, transcript scope and event ordering; a successful Rust compilation alone does not prove those behaviors. Live example execution is explicitly opt-in through the documented environment variables.
+- [Tools](gitbooks/developing/embed/concepts/tools.md): An agent's `ToolScopeSpec` chooses built-ins, named tools or `HostOnly`. Host-only mode starts with the host's advertised tools, requires an explicit bare prompt, and does not inherit an orchestrator tool catalog. This is useful when your application already owns read-only data access or tightly scoped actions.
+- [Turns and sessions](gitbooks/developing/embed/concepts/turns-sessions.md): `Agent::run` collects a turn. `Agent::turn` lets you set an explicit session, per-turn options, progress sink and cancellation before sending. Reuse the returned session identity for follow-up messages that should see the same transcript. Two calls on the same durable session remain distinct turn executions and receive distinct observation IDs.
+- [Embedding FAQ](gitbooks/developing/embed/faq.md): An ordinary embed process supports one `Runtime`; a second build returns `AlreadyRunning`. Add agents to the existing runtime. A multi-user host uses `ProfileRuntime` instead and needs a process dedicated to that mode. See runtime and profiles.
+- [Embedding guides](gitbooks/developing/embed/guides/README.md): Choose the guide that matches your host:
+- [CLI chatbot](gitbooks/developing/embed/guides/cli-chatbot.md): Keep one `Runtime` alive for the process and create an `Agent` for the conversation. The executable example starts with a single message, checks the reply, and prints it. A CLI input loop can send subsequent messages through the same agent; choose a stable thread identity when your host exposes separate conversations.
+- [Deploy a server](gitbooks/developing/embed/guides/deploy-server.md): Your HTTP host can keep a runtime alive and invoke its agents directly. The executable example binds a loopback listener, handles one request, and sends back the agent's reply. It exercises the request path without requiring an RPC server dependency in `openhuman-embed`.
+- [Lean and headless hosts](gitbooks/developing/embed/guides/lean-headless.md): `RuntimeBuilder::lean()` selects the agent, memory, and inference families without background services. Runtime module selection controls what is active; Cargo features control what is compiled. A lean preset alone does not shed compiled dependencies.
+- [Test with a mock backend](gitbooks/developing/embed/guides/mock-backend-testing.md): Run `node scripts/run-embed-examples.mjs` from the repository root. The runner builds and executes every example with the union of required features, clears inherited live-example credentials and operator workspace settings, and requires each program's `EXAMPLE_OK` marker after its assertions.
+- [Multiple agents](gitbooks/developing/embed/guides/multi-agent.md): A runtime owns shared services and credentials. Each `AgentSpec` selects its prompt, model route, access policy, and `action_dir`. Internal agent state belongs to its agent home; the action directory is where acting tools operate.
+- [SaaS with multiple tenants](gitbooks/developing/embed/guides/saas-multi-tenant.md): Use `ProfileRuntime` for a process serving multiple users. Provision each profile, install that profile's credential, and open a handle to its workspace. Reusing a thread id in two profiles does not share their conversation history.
+- [Installation](gitbooks/developing/embed/installation.md): `openhuman-embed` is currently an unpublished workspace crate. Use a local path dependency when developing in this repository, or a Git dependency on `https://github.com/tinyhumansai/openhuman` with `package = "openhuman-embed"`. Pin a reviewed Git revision for a deployed application; the nested vendored libraries are part of that revision's build inputs.
+- [Embedding integrations](gitbooks/developing/embed/integrations/README.md): An embedded runtime composes the capabilities its host supplies. Start with the adapter your application needs:
+- [Channels](gitbooks/developing/embed/integrations/channels.md): Enable the `channels` Cargo feature to use channel adapters. Your host configures the channel credential and binds incoming messages to an agent. In the Telegram example, the Bot API endpoint is a loopback stub, so updates and replies exercise the adapter without contacting Telegram.
+- [Composio](gitbooks/developing/embed/integrations/composio.md): Composio calls use the host backend transport. Install that transport before booting a managed runtime; see TinyHumans managed inference. An explicit inference provider route supplies model inference, not the connector transport.
+- [Local and custom models](gitbooks/developing/embed/integrations/local-models.md): For a local server that implements chat completions, use `Provider::openai_compatible` with its API root and model id. The constructor requires a bearer string even when a particular local server ignores it. Set the endpoint explicitly rather than relying on another user's installed configuration. The OpenAI-compatible example controls can point a live example at that local server.
+- [MCP servers](gitbooks/developing/embed/integrations/mcp.md): Enable the `mcp` Cargo feature and declare a server with `AgentSpec::mcp`. `McpServer::http` takes a registered name and endpoint; `allow_tools` narrows the remote tool list. Server configuration and its connections belong to the agent that declared them.
+- [OpenAI-compatible providers and BYOK](gitbooks/developing/embed/integrations/openai-compatible.md): Construct a route with `Provider::openai_compatible(base_url, api_key).model(model_id)`, then set it on the runtime or an individual agent. Pass the API root, such as a provider's `/v1` URL; the adapter appends `/chat/completions`. Supply an explicit model id so the route can register that model for its workload roles.
+- [Storage drivers](gitbooks/developing/embed/integrations/storage-drivers.md): Enable `storage-sqlite` for SQLite or `storage-mongodb` for MongoDB on your Embed dependency. These Cargo gates make the driver available; choosing a URL selects the runtime backend. Set `RuntimeConfig.storage.url`, pass a URL through `RuntimeBuilder::storage`, or set the `url` field in the `[storage]` section of the host's configuration. `OPENHUMAN_STORAGE_URL` is the environment override used by host configuration resolution.
+- [TinyHumans managed inference](gitbooks/developing/embed/integrations/tinyhumans-managed.md): Embed wraps the core; it does not contain a TinyHumans SDK backend client. A managed host must supply a `BackendTransport` through `RuntimeBuilder::backend_transport`, or boot through the SDK-backed builder in `openhuman-tinyhumans`. The connected host layer owns transport and session login. `RuntimeBuilder::backend_url` selects a URL; it does not install a transport.
+- [Quickstart](gitbooks/developing/embed/quickstart.md): Start from a checkout of the repository and run `cargo run -p openhuman-embed --example run_turn`. The example boots an ephemeral runtime, creates its own local provider/backend fixtures and prints `hello from the stub`. It needs no inference account and does not contact a real backend.
+- [Embedding troubleshooting](gitbooks/developing/embed/troubleshooting.md): Use the typed error and the effective capability report together. A method that was compiled out is a different problem from a configured method with a provider failure. Keep credentials, user prompts and raw provider payloads out of routine diagnostics.
+- [OpenHuman Embed](crates/openhuman-embed/README.md): A typed Rust facade for running the OpenHuman core inside your application: one Runtime per process, with independently configured Agents.
+- [Embedding OpenHuman](gitbooks/developing/embedding.md): The embedding documentation now lives in the Embedding section.
+- [Cookbook](gitbooks/developing/embed/cookbook.md): Executable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.
+- [Compiled feature matrix](gitbooks/developing/embed/capability-matrix.md): This matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.
+- [RuntimeBuilder setters](gitbooks/developing/embed/builder-setters.md): Public consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.
+- [API index](gitbooks/developing/embed/api-index.md): Generate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. Canonical facade source.
+- [Embed examples](crates/openhuman-embed/examples/README.md): Cookbook
diff --git a/package.json b/package.json
index 8ae60b12e1..fc0d3a402f 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
"build": "pnpm --filter openhuman-app build",
"docs:generate": "node scripts/generate-architecture-docs.mjs",
"docs:check": "node scripts/generate-architecture-docs.mjs --check",
- "docs:test": "node --test scripts/__tests__/generate-architecture-docs.test.mjs",
+ "docs:test": "node --test scripts/__tests__/generate-architecture-docs.test.mjs scripts/__tests__/generate-embed-docs.test.mjs",
"test:scripts": "node --test scripts/__tests__/*.test.mjs scripts/mock-api/*.test.mjs scripts/mock-api/routes/__tests__/*.test.mjs",
"test:inventory": "node scripts/generate-test-inventory.mjs",
"compile": "pnpm --filter openhuman-app compile",
diff --git a/scripts/__tests__/embed-contract-boundary.test.mjs b/scripts/__tests__/embed-contract-boundary.test.mjs
new file mode 100644
index 0000000000..03ce72a5d8
--- /dev/null
+++ b/scripts/__tests__/embed-contract-boundary.test.mjs
@@ -0,0 +1,48 @@
+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 });
+ copyFileSync(new URL('../ci/check-agent-runtime-boundary.mjs', import.meta.url), resolve(root, 'scripts/ci/check-agent-runtime-boundary.mjs'));
+ 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 --git a/scripts/__tests__/generate-embed-docs.test.mjs b/scripts/__tests__/generate-embed-docs.test.mjs
new file mode 100644
index 0000000000..abf8a3df7a
--- /dev/null
+++ b/scripts/__tests__/generate-embed-docs.test.mjs
@@ -0,0 +1,155 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { resolve } from 'node:path';
+import { extractAnchors, spliceSnippets, lintEmbedMarkdown, checkLocalLinks, exampleMetadata, exportedNames, runtimeBuilderSetters, proseDescription, generateEmbedDocs } from '../generate-embed-docs.mjs';
+
+const example = '//! Title: Hello\n//! Summary: Builds an offline agent.\n//! Run: offline\n// ANCHOR: hello\nfn main() {}\n// ANCHOR_END: hello\n';
+const marker = '<!-- BEGIN EMBED: crates/openhuman-embed/examples/hello.rs#hello -->\nstale\n<!-- END EMBED -->';
+
+test('extracts real source, excludes marker comments, validates anchors', () => {
+ assert.equal(extractAnchors(example).get('hello'), 'fn main() {}');
+ for (const source of ['// ANCHOR: a', '// ANCHOR_END: a', '// ANCHOR: a\n// ANCHOR_END: a', '// ANCHOR: a\nx\n// ANCHOR_END: a\n// ANCHOR: a', '// ANCHOR: a\n# hidden\n// ANCHOR_END: a']) assert.throws(() => extractAnchors(source));
+});
+test('injects plain rust fences and changes when the compiled source changes', () => {
+ assert.equal(spliceSnippets(marker, () => example), marker.replace('stale', '\n```rust\nfn main() {}\n```\n'));
+ assert.match(spliceSnippets(marker, () => example.replace('fn main() {}', 'fn main() { println!("new"); }')), /println!/);
+ assert.throws(() => spliceSnippets(marker, () => example.replaceAll('hello', 'other')), /Missing anchor/);
+ assert.throws(() => spliceSnippets(marker.replace('examples/hello', 'examples/../hello'), () => example), /must come from/);
+ assert.throws(() => spliceSnippets(marker.replace('<!-- END EMBED -->', ''), () => example), /Unclosed/);
+});
+test('rejects manually typed rust fences, alternative fence style, and hidden lines', () => {
+ for (const source of ['```rust\nx\n```', '~~~rust,no_run\nx\n~~~', '```text\n# hidden\n```', '```text\nx']) assert.throws(() => lintEmbedMarkdown(source));
+ assert.doesNotThrow(() => lintEmbedMarkdown(spliceSnippets(marker, () => example)));
+ assert.doesNotThrow(() => lintEmbedMarkdown('# Title\n\n```text\nnormal\n```'));
+});
+test('local links verify files and headings without following external services', () => {
+ const read = path => { if (path === '/repo/other.md') return '# Some API\n'; throw Error('missing'); };
+ assert.doesNotThrow(() => checkLocalLinks('# Here\n[x](other.md#some-api) [external](https://example.com) [self](#here)', '/repo/doc.md', '/repo', read));
+ assert.throws(() => checkLocalLinks('[x](missing.md)', '/repo/doc.md', '/repo', read), /Broken local/);
+ assert.throws(() => checkLocalLinks('[x](other.md#missing)', '/repo/doc.md', '/repo', read), /Broken heading/);
+ assert.throws(() => checkLocalLinks('[x](../secret)', '/repo/doc.md', '/repo', read), /escapes/);
+ assert.doesNotThrow(() => checkLocalLinks('```rust\nlet x = "[x](missing.md)";\n```', '/repo/doc.md', '/repo', read));
+});
+test('cookbook metadata must come from example headers', () => {
+ assert.deepEqual(exampleMetadata(example, 'hello'), { name: 'hello', title: 'Hello', summary: 'Builds an offline agent.', run: 'offline', feature: undefined });
+ assert.throws(() => exampleMetadata('fn main() {}', 'bad'), /headers/);
+});
+test('generate then check is stable, edited source fails check, no prose authored by tooling', () => {
+ const root = mkdtempSync(resolve(tmpdir(), 'embed-docs-'));
+ try {
+ mkdirSync(resolve(root, 'gitbooks/developing/embed'), { recursive: true });
+ mkdirSync(resolve(root, 'crates/openhuman-embed/examples'), { recursive: true });
+ mkdirSync(resolve(root, 'crates/openhuman-embed/src/runtime'), { recursive: true });
+ const builder = resolve(root, 'crates/openhuman-embed/src/runtime/builder.rs');
+ writeFileSync(builder, 'impl RuntimeBuilder { pub fn max_agents(mut self, limit: usize) -> Self { self } }');
+ writeFileSync(resolve(root, 'crates/openhuman-embed/src/lib.rs'), 'pub use runtime::{Runtime, RuntimeBuilder};');
+ const path = resolve(root, 'crates/openhuman-embed/examples/hello.rs');
+ writeFileSync(path, example);
+ writeFileSync(resolve(root, 'gitbooks/developing/embed/index.md'), '---\ndescription: Metadata description\nicon: code\n---\n\n# Introduction\n\nThe actual introduction explains the host.\n\n' + marker + '\n');
+ mkdirSync(resolve(root, 'docs/gitbooks/en/developing'), { recursive: true });
+ writeFileSync(resolve(root, 'gitbooks/developing/embedding.md'), '# Compatibility\n\n[Introduction](embed/index.md)\n');
+ writeFileSync(resolve(root, 'docs/gitbooks/en/developing/embedding.md'), '---\ndescription: >-\n Preserved existing GitBook metadata.\nicon: code\nlayout:\n width: wide\n---\n\n# Old pointer\n');
+ writeFileSync(resolve(root, 'gitbooks/developing/embed/retired.md'), '# Retired page\n\nA temporary canonical page.\n');
+ const capabilities = resolve(root, 'capabilities.json');
+ writeFileSync(capabilities, '{"schema_version":1,"compiled_features":{"mcp":true,"channels":false}}');
+ generateEmbedDocs({ root, capabilities });
+ generateEmbedDocs({ root, capabilities, check: true });
+ assert.match(readFileSync(resolve(root, 'llms-full.txt'), 'utf8'), /fn main\(\)/);
+ const published = resolve(root, 'docs/gitbooks/en/developing/embed/index.md');
+ assert.equal(readFileSync(published, 'utf8'), readFileSync(resolve(root, 'gitbooks/developing/embed/index.md'), 'utf8'));
+ assert.equal(readFileSync(resolve(root, 'docs/gitbooks/en/developing/embed/api-index.json'), 'utf8'), readFileSync(resolve(root, 'gitbooks/developing/embed/api-index.json'), 'utf8'));
+ assert.match(readFileSync(resolve(root, 'docs/gitbooks/en/developing/embedding.md'), 'utf8'), /Preserved existing GitBook metadata[\s\S]*width: wide[\s\S]*# Compatibility/);
+ const llms = readFileSync(resolve(root, 'llms.txt'), 'utf8');
+ assert.match(llms, /Introduction.*The actual introduction explains the host/);
+ assert.doesNotMatch(llms, /docs\/gitbooks\/en|Metadata description/);
+ assert.equal((readFileSync(resolve(root, 'llms-full.txt'), 'utf8').match(/# Introduction/g) ?? []).length, 1);
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/api-index.md'), 'utf8'), /cargo doc.*unpublished/);
+ assert.doesNotMatch(readFileSync(resolve(root, 'gitbooks/developing/embed/api-index.md'), 'utf8'), /https:\/\/docs[.]rs/);
+ writeFileSync(published, readFileSync(published, 'utf8').replace('actual introduction', 'mirror drift'));
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), /docs\/gitbooks\/en\/developing\/embed\/index[.]md/);
+ generateEmbedDocs({ root, capabilities });
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/api-index.md'), 'utf8'), /schema_version/);
+ assert.deepEqual(JSON.parse(readFileSync(resolve(root, 'gitbooks/developing/embed/api-index.json'), 'utf8')).exports, ['Runtime', 'RuntimeBuilder']);
+ assert.match(readFileSync(resolve(root, 'crates/openhuman-embed/examples/README.md'), 'utf8'), /Cookbook/);
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/builder-setters.md'), 'utf8'), /pub fn max_agents/);
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/builder-setters.md'), 'utf8'), /https:\/\/github\.com\/tinyhumansai\/openhuman\/blob\/main\/crates\/openhuman-embed\/src\/runtime\/builder\.rs#L1/);
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/cookbook.md'), 'utf8'), /https:\/\/github\.com\/tinyhumansai\/openhuman\/blob\/main\/crates\/openhuman-embed\/examples\/hello\.rs/);
+ writeFileSync(builder, 'impl RuntimeBuilder { pub fn max_agents(mut self, limit: usize) -> Self { self } pub fn new_knob(self, enabled: bool) -> Self { self } }');
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), /drift/);
+ generateEmbedDocs({ root, capabilities });
+ assert.match(readFileSync(resolve(root, 'gitbooks/developing/embed/builder-setters.md'), 'utf8'), /new_knob/);
+ writeFileSync(builder, 'impl RuntimeBuilder { pub fn new_knob(self, enabled: bool) -> Self { self } }');
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), /drift/);
+ generateEmbedDocs({ root, capabilities });
+ assert.doesNotMatch(readFileSync(resolve(root, 'gitbooks/developing/embed/builder-setters.md'), 'utf8'), /max_agents/);
+ const matrix = readFileSync(resolve(root, 'gitbooks/developing/embed/capability-matrix.md'), 'utf8');
+ assert.match(matrix, /channels` \| No/);
+ assert.match(matrix, /mcp` \| Yes/);
+ writeFileSync(capabilities, '{"schema_version":1,"compiled_features":{"mcp":false,"channels":false}}');
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), /drift/);
+ generateEmbedDocs({ root, capabilities });
+ generateEmbedDocs({ root, capabilities, check: true });
+ writeFileSync(path, example.replace('fn main() {}', 'fn main() { println!("changed"); }'));
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), error => {
+ assert.match(error.message, /gitbooks\/developing\/embed\/index[.]md/);
+ assert.match(error.message, /docs\/gitbooks\/en\/developing\/embed\/index[.]md/);
+ return true;
+ });
+ generateEmbedDocs({ root, capabilities });
+ generateEmbedDocs({ root, capabilities, check: true });
+ assert.match(readFileSync(published, 'utf8'), /println!\("changed"\)/);
+ unlinkSync(resolve(root, 'gitbooks/developing/embed/retired.md'));
+ assert.throws(() => generateEmbedDocs({ root, capabilities, check: true }), /docs\/gitbooks\/en\/developing\/embed\/retired[.]md/);
+ generateEmbedDocs({ root, capabilities });
+ assert.equal(existsSync(resolve(root, 'docs/gitbooks/en/developing/embed/retired.md')), false);
+ generateEmbedDocs({ root, capabilities, check: true });
+ } finally { rmSync(root, { recursive: true, force: true }); }
+});
+
+test('API index includes public export aliases and excludes internal facade', () => {
+ assert.deepEqual(exportedNames('pub mod __host;\npub mod process;\npub mod providers { }\n#[doc(hidden)]\npub use runtime::BuilderSummary;\npub use runtime::{Runtime, RuntimeBuilder};\npub use a::Config as Configuration;'), ['Configuration', 'Runtime', 'RuntimeBuilder', 'process', 'providers']);
+});
+
+
+test('builder setters include real consuming signatures and exclude presets, other types and strings', () => {
+ const source = `impl Runtime { pub fn wrong(self) -> Self { self } }
+impl RuntimeBuilder {
+ pub fn library() -> Self { Self::new() }
+ pub fn describe(&self) -> Self { self.clone() }
+ pub fn build(self) -> Result<Self> { todo!() }
+ pub(crate) fn hidden(self) -> Self { self }
+ pub fn actual(
+ mut self,
+ hook: impl Fn(u32) -> u32,
+ ) -> Self { let text = "pub fn bogus(self) -> Self { }"; self }
+ // pub fn commented(self) -> Self { self }
+}
+impl RuntimeBuilder { pub fn another(self, path: impl Into<PathBuf>) -> Self { self } }`;
+ const setters = runtimeBuilderSetters(source, 'builder.rs');
+ assert.deepEqual(setters.map(setter => setter.name), ['actual', 'another']);
+ assert.equal(setters[0].signature, 'pub fn actual( mut self, hook: impl Fn(u32) -> u32, ) -> Self');
+ assert.equal(setters[0].source, 'builder.rs');
+ assert.equal(setters[0].line, 7);
+});
+
+
+test('builder parser masks multiline Rust literals and raw strings without losing braces', () => {
+ const source = String.raw`impl RuntimeBuilder {
+ pub fn knob(self, name: &'static str) -> Self {
+ let raw = r###"{ \" nested quotes and // data"###;
+ let continued = "{ \
+ continued string";
+ let character = '{';
+ self
+ }
+ }`;
+ assert.deepEqual(runtimeBuilderSetters(source, 'source.rs').map(setter => setter.name), ['knob']);
+});
+
+
+test('index descriptions select prose rather than metadata, snippets or generation markers', () => {
+ assert.equal(proseDescription('---\ndescription: >-\n Metadata\nicon: code\n---\n# Title\n\n<!-- generated -->\n```rust\nfn main() {}\n```\n\nThe [host](host.md) owns transport.\n'), 'The host owns transport.');
+ assert.equal(proseDescription('# Title\n\n| API | Scope |\n| --- | --- |\n- [link](foo.md)\n\nActual introduction.'), 'Actual introduction.');
+});
diff --git a/scripts/__tests__/run-embed-examples.test.mjs b/scripts/__tests__/run-embed-examples.test.mjs
new file mode 100644
index 0000000000..ce3da711a4
--- /dev/null
+++ b/scripts/__tests__/run-embed-examples.test.mjs
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { assertExampleOutput, discoverExamples, offlineEnvironment, runExamples } from "../run-embed-examples.mjs";
+
+test("the runner strips inherited live credentials and operator workspace settings", () => {
+ assert.deepEqual(offlineEnvironment({ PATH: "bin", OPENHUMAN_EXAMPLE_LIVE: "1", OPENHUMAN_EXAMPLE_API_KEY: "secret", OPENHUMAN_BACKEND_API_KEY: "secret", OPENHUMAN_STORAGE_URL: "remote", OPENHUMAN_WORKSPACE: "operator", OPENHUMAN_KEYRING_MASTER_KEY: "operator-key", OPENHUMAN_KEYRING_MASTER_KEY_FILE: "operator-file", OPENHUMAN_KEYRING_BACKEND: "os" }), { PATH: "bin" });
+});
+test("zero exit without the example's behavioral marker is a failure", () => {
+ assert.throws(() => assertExampleOutput("hello", {status:0,stdout:"EXAMPLE_OK another\n",stderr:""}), /behavioral assertion marker/);
+ assert.throws(() => assertExampleOutput("hello", {status:1,stdout:"EXAMPLE_OK hello\n",stderr:"failed"}), /exited 1/);
+ assert.doesNotThrow(() => assertExampleOutput("hello", {status:0,stdout:"EXAMPLE_OK hello\n",stderr:""}));
+});
+test("runner executes feature gated examples and checks stdout", () => {
+ const calls = [];
+ runExamples({examples:[{name:"telegram",features:["channels"]}],environment:{OPENHUMAN_EXAMPLE_LIVE:"1"}, run(command,args,options) {
+ calls.push({command,args,options});
+ return {status:0,stdout:"EXAMPLE_OK telegram\n",stderr:""};
+ }});
+ assert.ok(calls[0].command.endsWith("ci-cancel-aware.sh"));
+ assert.ok(calls[0].args.includes("--features"));
+ assert.ok(calls[0].args.includes("channels"));
+ assert.equal(calls[0].options.env.OPENHUMAN_EXAMPLE_LIVE, undefined);
+});
+test("every discoverable example has an offline output contract", () => {
+ const examples = discoverExamples();
+ assert.ok(examples.length >= 18);
+ assert.ok(examples.some((example) => example.name === "mcp" && example.features.includes("mcp")));
+});
+
+test("all example runs share the same required feature graph", () => {
+ const featureArguments = [];
+ runExamples({
+ examples: [{name:"skills",features:["skills"]},{name:"mcp",features:["mcp"]}],
+ environment: {},
+ run(_command,args) {
+ featureArguments.push(args[args.indexOf("--features") + 1]);
+ const name = args[args.indexOf("--example") + 1];
+ return {status:0,stdout:`EXAMPLE_OK ${name}\n`,stderr:""};
+ },
+ });
+ assert.deepEqual(featureArguments, ["mcp,skills", "mcp,skills"]);
+});
diff --git a/scripts/__tests__/self-hosted-lanes.test.mjs b/scripts/__tests__/self-hosted-lanes.test.mjs
index 8339f4bf03..567f9dcb8e 100644
--- a/scripts/__tests__/self-hosted-lanes.test.mjs
+++ b/scripts/__tests__/self-hosted-lanes.test.mjs
@@ -155,7 +155,7 @@ test("a core-only change still installs the node deps rust-core-coverage's mock
assert.deepEqual(orderProblems(sub), []);
});
-test("doctests and module-gated tests are outside the PR lane, tui tests run on PRs", () => {
+test("core doctests remain outside PR coverage; embed doctests and tui tests run on PRs", () => {
for (const plan of plans()) {
const cov = plan.lanes
.find((l) => l.name === "rust-cov")
@@ -164,7 +164,12 @@ test("doctests and module-gated tests are outside the PR lane, tui tests run on
assert.equal(cov.env.OH_COV_TUI, "1");
const runs = allRuns(plan).join("\n");
assert.doesNotMatch(runs, /cargo test -p openhuman --doc/);
- assert.doesNotMatch(runs, /cargo test -p openhuman-(embed|tinyhumans)\b/);
+ assert.doesNotMatch(runs, /cargo test -p openhuman-(embed|tinyhumans)\b(?! --doc)/);
+ assert.match(runs, /cargo test -p openhuman-embed --doc/);
+ const doc = plan.lanes.find(l => l.name === "rust-lint").checks.find(c => c.name === "embed-rustdoc");
+ assert.equal(doc.env.RUSTDOCFLAGS, "-D warnings");
+ assert.match(doc.run, /cargo doc -p openhuman-embed --no-deps/);
+ assert.match(runs, /node scripts\/run-embed-examples.mjs/);
assert.doesNotMatch(runs, /-p openhuman --no-default-features$/m);
assert.doesNotMatch(runs, /tool_output_tabulates_a_large_graph/);
}
diff --git a/scripts/ci/check-agent-runtime-boundary.mjs b/scripts/ci/check-agent-runtime-boundary.mjs
index 0a742f64cb..29fb5d9ffb 100644
--- a/scripts/ci/check-agent-runtime-boundary.mjs
+++ b/scripts/ci/check-agent-runtime-boundary.mjs
@@ -11,6 +11,36 @@ const tinyagentsRoot = resolve(repoRoot, "vendor/tinyagents/crates");
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))]));
+
+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 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([
@@ -280,7 +310,8 @@ function add(rule, path, line, text) {
// Scan every OpenHuman crate: facades are not restricted to agent/.
for (const path of await filesUnder(openhumanCratesRoot, (path) => path.endsWith(".rs") && /\/src\//.test(path))) {
const rel = relative(repoRoot, path);
- for (const { line, text, raw } of codeLines(await readFile(path, "utf8"))) {
+ const lines = codeLines(await readFile(path, "utf8"));
+ 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)) add("openhuman-tool-calling-facade", path, line, raw);
@@ -294,7 +325,8 @@ for (const path of await filesUnder(openhumanCratesRoot, (path) => path.endsWith
const declaresDeletedModule = deletedTaskLocalModules.some((name) => new RegExp(`\\bmod\\s+${escapeRegex(name)}\\s*;`).test(text));
if ((isListedTaskLocalFile && /\btokio\s*::\s*task_local!/.test(text)) || namesTaskLocalAccessor || namesTaskLocalStatic || usesGenericAccessor || declaresDeletedModule) add("openhuman-task-local", path, line, raw);
}
- if (/\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text)) add("openhuman-upstream-reexport", path, line, raw);
+ if (/\bpub(?:\s*\([^)]*\))?\s+use\s+(?:tinyagents(?:_[a-z_]+)?|tinytools(?:_[a-z_]+)?|tinyinference(?:_[a-z_]+)?)\s*::/i.test(text)
+ && !isEmbedContractExport(rel, lines, index)) add("openhuman-upstream-reexport", path, line, raw);
}
}
diff --git a/scripts/ci/self-hosted/lanes-plan.mjs b/scripts/ci/self-hosted/lanes-plan.mjs
index c7b80638ab..32eeaf13e3 100644
--- a/scripts/ci/self-hosted/lanes-plan.mjs
+++ b/scripts/ci/self-hosted/lanes-plan.mjs
@@ -415,6 +415,22 @@ export function buildPlan({ profile, areas, env = {}, isPullRequest = true }) {
when: core,
run: "cargo check -p openhuman-embed --no-default-features",
},
+ {
+ name: "embed-doctests",
+ when: core,
+ run: "bash scripts/ci-cancel-aware.sh cargo test -p openhuman-embed --doc",
+ },
+ {
+ name: "embed-rustdoc",
+ when: core,
+ env: { RUSTDOCFLAGS: "-D warnings" },
+ run: "bash scripts/ci-cancel-aware.sh cargo doc -p openhuman-embed --no-deps",
+ },
+ {
+ name: "embed-offline-examples",
+ when: core,
+ run: "node scripts/run-embed-examples.mjs",
+ },
{
name: "tinyhumans-clippy",
when: core,
diff --git a/scripts/generate-architecture-docs.mjs b/scripts/generate-architecture-docs.mjs
index 772a6e98f3..ad718bce22 100644
--- a/scripts/generate-architecture-docs.mjs
+++ b/scripts/generate-architecture-docs.mjs
@@ -24,6 +24,7 @@
*/
import { readFileSync, writeFileSync } from 'node:fs';
+import { generateEmbedDocs } from './generate-embed-docs.mjs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -142,6 +143,7 @@ export function computeFrontendDoc() {
function main() {
const check = process.argv.includes('--check');
+ generateEmbedDocs({ check });
const { updated, current } = computeFrontendDoc();
if (check) {
diff --git a/scripts/generate-embed-docs.mjs b/scripts/generate-embed-docs.mjs
new file mode 100644
index 0000000000..2b5ee93340
--- /dev/null
+++ b/scripts/generate-embed-docs.mjs
@@ -0,0 +1,251 @@
+#!/usr/bin/env node
+/** Embed documentation is generated only from compiled examples and runtime introspection. */
+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, extname, relative, resolve, sep } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const MARKER = /^<!-- BEGIN EMBED: ([^\s#]+)#([\w-]+) -->$/;
+
+export function extractAnchors(source) {
+ const regions = new Map();
+ const active = new Map();
+ for (const line of source.split('\n')) {
+ const start = /^\s*\/\/ ANCHOR: ([\w-]+)\s*$/.exec(line);
+ const end = /^\s*\/\/ (?:ANCHOR_END|END ANCHOR): ([\w-]+)\s*$/.exec(line);
+ if (start) {
+ if (regions.has(start[1]) || active.has(start[1])) throw new Error(`Duplicate anchor: ${start[1]}`);
+ active.set(start[1], []);
+ } else if (end) {
+ if (!active.has(end[1])) throw new Error(`Unmatched anchor end: ${end[1]}`);
+ const body = active.get(end[1]).join('\n');
+ if (!body.trim()) throw new Error(`Empty anchor: ${end[1]}`);
+ if (/^\s*#(?:\s|$)/m.test(body)) throw new Error(`Hidden rustdoc line in anchor: ${end[1]}`);
+ regions.set(end[1], body);
+ active.delete(end[1]);
+ } else {
+ for (const lines of active.values()) lines.push(line);
+ }
+ }
+ if (active.size) throw new Error(`Unclosed anchors: ${[...active.keys()].join(', ')}`);
+ return regions;
+}
+
+export function spliceSnippets(markdown, readSource) {
+ const lines = markdown.split('\n');
+ const output = [];
+ for (let i = 0; i < lines.length; i++) {
+ const match = MARKER.exec(lines[i]);
+ if (!match) {
+ if (lines[i].includes('BEGIN EMBED:') || lines[i] === '<!-- END EMBED -->') throw new Error('Malformed or unmatched embed splice marker');
+ output.push(lines[i]);
+ continue;
+ }
+ output.push(lines[i]);
+ const source = match[1];
+ if (!source.startsWith('crates/openhuman-embed/examples/') || !source.endsWith('.rs') || source.split('/').includes('..')) throw new Error(`Snippet must come from an embed example: ${source}`);
+ const body = extractAnchors(readSource(source)).get(match[2]);
+ if (body === undefined) throw new Error(`Missing anchor ${source}#${match[2]}`);
+ output.push('', '```rust', body, '```', '');
+ while (++i < lines.length && lines[i] !== '<!-- END EMBED -->') {
+ if (lines[i].includes('BEGIN EMBED:')) throw new Error('Nested embed splice markers');
+ }
+ if (i === lines.length) throw new Error('Unclosed embed splice marker');
+ output.push(lines[i]);
+ }
+ return output.join('\n');
+}
+
+export function lintEmbedMarkdown(markdown) {
+ let generated = false;
+ let fence = null;
+ for (const line of markdown.split('\n')) {
+ if (MARKER.test(line)) generated = true;
+ if (line === '<!-- END EMBED -->') generated = false;
+ const opening = /^\s*(`{3,}|~{3,})(.*)$/.exec(line);
+ if (opening) {
+ if (fence && opening[1][0] === fence[0] && opening[1].length >= fence.length && !opening[2].trim()) fence = null;
+ else if (!fence) {
+ const language = opening[2].trim();
+ if (/^rust(?:\b|,)/i.test(language) && !generated) throw new Error('Hand-written Rust fence; use an example splice marker');
+ fence = opening[1];
+ }
+ } else if (fence && /^\s*#(?:\s|$)/.test(line)) throw new Error('Hidden rustdoc line in prose code block');
+ }
+ if (fence) throw new Error('Unclosed Markdown fence');
+}
+
+function markdownFiles(directory, extensions = new Set(['.md'])) {
+ if (!existsSync(directory)) return [];
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
+ const path = resolve(directory, entry.name);
+ return entry.isDirectory() ? markdownFiles(path, extensions) : extensions.has(extname(path)) ? [path] : [];
+ }).sort();
+}
+
+export function checkLocalLinks(markdown, document, root, read = path => readFileSync(path, 'utf8')) {
+ const headings = source => new Set([...source.matchAll(/^#{1,6}\s+(.+)$/gm)].map(match => match[1].toLowerCase().replace(/[`*_]/g, '').replace(/[^\p{L}\p{N}\s-]/gu, '').trim().replace(/\s/g, '-')));
+ // Fenced code is data, not Markdown links.
+ const prose = markdown.replace(/^\s*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\s*\1\s*$/gm, '');
+ for (const match of prose.matchAll(/!?\[[^\]]*\]\(([^\s)]+)(?:\s+"[^"]*")?\)/g)) {
+ const url = match[1].replace(/^<|>$/g, '');
+ if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(url)) continue;
+ const [link, fragment] = url.split('#');
+ const path = link ? resolve(link.startsWith('/') ? root : dirname(document), decodeURIComponent(link.replace(/^\//, '').split('?')[0])) : document;
+ if (path !== root && !path.startsWith(root + sep)) throw new Error(`Link escapes repository: ${url}`);
+ let source;
+ try { source = path === document ? markdown : read(path); } catch { throw new Error(`Broken local link in ${document}: ${url}`); }
+ if (fragment && extname(path) === '.md' && !headings(source).has(decodeURIComponent(fragment))) throw new Error(`Broken heading link in ${document}: ${url}`);
+ }
+}
+
+export function exampleMetadata(source, name) {
+ const field = key => new RegExp(`^//! ${key}: (.+)$`, 'm').exec(source)?.[1];
+ const title = field('Title');
+ const summary = field('Summary');
+ if (!title || !summary) throw new Error(`Example ${name} needs //! Title: and //! Summary: headers`);
+ const feature = field('Feature');
+ return { name, title, summary, run: field('Run') ?? 'offline', feature: feature === 'default' ? undefined : feature };
+}
+
+/** Public facade exports, suitable for rustdoc search links (including aliases). */
+export function exportedNames(source) {
+ // Doc-hidden compatibility seams are not part of the curated host API.
+ source = source.replace(/#\[doc\(hidden\)\]\s*(?:#\[[^\]]+\]\s*)*pub\s+(?:use\s+[\s\S]*?|mod\s+\w+);/g, '');
+ const names = new Set();
+ for (const match of source.matchAll(/^pub mod ([a-zA-Z_][\w]*)\s*[;{]/gm)) if (!match[1].startsWith('__')) names.add(match[1]);
+ for (const match of source.matchAll(/^pub use ([\s\S]*?);/gm)) {
+ const body = match[1].replace(/\/\/[^\n]*/g, '');
+ const items = body.includes('{') ? body.slice(body.indexOf('{') + 1, body.lastIndexOf('}')).split(',') : [body];
+ for (const item of items) {
+ const name = /(?:as\s+|::|^)([a-zA-Z_]\w*)\s*$/.exec(item.trim())?.[1];
+ if (name && !name.startsWith('__')) names.add(name);
+ }
+ }
+ return [...names].sort();
+}
+
+/** Consuming public setters on RuntimeBuilder, excluding presets and borrowed methods. */
+export function runtimeBuilderSetters(source, file) {
+ // Mask strings and comments without moving offsets used by source links.
+ const masked = source.replace(/r(#+)"[\s\S]*?"\1|r"[\s\S]*?"|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n])'|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, value => value.replace(/[^\n]/g, ' '));
+ const setters = [];
+ for (const declaration of masked.matchAll(/\bimpl\s+RuntimeBuilder\s*\{/g)) {
+ const begin = declaration.index + declaration[0].length;
+ let end = begin;
+ let depth = 1;
+ while (end < masked.length && depth) {
+ if (masked[end] === '{') depth++;
+ if (masked[end] === '}') depth--;
+ end++;
+ }
+ if (depth) throw new Error(`Unclosed RuntimeBuilder implementation in ${file}`);
+ const body = masked.slice(begin, end - 1);
+ for (const method of body.matchAll(/\bpub\s+(?:async\s+)?fn\s+(\w+)[^(]*\(/g)) {
+ const preceding = body.slice(0, method.index);
+ if ([...preceding].reduce((nesting, char) => nesting + (char === '{' ? 1 : char === '}' ? -1 : 0), 0)) continue;
+ const open = begin + method.index + method[0].length - 1;
+ let close = open + 1;
+ let parameters = 1;
+ while (close < end && parameters) {
+ if (masked[close] === '(') parameters++;
+ if (masked[close] === ')') parameters--;
+ close++;
+ }
+ if (parameters) throw new Error(`Unclosed method signature in ${file}`);
+ const receiver = masked.slice(open + 1, close - 1).split(',')[0].trim();
+ const returned = /^\s*->\s*Self\b/.exec(masked.slice(close));
+ if (!/^(?:mut\s+)?self(?:\s*:\s*Self)?$/.test(receiver) || !returned) continue;
+ const offset = begin + method.index;
+ setters.push({ name: method[1], signature: source.slice(offset, close + returned[0].length).replace(/\s+/g, ' ').trim(), source: file, line: source.slice(0, offset).split('\n').length });
+ }
+ }
+ return setters.sort((left, right) => left.name.localeCompare(right.name));
+}
+
+/** Human-facing index descriptions ignore GitBook metadata and code/data blocks. */
+export function proseDescription(markdown) {
+ const prose = markdown
+ .replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '')
+ .replace(/^\s*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\s*\1\s*$/gm, '')
+ .replace(/<!--[\s\S]*?-->/g, '');
+ return (prose.split('\n').find(line => line.trim() && !/^\s*(?:#|[|]|[-*]\s|\d+[.]\s|[{]%|<)/.test(line)) ?? '')
+ .trim().replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
+}
+
+function preserveFrontmatter(source, existing) {
+ const prefix = /^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/;
+ const metadata = prefix.exec(existing)?.[0];
+ return metadata ? metadata + source.replace(prefix, '') : source;
+}
+
+export function generateEmbedDocs({ root = ROOT, check = false, capabilities } = {}) {
+ const directory = resolve(root, 'gitbooks/developing/embed');
+ if (!existsSync(directory)) return; // Track D starts only after code/examples/tooling verification.
+ const docs = markdownFiles(directory).filter(path => !['cookbook.md', 'api-index.md', 'capability-matrix.md', 'builder-setters.md'].includes(path.split(sep).at(-1)));
+ if (!docs.length) throw new Error('Embed documentation directory is empty');
+ const desired = new Map();
+ for (const path of ['crates/openhuman-embed/README.md', 'gitbooks/developing/embedding.md'].map(path => resolve(root, path))) {
+ if (existsSync(path)) docs.push(path);
+ }
+ for (const path of docs) {
+ const current = readFileSync(path, 'utf8');
+ lintEmbedMarkdown(current);
+ const updated = spliceSnippets(current, source => readFileSync(resolve(root, source), 'utf8'));
+ lintEmbedMarkdown(updated);
+ desired.set(path, updated);
+ }
+ const examples = readdirSync(resolve(root, 'crates/openhuman-embed/examples')).filter(name => name.endsWith('.rs')).sort().map(file => exampleMetadata(readFileSync(resolve(root, 'crates/openhuman-embed/examples', file), 'utf8'), file.slice(0, -3)));
+ desired.set(resolve(directory, 'cookbook.md'), '# Cookbook\n\n<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->\n\nExecutable recipes are indexed from their source headers. Each entry records the declared run mode and any named Embed feature required by the example. Full source includes the surrounding setup and assertions.\n\n' + examples.map(example => `## ${example.title}\n\n${example.summary}\n\n[Source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/${example.name}.rs) · ${example.run}${example.feature ? ` · feature: ${example.feature}` : ''}\n\nRun: \`cargo run -p openhuman-embed --example ${example.name}${example.feature ? ` --features ${example.feature}` : ''}\`\n`).join('\n'));
+ const report = capabilities ? JSON.parse(readFileSync(capabilities, 'utf8')) : JSON.parse(execFileSync('bash', ['scripts/ci-cancel-aware.sh', 'cargo', 'run', '--quiet', '-p', 'openhuman-embed', '--example', 'capability_report', '--', '--json'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }));
+ const exports = exportedNames(readFileSync(resolve(root, 'crates/openhuman-embed/src/lib.rs'), 'utf8'));
+ if (!report || typeof report !== 'object' || !Number.isInteger(report.schema_version) || !report.compiled_features || typeof report.compiled_features !== 'object') throw new Error('Capability report must be versioned RuntimeInfo JSON');
+ desired.set(resolve(directory, 'capability-matrix.md'), '# Compiled feature matrix\n\n<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->\n\nThis matrix comes from the default-feature compiled capability-report example. Runtime presets can narrow enabled domains and services; core Cargo features determine which implementations are available. Named Embed features also gate facade exports: enable `mcp` or `skills` explicitly for their public setters even when core defaults compile those implementations. Embed defaults enable the named `channels` feature. See the installation guide for these separate layers.\n\n| Cargo feature | Compiled in this build |\n| --- | --- |\n' + Object.entries(report.compiled_features).sort(([left], [right]) => left.localeCompare(right)).map(([feature, enabled]) => `| \`${feature}\` | ${enabled ? 'Yes' : 'No'} |`).join('\n') + '\n');
+ const runtimeDirectory = resolve(root, 'crates/openhuman-embed/src/runtime');
+ const setters = existsSync(runtimeDirectory) ? readdirSync(runtimeDirectory).filter(file => file.endsWith('.rs') && !file.endsWith('_tests.rs')).sort().flatMap(file => {
+ const path = resolve(runtimeDirectory, file);
+ return runtimeBuilderSetters(readFileSync(path, 'utf8'), relative(root, path).split(sep).join('/'));
+ }).sort((left, right) => left.name.localeCompare(right.name)) : [];
+ desired.set(resolve(directory, 'builder-setters.md'), '# RuntimeBuilder setters\n\n<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->\n\nPublic consuming methods that return `Self`, extracted from the RuntimeBuilder implementations. Static host and weight presets, inspection methods and build/run methods are excluded.\n\n' + setters.map(setter => `- [\`${setter.name}\`](https://github.com/tinyhumansai/openhuman/blob/main/${setter.source}#L${setter.line}): \`${setter.signature}\``).join('\n') + '\n');
+ desired.set(resolve(directory, 'api-index.md'), '# API index\n\n<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->\n\nGenerate the complete local Rust API reference with `cargo doc -p openhuman-embed --all-features --no-deps --open`. This crate is currently unpublished; docs.rs is a future publication target. Names below are source-listed exports, including conditional Cargo-gated items; local rustdoc with your selected features describes availability. [Canonical facade source](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs).\n\n' + exports.map(name => `- [\`${name}\`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/src/lib.rs)`).join('\n') + '\n\nThe compiled capability report describes this build:\n\n```json\n' + JSON.stringify(report, null, 2) + '\n```\n');
+ desired.set(resolve(directory, 'api-index.json'), JSON.stringify({
+ schema_version: 1,
+ exports,
+ builder_setters: setters,
+ capabilities: report,
+ pages: [...desired.keys()].filter(path => path.endsWith('.md')).map(path => relative(root, path).split(sep).join('/')),
+ }, null, 2) + '\n');
+ desired.set(resolve(root, 'crates/openhuman-embed/examples/README.md'), '# Embed examples\n\n<!-- Generated by scripts/generate-embed-docs.mjs; do not edit. -->\n\n[Cookbook](../../../gitbooks/developing/embed/cookbook.md)\n\n' + examples.map(example => `- [${example.title}](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/${example.name}.rs): ${example.summary} (${example.run}${example.feature ? `; feature: ${example.feature}` : ''})`).join('\n') + '\n');
+ const index = '# OpenHuman Embed\n\n> Embed OpenHuman runtimes and independently configured agents in Rust applications.\n\n' + [...desired].filter(([path]) => path.endsWith('.md')).map(([path, source]) => `- [${/^# (.+)$/m.exec(source)?.[1] ?? 'Documentation'}](${relative(root, path).split(sep).join('/')}): ${proseDescription(source)}`).join('\n') + '\n';
+ desired.set(resolve(root, 'llms.txt'), index);
+ desired.set(resolve(root, 'llms-full.txt'), index + '\n' + [...desired].filter(([path]) => path.endsWith('.md')).map(([path, source]) => `<!-- Source: ${relative(root, path)} -->\n${source}`).join('\n'));
+ desired.set(resolve(root, 'EMBED.md'), index + '\nSee the generated [API index](gitbooks/developing/embed/api-index.md) for build capabilities.\n');
+ // Aggregate only canonical pages above. Publish their exact generated bodies
+ // afterward, so English copies never duplicate llms-full content or index paths.
+ const publishedDirectory = resolve(root, 'docs/gitbooks/en/developing/embed');
+ for (const [path, source] of [...desired]) {
+ if (path.startsWith(directory + sep)) desired.set(resolve(publishedDirectory, relative(directory, path)), source);
+ }
+ const compatibility = resolve(root, 'gitbooks/developing/embedding.md');
+ const publishedCompatibility = resolve(root, 'docs/gitbooks/en/developing/embedding.md');
+ if (desired.has(compatibility)) {
+ desired.set(publishedCompatibility, preserveFrontmatter(desired.get(compatibility), existsSync(publishedCompatibility) ? readFileSync(publishedCompatibility, 'utf8') : ''));
+ }
+ for (const [path, source] of desired) {
+ if (path.endsWith('.md')) checkLocalLinks(source, path, root, link => desired.get(link) ?? readFileSync(link, 'utf8'));
+ }
+ const obsolete = markdownFiles(publishedDirectory, new Set(['.md', '.json'])).filter(path => !desired.has(path));
+ const stale = [...desired].filter(([path, source]) => !existsSync(path) || readFileSync(path, 'utf8') !== source);
+ if (check && (stale.length || obsolete.length)) throw new Error(`Embed documentation drift: ${[...stale.map(([path]) => path), ...obsolete].map(path => relative(root, path)).join(', ')}. Run pnpm docs:generate.`);
+ if (!check) for (const [path, source] of stale) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, source);
+ }
+ if (!check) for (const path of obsolete) rmSync(path);
+}
+
+if (resolve(process.argv[1] ?? '') === fileURLToPath(import.meta.url)) {
+ try { generateEmbedDocs({ check: process.argv.includes('--check'), capabilities: process.argv.includes('--capabilities') ? process.argv[process.argv.indexOf('--capabilities') + 1] : undefined }); }
+ catch (error) { console.error(error.message); process.exitCode = 1; }
+}
diff --git a/scripts/run-embed-examples.mjs b/scripts/run-embed-examples.mjs
new file mode 100644
index 0000000000..7f11b2b625
--- /dev/null
+++ b/scripts/run-embed-examples.mjs
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+import { spawnSync } from "node:child_process";
+import { readdirSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+export function discoverExamples(directory = resolve(root, "crates/openhuman-embed/examples")) {
+ return readdirSync(directory).filter((file) => file.endsWith(".rs")).sort().map((file) => {
+ const source = readFileSync(resolve(directory, file), "utf8");
+ const feature = source.match(/^\/\/! Feature: (.+)$/m)?.[1]?.trim();
+ if (!source.includes("//! Title:") || !source.includes("//! Run:") || !source.includes("// ANCHOR:")) {
+ throw new Error(`${file}: missing example metadata or documentation anchor`);
+ }
+ return { name: file.slice(0, -3), features: feature && feature !== "default" ? [feature] : [] };
+ });
+}
+export function offlineEnvironment(environment) {
+ return Object.fromEntries(Object.entries(environment).filter(([name]) =>
+ !name.startsWith("OPENHUMAN_EXAMPLE_") && !name.startsWith("OPENHUMAN_BACKEND_") &&
+ !name.startsWith("OPENHUMAN_KEYRING_") &&
+ name !== "OPENHUMAN_STORAGE_URL" && name !== "OPENHUMAN_WORKSPACE"));
+}
+export function assertExampleOutput(name, result) {
+ if (result.error) throw result.error;
+ if (result.status !== 0) throw new Error(`${name} exited ${result.status}\n${result.stdout}\n${result.stderr}`);
+ if (!result.stdout.split(/\r?\n/).includes(`EXAMPLE_OK ${name}`)) {
+ throw new Error(`${name}: successful exit without behavioral assertion marker\n${result.stdout}`);
+ }
+}
+export function runExamples({ run = spawnSync, examples = discoverExamples(), environment = process.env } = {}) {
+ // Keep the feature graph identical for every run so Cargo reuses one build.
+ const features = [...new Set(examples.flatMap((example) => example.features))].sort();
+ for (const example of examples) {
+ const args = ["run", "--quiet", "-p", "openhuman-embed", "--example", example.name];
+ if (features.length) args.push("--features", features.join(","));
+ const result = run(resolve(root, "scripts/ci-cancel-aware.sh"), ["cargo", ...args], {
+ cwd: root, encoding: "utf8", env: offlineEnvironment(environment), timeout: 1800000, maxBuffer: 16 * 1024 * 1024,
+ });
+ assertExampleOutput(example.name, result);
+ console.log(`PASS ${example.name}`);
+ }
+}
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ if (process.argv.includes("--list")) console.log(discoverExamples().map((example) => example.name).join("\n"));
+ else runExamples();
+}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 5db9caf3b2..a5ec4e49c4 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 5db9caf3b2224d8c49cdb29fe57196f9c3d34ca2
+Subproject commit a5ec4e49c428d3a9a4bc4c14952bd629427ba2be