Skip to content

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

Merge remote-tracking branch 'upstream/main' into medulla-12-scoped-hooks

Steven Enamakel0337817bd923
diff --cc crates/openhuman-embed/README.md
index 7e764f443d,7e6c1979f1..ac6b18a1a6
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@@ -1,832 -1,9 +1,84 @@@
- # 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.
+ 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.
+
+## Cancelling one turn
+
+Acquire `Turn::cancellation_handle()` before sending a turn. The handle is
+cloneable and `cancel().await` waits for the turn to stop and for tracked
+commands to be reaped. The agent remains available for later turns:
+
- ```rust,no_run
- # async fn demo(agent: &openhuman_embed::Agent) -> Result<(), Box<dyn std::error::Error>> {
- let mut turn = agent.turn("Run the job.");
- let cancel = turn.cancellation_handle();
- let running = tokio::spawn(turn.send());
- // When the host receives an abort request:
- cancel.cancel().await;
- assert!(matches!(running.await?, Err(openhuman_embed::CoreError::TurnCancelled { .. })));
- # Ok(())
- # }
- ```
++
+
+Cancellation is scoped to this turn, including while waiting for inference.
+Turns with a cancellation handle use owned interpreter subprocesses rather
+than the Node/Python pool, which has no acknowledged per-job abort API. This
+trades warm-worker reuse for awaited cleanup; ordinary turns retain pooling.
+The `meter` callback fires once on cancellation or a dropped send future,
+with `None` when dispatch has not supplied usage yet.
+
+Before send, cancellation prevents dispatch; after completion it is a no-op.
+On Unix, the built-in shell, Node, Python and npm commands kill their process
+group, including descendants. Other platforms stop the direct command. Host
+tools that spawn independent tasks or processes must provide their own cleanup;
+MCP server lifecycles remain owned by the agent. Keep polling `send()` while
- awaiting cancellation, for example in a spawned task as above.
-
- ## Using it
-
- 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,
- };
++awaiting cancellation, for example in a spawned task.
+
- # 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(())
- # }
- ```
++## Scoped worker hooks
+
+Hooks can be supplied at three levels: `RuntimeBuilder::tool_hook` /
+`post_turn_hook` for all agents, `AgentSpec::tool_hook` / `post_turn_hook`
+for one agent, and `Turn::tool_hook` / `post_turn_hook` for one dispatch.
- Tool callbacks run in that order; same-named scoped callbacks are additive.
++Tool callbacks run in that order. Named agent updates replace only that agent’s callback; per-turn callbacks are additional.
+`ToolHookContext` carries the agent/session identity when known, and `cwd`
+follows the execution workspace descriptor (including `Turn::cwd`), falling
+back to the embedding context's configured action root.
+The agent and turn hooks are never installed in the global registry, so
+concurrent workers and later turns do not pick up one another's callbacks.
+Post-turn callbacks run asynchronously with an owned session snapshot.
+Independently spawned tasks that build sessions must explicitly inherit
+`openhuman_core::agent::hooks::HookScope` to carry scoped hooks.
+
- `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`.
-
+Gateway attribution headers can be attached to `Route::header(name, value)`
+and used with `Turn::route`, or with `Provider::routed(route)` on an agent.
+They follow only that route's endpoint and are never saved to configuration,
+sent to background providers, or included as values in `Route`'s `Debug`.
+
- 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.
-
+### Inline permission and usage policy
+
+`AgentSpec::can_use_tool` and `Turn::can_use_tool` await a host callback before
+executing each tool. The callback can wait for an approval UI and return
+`ToolHookDecision::Proceed`, `Deny`, or `ProceedWith`. It owns that wait;
+returning `Ask` denies execution. These callbacks add to existing tool policies,
+and a turn callback cannot override an agent denial.
+
+`AgentSpec::stop_hook` and `Turn::stop_hook` receive cumulative usage after each
+completed model call. Return `StopDecision::Continue` to observe usage, or
+`Stop` to prevent subsequent calls. Completed tool rounds may still execute;
+this is an after-call budget boundary, so hosts must refuse an already exhausted
+budget before sending a turn. Provider-reported charges remain authoritative,
+including known zero; missing charges remain unknown unless pricing is known.
+A policy stop uses a deterministic partial summary rather than spending on
+final-answer repair calls.
+
+### Per-turn tools and subprocess environment
+
+`Turn::tools` replaces this turn's host tool belt, including attached sources.
+An empty belt revokes host tools; the next turn returns to the agent's belt.
+Builtin tools still follow the agent definition. This supplies dynamic tools for
+in-process hosts; statically declared MCP servers retain their creation-time
+configuration.
+
+`Turn::tool_env` supplies the base environment of owned builtin subprocesses.
+Variables absent from it are not inherited from the daemon. The builtin command
+builders retain their own security/runtime additions, including Git restrictions,
+managed interpreter paths and scratch directories. Scoped turns bypass Node and
+Python pools, which cannot acknowledge per-job cancellation or swap a job's
+process environment. A host tool that spawns a separate Tokio task must explicitly
+carry the command environment and cleanup scopes into that task.
diff --cc crates/openhuman-embed/src/agent/build.rs
index aa937daa4a,42e995d34b..4b7786e867
--- a/crates/openhuman-embed/src/agent/build.rs
+++ b/crates/openhuman-embed/src/agent/build.rs
@@@ -202,9 -261,25 +261,26 @@@ pub(crate) fn instantiate(runtime: &Run
Some(route.base_url.clone()),
Some(route.api_key.clone()),
)
+ .map(|scoped| scoped.with_headers(route.headers.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,
@@@ -250,8 -329,7 +330,8 @@@
access,
layout,
host_tools: parts.host_tools,
+ hooks: parts.hooks,
- lifecycle: super::lifecycle::Lifecycle::new(),
+ lifecycle,
host_only,
})
}
diff --cc crates/openhuman-embed/src/agent/spec.rs
index 86569485d5,bcf21b2c19..42352eb75d
--- a/crates/openhuman-embed/src/agent/spec.rs
+++ b/crates/openhuman-embed/src/agent/spec.rs
@@@ -273,47 -324,6 +326,31 @@@ impl AgentSpec
self
}
- /// Add a tool callback to every turn of this agent alone.
- ///
- /// Runtime callbacks run first, then agent callbacks, then callbacks added
- /// on the turn. Same-named callbacks are additive, never replaced globally.
- pub fn tool_hook(mut self, hook: std::sync::Arc<dyn crate::seams::ToolHook>) -> Self {
- self.hooks.push_tool(hook);
- self
- }
-
+ /// Await the host's permission decision before each tool executes.
+ /// The callback may wait for UI approval, then return `Proceed`, `Deny`,
+ /// or `ProceedWith`. Returning `Ask` denies the call; this callback itself
+ /// owns the approval wait. Static tool/security restrictions still apply.
+ /// Agent and turn callbacks are additive: a denial cannot be overridden.
+ pub fn can_use_tool<F>(self, callback: F) -> Self
+ where
+ F: for<'a> Fn(&'a crate::seams::ToolHookContext) -> crate::PermissionFuture<'a>
+ + Send
+ + Sync
+ + 'static,
+ {
+ self.tool_hook(std::sync::Arc::new(crate::permission::PermissionHook(
+ callback,
+ )))
+ }
+
+ /// Observe cumulative usage after each model call or vote to stop before
+ /// the next call. Return `StopDecision::Continue` for observation alone;
+ /// a budget policy can return `StopDecision::Stop`. Scoped to this agent; no runtime-global policy is replaced.
+ pub fn stop_hook(mut self, hook: std::sync::Arc<dyn crate::seams::StopHook>) -> Self {
+ self.hooks.push_stop(hook);
+ self
+ }
+
- /// Add a completed-turn callback to this agent alone. Runs asynchronously
- /// with an owned snapshot, after the runtime's callbacks.
- pub fn post_turn_hook(mut self, hook: std::sync::Arc<dyn crate::seams::PostTurnHook>) -> Self {
- self.hooks.push_post_turn(hook);
- self
- }
-
/// Arbitrary edits to the agent's config, applied last.
///
/// The escape hatch for the config fields the spec does not model — not
diff --cc crates/openhuman-embed/src/harness/provider.rs
index 283ca9ee32,21ba6f5b85..5f018dea05
--- a/crates/openhuman-embed/src/harness/provider.rs
+++ b/crates/openhuman-embed/src/harness/provider.rs
@@@ -35,14 -83,11 +83,16 @@@ impl Provider
/// Both halves are required: the core ignores a route with only one, and
/// taking them together here means a partial route cannot be expressed.
pub fn openai_compatible(base_url: impl Into<String>, api_key: impl Into<String>) -> Self {
+ Self::routed(Route::openai_compatible(base_url, api_key))
+ }
+
+ /// Use a route including its gateway attribution headers.
+ pub fn routed(route: Route) -> Self {
Self {
- route: Some(Route::openai_compatible(base_url, api_key)),
+ route: Some(route),
model: None,
+ custom: None,
+ roles: Default::default(),
}
}
diff --cc crates/openhuman-embed/src/process.rs
index f5c3733079,44120705b5..b1b99c6341
--- a/crates/openhuman-embed/src/process.rs
+++ b/crates/openhuman-embed/src/process.rs
@@@ -11,11 -11,9 +11,13 @@@ use std::path::{Path, PathBuf}
pub use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};
+/// Scoped ownership for host commands outside an agent turn. After dropping
+/// the scoped future, await `wait()` before acknowledging cancellation.
+pub use openhuman_core::tools::timeout::ProcessCleanup as CommandCleanup;
+
+ /// 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 --cc crates/openhuman-embed/src/turn.rs
index 3ef4cfdb1d,2806e804c8..fd3a2b5714
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@@ -271,11 -257,9 +271,13 @@@ 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,
- cancellation: Option<crate::TurnCancellation>,
++ cancel_handle: Option<crate::TurnCancellation>,
+ hooks: openhuman_core::agent::hooks::HookScope,
+ tools: Option<openhuman_core::agent::HostTools>,
+ tool_env: Option<openhuman_core::tools::timeout::CommandEnvironment>,
}
impl Turn {
@@@ -290,11 -274,9 +292,13 @@@
meter: None,
response_format: None,
max_tokens: None,
- untrusted_input: false,
+ top_p: None,
cancellation: None,
+ untrusted_input: false,
++ cancel_handle: None,
+ hooks: Default::default(),
+ tools: None,
+ tool_env: None,
}
}
@@@ -566,70 -499,69 +591,125 @@@
/// 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 hooks = std::mem::take(&mut self.hooks);
+ let environment = self.tool_env.take();
+ let fresh_tools = self.tools.is_some();
+ let dispatch = hooks.scope(Box::pin(self.send_with_cancellation()));
+ let dispatch = async move {
+ if fresh_tools {
+ openhuman_core::agent::tool_snapshot_scope::with_fresh_snapshot(dispatch).await
+ } else {
+ dispatch.await
+ }
+ };
+ match environment {
+ Some(environment) => environment.scope(dispatch).await,
+ None => dispatch.await,
+ }
+ }
+
+ async fn send_with_cancellation(mut self) -> Result<TurnOutcome, CoreError> {
+ let session_id = self
+ .session_id
- .take()
++ .clone()
+ .filter(|id| !id.trim().is_empty())
+ .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
++ self.session_id = Some(session_id.clone());
+ self.request.thread_id = Some(session_id.clone());
+ // Drop the meter before publishing cancellation's finished phase.
- let cancellation = self.cancellation.take();
++ let cancellation = self.cancel_handle.take();
+ let _guard = cancellation.as_ref().map(crate::TurnCancellation::enter);
+ let meter = crate::turn_meter::TurnMeter::new(self.meter.take());
+ let token = self.cancellation.take().unwrap_or_default();
- openhuman_core::agent::host_overrides::with_cancellation(token, self.send_observed()).await
+ let Some(cancellation) = cancellation else {
- return self.send_inner(&meter.usage).await;
++ return openhuman_core::agent::host_overrides::with_cancellation(
++ token,
++ self.send_observed(&meter.usage),
++ )
++ .await;
+ };
+ let outcome = cancellation
+ .cleanup()
- .scope(async {
++ .scope(openhuman_core::agent::host_overrides::with_cancellation(token.clone(), async {
+ tokio::select! {
+ biased;
+ _ = cancellation.cancelled() => {
++ token.cancel();
+ log::debug!("[embed][agent] turn_cancelled session={session_id} method={AGENT_CHAT}");
+ Err(CoreError::TurnCancelled { method: AGENT_CHAT })
+ }
- outcome = Box::pin(self.send_inner(&meter.usage)) => outcome,
++ outcome = Box::pin(self.send_observed(&meter.usage)) => outcome,
+ }
- })
++ }))
+ .await;
+ // The dispatch future is dropped before waiting for its command
+ // waiters. No new command can register after this point.
+ cancellation.cleanup().wait().await;
+ outcome
+ }
+
+ /// Obtain a cloneable handle that cancels only this turn and awaits its
+ /// subprocess cleanup. Acquire it before moving the turn to `send()`.
+ pub fn cancellation_handle(&mut self) -> crate::TurnCancellation {
- self.cancellation
++ self.cancel_handle
+ .get_or_insert_with(Default::default)
+ .clone()
}
- async fn send_observed(mut self) -> Result<TurnOutcome, CoreError> {
++ async fn send_observed(mut self, usage: &UsageSink) -> 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;
++ return self.send_inner(usage).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 mut dispatch = Box::pin(self.send_inner(usage));
+ 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
- // differently. Mint one here and hand it back.
+ async fn send_inner(mut self, usage: &UsageSink) -> Result<TurnOutcome, CoreError> {
let session_id = self
- .session_id
- .take()
- .filter(|id| !id.trim().is_empty())
- .unwrap_or_else(|| format!("embed-{}", uuid::Uuid::new_v4()));
- self.request.thread_id = Some(session_id.clone());
+ .request
+ .thread_id
+ .clone()
+ .expect("send assigned a session id");
log::debug!(
"[embed][agent] turn session={session_id} model={:?} routed={} cwd_set={}",
@@@ -679,9 -617,16 +760,17 @@@
},
),
untrusted_input: self.untrusted_input,
+ tools: self.tools.take(),
};
- 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,
++ usage,
+ options,
+ ));
let reply = match (self.origin, self.progress) {
(Some(origin), Some(sink)) => {
@@@ -764,13 -727,10 +862,16 @@@
let host_only = match &self.target {
TurnTarget::Agent(agent) => agent.host_only,
TurnTarget::Runtime(_) => {
+ if self.tools.is_some() {
+ return refuse(
+ "per-turn host tools need a runtime-owned Agent",
+ "turn_tools_unsupported",
+ );
+ }
- 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",
diff --cc docs/TEST-COVERAGE-MATRIX.md
index 4d88a495d7,e99a038c5a..82b8e25a71
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@@ -661,15 -661,20 +661,28 @@@ The thread JSONL store moved to `tinyag
| 16.1.10 | One runtime per process | RU+RI | `crates/openhuman-embed/src/runtime/builder_tests.rs`, `crates/openhuman-embed/tests/harness_embed.rs` | ✅ | A second `Runtime` (or `Harness`) returns `AlreadyRunning` rather than sharing process-global keyring/event-bus/subscribers; a failed build releases the slot so a retry is possible |
| 16.1.11 | Many agents on one runtime | RU+RI | `crates/openhuman-embed/src/agent/spec_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Three agents with different providers, access tiers, skills, MCP servers and action dirs; turns land on their own provider; per-agent MCP visibility; thread-scoped resume; duplicate/invalid ids and widening are refused |
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
+| 16.1.13 | Awaited per-turn cancellation | RI | `crates/openhuman-embed/tests/turn_cancellation.rs`, `crates/openhuman-embed/tests/process_cancellation.rs` | ✅ | Before send, during inference and during a builtin shell command; agent reuse, concurrent cancellation handles, failure/drop acknowledgement, bounded and unbounded descendant termination plus direct-child reaping on Linux |
+| 16.1.14 | Agent and turn hook isolation | RI | `crates/openhuman-embed/tests/scoped_hooks.rs` | ✅ | Additive same-named callbacks, overlapping worker turns, one-turn callback lifetime, resumed-session snapshots, core-scheduled turn callbacks and reuse of a removed agent id without registry leakage |
+| 16.1.15 | Agent-turn route attribution headers | RU+RI | `crates/openhuman-embed/tests/route_headers.rs`, `crates/openhuman-embed/src/turn_tests.rs` | ✅ | Per-route headers reach only the named endpoint and turn, remain absent on other agents and backend requests, and are redacted in Debug; wire fields pinned against the registered controller schema |
+| 16.1.16 | Tool-hook turn identity and cwd | RI | `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Before and after hooks report the worker/session and working root used by builtin shell; a later turn returns to its agent default |
+| 16.1.17 | Inline agent/turn permission callback | RI | `crates/openhuman-embed/tests/inline_permissions.rs` | ✅ | UI decisions precede execution; denials narrow authority, concurrent agents remain independent, cancellation closes a pending receiver and a closed UI refuses execution |
+| 16.1.18 | Per-turn host-tool replacement | RI | `crates/openhuman-embed/tests/turn_tools.rs` | ✅ | Replacement and empty-belt revocation apply to resumed HostOnly and mixed definitions, without restoring historical declarations or affecting other agents and later turns |
+| 16.1.19 | Scoped usage observation and budget stop | RI | `crates/openhuman-embed/tests/usage_hooks.rs` | ✅ | Cumulative charged cost and tokens, known-zero versus unpriced calls, per-agent policy and per-turn observer isolation; no summary-repair model calls after a stop |
+| 16.1.20 | Scoped builtin command environments | RI | `crates/openhuman-embed/tests/tool_environment.rs`, `crates/openhuman-embed/tests/tool_hook_context.rs` | ✅ | Overlapping subprocess maps exclude host inheritance on Unix; a real shell receives its turn's variables while excluding host HOME and preserving command-owned runtime/security additions |
+ ### 16.2 Dynamic runtime and agent configuration
+
+ | ID | Feature | Layer | Test path(s) | Status | Notes |
+ | --- | --- | --- | --- | --- | --- |
+ | 16.2.1 | Defaults, templates and typed configuration | RU+RI | `crates/openhuman-embed/src/runtime/defaults_tests.rs`, `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-embed/src/agent/definition_tests.rs`, `crates/openhuman-embed/tests/runtime_configuration.rs` | ✅ | Config, runtime, template, agent and turn overrides preserve unspecified fields; invalid sampling, unknown templates and capability widening are rejected. |
+ | 16.2.2 | Versioned capabilities and runtime weight | RU | `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-rpc/src/host_tests.rs`, `crates/openhuman-embed/examples/capability_report.rs` | ✅ | Reports compiled gates, selected domains/services/modules and effective limits; credentials, endpoints and prompts stay out of JSON. Unavailable modules identify their required feature. |
+ | 16.2.3 | Configured storage and driver feature gates | RU+RI | `crates/openhuman-embed/src/runtime/info_tests.rs`, `crates/openhuman-embed/tests/runtime_configuration.rs`, `crates/openhuman-embed/examples/storage.rs` | ✅ | Configured memory/SQLite storage is installed before boot and supplies session stores; MongoDB requires its Cargo feature and operator configuration. Automated recipes use local storage without contacting MongoDB. |
+ | 16.2.4 | Native providers, role pins and ordered fallback | RU+RI | `crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/examples/custom_provider.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/fallback_tests.rs` | ✅ | Agent-local native providers receive effective sampling parameters; `crates/openhuman-core/src/inference/host_runtime/ops/agent_chat_tests.rs` pins explicit turn temperature over the stored definition. Explicit role pins override config routing. Generic fallback preserves deferred polling and never switches after visible content. |
+ | 16.2.5 | Live hooks and isolated session stores | RU+RI | `crates/openhuman-core/src/agent/host_overrides_tests.rs`, `crates/openhuman-embed/src/runtime/seams_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/examples/runtime_events.rs` | ✅ | Runtime hooks compose with local hooks, can be replaced or removed between turns, and restore prior registrations on drop; agent-local session stores do not leak transcripts. |
+ | 16.2.6 | Runtime events and approval callbacks | RU+RI | `crates/openhuman-embed/src/events_tests.rs`, `crates/openhuman-embed/src/turn_tests.rs`, `crates/openhuman-embed/tests/runtime_observation.rs`, `crates/openhuman-embed/tests/approval_lifecycle.rs`, `crates/openhuman-embed/examples/approvals.rs` | ✅ | Ordered, bounded, content-free events identify agents and individual calls, retain approval origins, and report lag. Callback approve/deny and subscription-drop cancellation exercise real shell markers. Removed-agent handles are invalidated and IDs stay reserved until teardown completes, including cancelled removals. |
+ | 16.2.7 | Streaming and cancellation under backpressure | RU+RI | `crates/openhuman-embed/tests/stream_cancellation.rs`, `crates/openhuman-embed/examples/streaming.rs` | ✅ | Progress precedes the final result; dropping the stream or cancelling its supplied token releases native model work even with an unread bounded receiver. |
+ | 16.2.8 | Executable recipes and generated documentation | scripts+RI | `scripts/__tests__/run-embed-examples.test.mjs`, `scripts/__tests__/generate-embed-docs.test.mjs`, `scripts/run-embed-examples.mjs` | ✅ | Every recipe runs with loopback fixtures and an explicit output contract. Snippets, cookbook metadata, builder signatures and capability output regenerate from source; drift, hidden rustdoc lines and broken links fail checks. |
+
## Summary
| Status | Count |
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 07b443dda5,5caeba4b71..45d30d0c0d
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -160,8 -160,8 +160,7 @@@ for (const [directory, table] of
["examples", "example"],
]) {
const files = new Set(
-- fs
-- .readdirSync(directory)
++ (fs.existsSync(directory) ? fs.readdirSync(directory) : [])
.filter((name) => name.endsWith(".rs"))
.map((name) => name.slice(0, -3)),
);