The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge upstream/main into oh-embed-cron-resolver
Steven Enamakel67685f9a7513
diff --cc crates/openhuman-app/Cargo.lockindex 79cd13a00f,27ee3deead..95803533d2--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@@ -4655,9 -4577,9 +4577,10 @@@ version = "0.64.15dependencies = ["anyhow","async-trait",+ "chrono","log","openhuman",+ "sentry","serde","serde_json","tempfile",diff --cc crates/openhuman-core/src/cron/store.rsindex cce2ad3f51,8956f165f3..31310a4978--- a/crates/openhuman-core/src/cron/store.rs+++ b/crates/openhuman-core/src/cron/store.rs@@@ -115,21 -193,23 +193,34 @@@ pub fn get_job(config: &Config, job_id}pub fn remove_job(config: &Config, id: &str) -> Result<()> {+ if let Some(docs) = documents(config)? {+ let owned = id.to_string();+ run(async move { docs.remove_job(&owned).await })?;++ if let Err(error) = super::policy::clear_policy(config, id) {++ tracing::warn!(job_id = id, %error, "[cron:store] removing job policy failed");++ }+ println!("✅ Removed cron job {id}");+ return Ok(());+ }upstream::remove_job(&opts(config), id)?;+ if let Err(error) = super::policy::clear_policy(config, id) {+ tracing::warn!(job_id = id, %error, "[cron:store] removing job policy failed");+ }println!("✅ Removed cron job {id}");Ok(())}/// Deletes every cron job in the workspace (E2E `openhuman.test_reset`).pub fn clear_all_jobs(config: &Config) -> Result<usize> {- let removed = upstream::clear_all_jobs(&opts(config))?;- if let Some(docs) = documents(config)? {- return run(async move { docs.clear_all_jobs().await });++ let removed = if let Some(docs) = documents(config)? {++ run(async move { docs.clear_all_jobs().await })?++ } else {++ upstream::clear_all_jobs(&opts(config))?++ };+ if let Err(error) = super::policy::clear_all_policies(config) {+ tracing::warn!(%error, "[cron:store] clearing job policies failed");}- upstream::clear_all_jobs(&opts(config))+ Ok(removed)}/// Removes duplicate jobs sharing a `name`, keeping the one with most history.diff --cc crates/openhuman-embed/README.mdindex 1d2f6d65f5,e5566d8c6b..f2f58f5756--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@@ -263,161 -351,244 +351,307 @@@ let runtime = Runtime::builder(.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 and one agent can never reach another's conversation. A- reopened agent resumes its thread from the store, in any process.- `InMemorySessionStores` keeps everything in memory; the conformance suites in- `session_store` are what a host's provider is held to.- `Workspace::stateless()` refuses to build without a store, and a private- scratch directory, removed with the runtime, still holds process-local- caches (cost log, prompt templates, migration markers). The desktop app, CLI- and TUI install `openhuman_rpc::session_store`, the classic on-disk layout behind- the same port. See `tests/session_store.rs`.-+ 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.+++<<<<<<< HEAD+### 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`.++### Still runtime-wide++=======+ ## Tools on an agent++>>>>>>> upstream/main++ `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/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 modules 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, and two agents on one runtime. |+ | [`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.++ ## 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(())+ # }+ ```- These are read from the runtime's boot config by every agent today. They- are documented rather than hidden; each is a candidate follow-up in the core.+ 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.- - `autonomy.auto_approve` / `auto_approve_all` and the memory guard's- autonomy tier come from the runtime's boot config (`security::live_policy`),- not the agent's. Path and command policy _do_ use the agent's own tier.- - The approval gate is on or off process-wide; parked approvals are not- labelled with the agent id. A per-agent "no approvals" is `Access::full()`,- whose `TrustedAutomation` origin the gate honours per turn.- - The sub-agent catalogue is runtime-wide (built-ins plus- `<workspace>/agents/*.toml`). Embedded agents cannot be `delegate_*`- targets of one another. Do not reuse built-in ids (`orchestrator`,- `summarizer`, …) for your agents.- - Sub-agents an agent spawns and the experience store re-read the runtime's- on-disk config rather than the agent's overlay. (The turn journal goes to- the agent's own stores under a host session store; without one it uses the- process-default workspace.)- - Sub-agent run-ledger rows, cron jobs and the cost log stay in the- workspace even with a host session store.- - Agents sharing a workspace share the dynamic (`mcp_registry_*`) MCP- registry; `[[mcp_client.servers]]` declared through `AgentSpec::mcp` are- per agent. The host-seeded documentation server is visible to every agent.- - `install_skill` / `create_skill` still write to `~/.openhuman`. With- `include_user_skills(false)` (the default) an agent does not _discover_ the- operator's skills, but an install by the agent lands there.- - One API key (or session) is shared by all agents.- - `IntegrationClient` (backend-proxied Composio/search/media tools) accepts- the runtime's TinyHumans API key or an app-session JWT through- `security::credentials::session_support::resolve_backend_credential`.- API keys use `x-api-key`; session JWTs use `Authorization: Bearer`.- With the backend transport installed and the integration feature and runtime- gates enabled, an API-key-only runtime can register integration tools.-- Other invariants worth knowing before wiring any entry point:+ `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.- - 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` set both for `Workspace::Ephemeral` and `Workspace::Dir`.- - A turn runs under the access tier _and_ the turn origin. `Access::full()`- sets both (`AutonomyLevel::Full` plus a `TrustedAutomation` origin);- `Access::readonly()` and `Access::supervised()` set no origin and leave the- approval gate on.- - Supply skills through `AgentSpec::skills_dir` / `HarnessBuilder::skills_dir`,- which copy the bundles. Skill discovery rejects symlinked bundles, so- linking them in does not work.+ ## Locked-down agents: `HostOnly`- ## Feature flags+ 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.- Every feature on this crate 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`, `contacts`, `media`, `flows`, `skills`, `mcp`,- `crash-reporting`, `channels`,- `sandbox-bubblewrap`, `browser-native`, `whatsapp-web`,- `file-logging`, `scheduler-gate`.+ ```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()));+ ```- Two of them also gate items on this crate's own public surface:+ - 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`).- - `mcp`: `HttpHeader`, `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and- `HarnessBuilder::mcp`.- - `skills`: `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.+ ## Feature flags- See [`docs/library-minimal-recipe.md`](../../docs/library-minimal-recipe.md)- for a measured minimal-footprint feature set, and- [`gitbooks/developing/performance.md`](../../gitbooks/developing/performance.md)- for the resulting binary sizes and per-agent memory numbers.+ 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.- ## Examples and tests+ Two features also gate this crate's own surface. `mcp` adds `HttpHeader`,+ `McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`.+ `skills` adds `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.- ```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?"+ [`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++ - 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`.- # 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."+ ```bash+ cargo test -p openhuman-embed --features inference,mcp,skills+ cargo test -p openhuman-embed --features inference,mcp,skills --test runtime_agents```- Optional: `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`](../../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`.- Two agents on one runtime, either BYOK with the same variables as above, or- managed inference with `OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY`:+ ## Further reading++<<<<<<< HEAD+```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."++# Or managed inference, no BYOK endpoint needed:+OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_… \+ cargo run -p openhuman-embed --example two_agents -- "Describe this directory."+```++The repository-root `examples/embed_headless.rs` (`DomainSet::harness()`,+`ServiceSet::none()`, RPC through `CoreRuntime::invoke`) and+`examples/embed_kernel.rs` (`DomainSet::kernel()`, then opt one family back+in) drive `CoreBuilder` from `openhuman_core` directly, without this crate;+they are `[[example]]` entries of the `openhuman` package, so run them with+`cargo run --example embed_headless`.++`tests/harness_embed.rs` is the end-to-end proof that `Harness` runs a real+turn against a `wiremock` provider with nothing bound;+`tests/runtime_agents.rs` runs three agents with different providers, access+tiers, skills, MCP servers and working directories on one runtime and shows+the API key reaching a mocked managed backend as a bearer;+`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;+`tests/public_api.rs` pins the host-facing embedding contract at compile+time. Run them with `cargo test -p openhuman-embed --features inference,mcp,skills`.++## 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.++=======+ - [`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.++>>>>>>> upstream/maindiff --cc crates/openhuman-embed/src/lib.rsindex c01e854783,f0f4b68e2e..b5454a46c3--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@@ -85,15 -85,32 +85,33 @@@ pub mod agent_progress};}+ /// The skill registry: the host transport an embedder passes to+ /// `tinyskills::SkillRegistry::builder`, and the process registry the core+ /// itself serves catalog RPC and tools from.+ #[cfg(feature = "skills")]+ pub mod skill_registry {+ pub use openhuman_core::skills::catalog::{+ skill_registry, ReqwestTransport, HERMES_REGISTRY_ID,+ };+ }+mod agent;+ pub mod artifacts;mod auth;mod call;- mod config;+ pub mod chat_surface;+ pub mod complete;+ pub mod config;mod core_agent;+pub mod cron;+ pub mod embeddings;mod error;mod harness;+ pub mod identity;pub mod memory;+ #[cfg(feature = "modules")]+ pub mod modules;+ pub mod process;mod runtime;mod turn;diff --cc crates/openhuman-embed/src/runtime/build.rsindex 0000000000,b15bd509e3..fc232a866emode 000000,100644..100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@@ -1,0 -1,395 +1,400 @@@+ //! [`RuntimeBuilder::build`]: the boot sequence.++ use std::path::Path;+ use std::sync::Arc;++ use openhuman_core::agent::session_store::SessionStoreProvider;+ use openhuman_core::config::Config;+ use openhuman_core::core::runtime::CoreBuilder;+ use openhuman_core::core::types::HostKind;+-use super::builder::ConfigSource;++use super::builder::{requests_background_services, ConfigSource};+ use super::presets::{default_domains, default_services};+ use super::{ApiKey, Runtime, RuntimeBuilder, RuntimeError, RUNTIME_LIVE};+ use crate::harness::workspace::ResolvedWorkspace;+ use crate::harness::{Provider, Workspace};+ use crate::Core;++ struct SessionStoreCleanup {+ installed: Option<Arc<dyn SessionStoreProvider>>,+ previous: Option<Arc<dyn SessionStoreProvider>>,+ }++ impl Drop for SessionStoreCleanup {+ fn drop(&mut self) {+ let Some(installed) = self.installed.take() else {+ return;+ };+ if openhuman_core::agent::session_store::clear_if(&installed) {+ openhuman_core::agent::session_store::restore(self.previous.take());+ }+ }+ }++ /// Releases [`RUNTIME_LIVE`] unless disarmed: held across+ /// [`RuntimeBuilder::build`]'s boot so a failed or cancelled build never+ /// leaves the process slot claimed.+ struct SlotClaim {+ armed: bool,+ }++ impl Drop for SlotClaim {+ fn drop(&mut self) {+ if self.armed {+ RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);+ log::debug!("[embed][runtime] build did not complete; process slot released");+ }+ }+ }++ impl RuntimeBuilder {+ /// Build the core and return a runtime ready to host agents.+ ///+ /// # Errors+ ///+ /// [`RuntimeError::AlreadyRunning`] if this process already has one;+ /// [`RuntimeError::BlankApiKey`] for an empty key;+ /// [`RuntimeError::Invalid`] for a knob the [`ConfigSource`] cannot+ /// honour or a refused controller extension.+ pub async fn build(self) -> Result<Runtime, RuntimeError> {+ // Claim the process slot before doing any work, so a losing racer+ // neither creates a temp dir nor half-initializes global state.+ if RUNTIME_LIVE.swap(true, std::sync::atomic::Ordering::AcqRel) {+ return Err(RuntimeError::AlreadyRunning);+ }+ // From here on every early return must release the slot, or a failed+ // build would permanently poison the process against retrying. The+ // claim is a drop guard rather than a match on the result so that a+ // *cancelled* build (the future dropped mid-boot, as the desktop+ // shell's startup timeout does to its server task) releases it too.+ let mut claim = SlotClaim { armed: true };+ let result = self.build_inner().await;+ if result.is_ok() {+ // The runtime's `CoreGuard` owns the slot from here.+ claim.armed = false;+ }+ result+ }++ /// Refuse combinations the chosen [`ConfigSource`] cannot honour.+ pub(super) fn validate(&self) -> Result<(), RuntimeError> {+ 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() {+ return Err(RuntimeError::NoSessionStore);+ }+ if self.config_source == ConfigSource::Discovered {+ if !matches!(self.workspace, Workspace::Inherit) {+ return Err(RuntimeError::Invalid(+ "ConfigSource::Discovered needs Workspace::Inherit: the core discovers \+ the operator's install"+ .into(),+ ));+ }+ let edits = [+ ("config", self.config.is_some()),+ ("backend_url", self.backend_url.is_some()),+ ("workspace_dir", self.workspace_dir.is_some()),+ ("action_dir", self.action_dir.is_some()),+ ("api_key", self.api_key.is_some()),+ ];+ if let Some((knob, _)) = edits.iter().find(|(_, set)| *set) {+ return Err(RuntimeError::Invalid(format!(+ "`{knob}` edits the boot config, which ConfigSource::Discovered leaves \+ to the core; use ConfigSource::Resolved"+ )));+ }+ }+ Ok(())+ }++ async fn build_inner(mut self) -> Result<Runtime, RuntimeError> {+ self.validate()?;+ let discovered = self.config_source == ConfigSource::Discovered;+ let inherit = self.workspace.is_operator_owned();+ let resolved = ResolvedWorkspace::resolve(&self.workspace, self.action_dir.as_deref())+ .map_err(map_ws)?;++ // Discovered: the core loads its own config during boot; nothing to+ // assemble here. Resolved: `Inherit` starts from the operator's own+ // config — loaded here rather than left to the core to discover,+ // because the other knobs are applied *on top* of it.+ let mut config = if discovered {+ None+ } else {+ Some(self.resolve_config(&resolved).await?)+ };++ // The seams are the last fallible step before side effects a failed+ // 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 seams = std::mem::take(&mut self.seams)+ .install()+ .map_err(RuntimeError::Invalid)?;++ // Before `CoreBuilder::build()`: the scheduler gate reads the credential+ // store exactly once, at boot, to decide whether it is signed in.+ let has_api_key = match (self.api_key.as_ref(), config.as_ref()) {+ (Some(key), Some(config)) => {+ store_api_key(config, key)?;+ true+ }+ _ => false,+ };++ // An endpoint without a model is deliberately ignored by the route+ // applicator, so host policy follows the effective behaviour: only a+ // *usable* runtime-default route exempts an inherited install from+ // its session gate. An API key is a credential in its own right.+ let routed_provider_effective = routed_provider_effective(&self.provider, config.as_ref());+ let host_kind = effective_host_kind(+ self.host_kind,+ inherit,+ routed_provider_effective || has_api_key,+ );++ let domains = self.domains.unwrap_or_else(default_domains);+ let tool_groups = self.tool_groups.clone().unwrap_or_default();+ let services = self.services.unwrap_or_else(default_services);++ if let Some(engine) = self.memory_engine.clone() {+ openhuman_core::memory::engine::install_host_engine(engine);+ }++ // Install only after all fallible workspace/config resolution has+ // completed; core boot performs recovery against this provider.+ let installed_session_store = self.session_store.clone();+ let previous_session_store = installed_session_store+ .clone()+ .and_then(openhuman_core::agent::session_store::install);+ let mut session_store_cleanup = SessionStoreCleanup {+ installed: installed_session_store,+ previous: previous_session_store,+ };++ log::debug!(+ "[embed][runtime] building host_kind={host_kind:?} config_source={:?} \+ inherit_workspace={inherit} routed_provider={} api_key={has_api_key} \+ domains={domains:?} services={services:?} tool_groups={tool_groups:?} \+ listen_host={:?} listen_port={:?}",+ self.config_source,+ self.provider.is_routed(),+ self.listen_host,+ self.listen_port,+ );++ let mut builder = CoreBuilder::new(host_kind)+ .domains(domains)+ .tool_groups(tool_groups.clone())+ .services(services)+ .token(std::mem::replace(+ &mut self.token,+ openhuman_core::core::runtime::TokenSource::EnvOrFile,+ ));+ if let Some(config) = config.clone() {+ builder = builder.config(config);+ }+ if let Some(host) = self.listen_host.take() {+ builder = builder.host(host);+ }+ if let Some(port) = self.listen_port {+ builder = builder.port(port);+ }+ if let Some(transport) = self.backend_transport.take() {+ builder = builder.backend_transport(transport);+ }+ let runtime = builder.build().await.map_err(|error| {+ log::warn!("[embed][runtime] core build failed: {error:#}");+ RuntimeError::Build(error)+ })?;+ let core = Core::from_runtime(Arc::new(runtime));++ // Discovered: agents start from the config the core just loaded.+ let (mut base_config, config_unavailable) = match config.take() {+ Some(config) => (config, None),+ None => discovered_base_config().await,+ };+ if discovered {+ // Agent defaults only — the core's own config is not edited.+ self.access.apply(&mut base_config);+ apply_provider(&mut base_config, &self.provider);+ }++ if seams.has_pending_live_policy() {+ if config_unavailable.is_some() {+ // The base config is a placeholder: its directories are the+ // default root, not the operator's install, so a policy+ // scoped to them would guard the wrong tree. Keep the policy+ // the core's bootstrap installed.+ log::warn!(+ "[embed][runtime] live policy not installed: discovered config unavailable"+ );+ } else {+ seams.install_live_policy(&base_config.workspace_dir, &base_config.action_dir);+ }+ }++ if let Some(session) = self.session.take() {+ core.auth().store(session).await?;+ }++ let installed_session_store = session_store_cleanup.installed.take();+ let previous_session_store = session_store_cleanup.previous.take();+ log::debug!("[embed][runtime] built host_kind={host_kind:?}");+- Ok(Runtime::new(++ let runtime = Runtime::new(+ core,+ resolved,+ installed_session_store,+ previous_session_store,+ Some(seams),+ base_config,+ config_unavailable,+ inherit,+ domains,+ tool_groups,+ self.provider,+ self.access,- ))++ );++ if requests_background_services(services) {++ log::debug!("[embed][runtime] starting background services {services:?}");++ runtime.start_services().await;++ }++ Ok(runtime)+ }++ /// The config a [`ConfigSource::Resolved`] runtime hands the core.+ async fn resolve_config(+ &mut self,+ resolved: &ResolvedWorkspace,+ ) -> Result<Config, RuntimeError> {+ let mut config = match (&self.workspace, self.config.take()) {+ (Workspace::Inherit, Some(config)) => config,+ (Workspace::Inherit, None) => {+ Config::load_or_init().await.map_err(RuntimeError::Build)?+ }+ (_, supplied) => {+ let mut config = supplied.unwrap_or_default();+ config.workspace_dir = resolved.workspace_dir.clone();+ config.action_dir = resolved.action_dir.clone();+ // Credential state, auth profiles and the keyring file backend+ // all resolve against this path's parent, not `workspace_dir`.+ config.config_path = resolved.config_path.clone();+ config+ }+ };+ // Raw paths refine the resolved workspace field by field; the+ // credential root (`config_path`) is left to the `Workspace`.+ if let Some(dir) = self.workspace_dir.clone() {+ create_dir(&dir, "create the workspace_dir")?;+ log::debug!("[embed][runtime] workspace_dir override applied");+ config.workspace_dir = dir;+ }+ if let Some(dir) = self.action_dir.clone() {+ create_dir(&dir, "create the action_dir")?;+ log::debug!("[embed][runtime] action_dir override applied");+ config.action_dir = dir;+ }+ if let Some(url) = self.backend_url.clone() {+ config.api_url = Some(url);+ }+ self.access.apply(&mut config);+ apply_provider(&mut config, &self.provider);+ Ok(config)+ }+ }++ /// The base config for agents of a runtime whose core discovered its own:+ /// the same `load_or_init` the core just ran, so the two agree.+ ///+ /// When it fails the core has already booted without its workspace-bound+ /// stores. The runtime still comes up (a host that never creates an agent,+ /// like the desktop shell, keeps working), but the failure is returned with+ /// the placeholder config so [`Runtime::agent`] refuses instead of laying an+ /// agent out under the default root, a different workspace and credential+ /// store from the one the operator selected.+ async fn discovered_base_config() -> (Config, Option<String>) {+ match Config::load_or_init().await {+ Ok(config) => (config, None),+ Err(error) => {+ log::warn!(+ "[embed][runtime] discovered config failed to load; agents will be refused: {error:#}"+ );+ (Config::default(), Some(format!("{error:#}")))+ }+ }+ }++ /// Whether the runtime-default provider route would actually take effect. An+ /// endpoint without a model is deliberately ignored by the route applicator,+ /// so host policy follows the effective behaviour: only a usable route with a+ /// model exempts an inherited install from its session gate. A+ /// [`ConfigSource::Discovered`] build has no config yet (`None`), but the+ /// 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())+ }++ fn store_api_key(config: &Config, key: &ApiKey) -> Result<(), RuntimeError> {+ let state_dir = config+ .config_path+ .parent()+ .map(Path::to_path_buf)+ .unwrap_or_else(|| config.config_path.clone());+ openhuman_core::security::credentials::api_key::store_api_key_in(+ &state_dir,+ config.secrets.encrypt,+ key.expose(),+ )+ .map(|_| ())+ .map_err(RuntimeError::Build)+ }++ fn create_dir(dir: &Path, what: &'static str) -> Result<(), RuntimeError> {+ std::fs::create_dir_all(dir).map_err(|source| RuntimeError::Workspace { what, source })+ }++ fn map_ws(err: crate::HarnessError) -> RuntimeError {+ match err {+ crate::HarnessError::Workspace { what, source } => RuntimeError::Workspace { what, source },+ crate::HarnessError::Invalid(msg) => RuntimeError::Invalid(msg),+ crate::HarnessError::Build(e) => RuntimeError::Build(e),+ crate::HarnessError::Call(e) => RuntimeError::Call(e),+ crate::HarnessError::AlreadyRunning => RuntimeError::AlreadyRunning,+ }+ }++ /// Preserve the installed application's authentication policy when the+ /// runtime borrows both its workspace and provider. `Library` means the host+ /// supplied inference (a route or an API key); it must not become a blanket+ /// way to bypass the session gate around an operator-installed provider.+ pub(crate) fn effective_host_kind(+ requested: HostKind,+ inherit_workspace: bool,+ host_supplied_credential: bool,+ ) -> HostKind {+ if requested == HostKind::Library && inherit_workspace && !host_supplied_credential {+ HostKind::Cli+ } else {+ requested+ }+ }++ /// Apply a [`Provider`]'s model to the config.+ ///+ /// Only the model: the *route* is a per-turn parameter, never a config write,+ /// because config routes persist. See the [`provider`](crate::harness::provider)+ /// module docs.+ pub(crate) fn apply_provider(config: &mut Config, provider: &Provider) {+ if let Some(model) = provider.model_id() {+ config.default_model = Some(model.to_string());+ }+ }diff --cc crates/openhuman-embed/src/runtime/builder.rsindex 44e831a17d,e8d2c34d86..3340987b74--- a/crates/openhuman-embed/src/runtime/builder.rs+++ b/crates/openhuman-embed/src/runtime/builder.rs@@@ -13,45 -21,71 +21,81 @@@ use openhuman_core::core::runtime::{Domuse openhuman_core::core::types::HostKind;use openhuman_core::tools::toolpacks::ToolGroups;- use openhuman_core::agent::session_store::SessionStoreProvider;-- use super::{ApiKey, Runtime, RuntimeError, RUNTIME_LIVE};- use crate::harness::workspace::ResolvedWorkspace;+ use super::seams::HostSeams;+ use super::ApiKey;use crate::harness::{Access, Provider, Workspace};- use crate::{Core, Session};+ use crate::Session;++ // Re-exported for the sibling test module and older call sites that reached+ // the default triples through this module.+ pub(crate) use super::build::apply_provider;+- struct SessionStoreCleanup {- installed: Option<Arc<dyn SessionStoreProvider>>,- previous: Option<Arc<dyn SessionStoreProvider>>,++/// Whether `services` asks for any background work beyond the one-shot++/// harness init, which a library runtime has never started on its own.++pub(crate) fn requests_background_services(services: ServiceSet) -> bool {++ ServiceSet {++ harness_init: false,++ ..services++ } != ServiceSet::none()+}+- impl Drop for SessionStoreCleanup {- fn drop(&mut self) {- let Some(installed) = self.installed.take() else {- return;- };- if openhuman_core::agent::session_store::clear_if(&installed) {- openhuman_core::agent::session_store::restore(self.previous.take());- }- }+ #[cfg(test)]+ pub(crate) use super::build::{effective_host_kind, routed_provider_effective};+ #[cfg(test)]+ pub(crate) use super::presets::{default_domains, default_services};+ #[cfg(test)]+ pub(crate) use super::{RuntimeError, RUNTIME_LIVE};++ /// Who produces the [`Config`] the core boots with.+ ///+ /// The choice is not cosmetic. A config the core is *handed* makes it a+ /// scoped embedder: credentials live under that config's root, the operator's+ /// `active_user.toml` is never read or written, and handlers see that exact+ /// config for the life of the process. A config the core *discovers* is the+ /// operator's install, re-read from `config.toml` and the environment, with+ /// per-user activation — what the desktop app, the CLI and the TUI run.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+ pub enum ConfigSource {+ /// The builder resolves the config — from the [`Workspace`], a supplied+ /// [`RuntimeBuilder::config`], and the other knobs — and hands it to the+ /// core verbatim. The library default.+ #[default]+ Resolved,+ /// The core discovers its config itself, exactly as a desktop, CLI or TUI+ /// host does. Requires [`Workspace::Inherit`]; refuses the knobs that+ /// 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).+ Discovered,}- /// Builder for a [`Runtime`]. Obtain with [`Runtime::builder`].+ /// Builder for a [`Runtime`](super::Runtime). Obtain with+ /// [`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 {- workspace: Workspace,- provider: Provider,- access: Access,- services: Option<ServiceSet>,- domains: Option<DomainSet>,- tool_groups: Option<ToolGroups>,- host_kind: HostKind,- config: Option<Config>,- session: Option<Session>,- backend_url: Option<String>,- api_key: Option<ApiKey>,- backend_transport: Option<Arc<dyn BackendTransport>>,- memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,- session_store: Option<Arc<dyn SessionStoreProvider>>,+ pub(super) workspace: Workspace,+ pub(super) workspace_dir: Option<PathBuf>,+ pub(super) action_dir: Option<PathBuf>,+ pub(super) config_source: ConfigSource,+ pub(super) provider: Provider,+ pub(super) access: Access,+ pub(super) services: Option<ServiceSet>,+ pub(super) domains: Option<DomainSet>,+ pub(super) tool_groups: Option<ToolGroups>,+ pub(super) host_kind: HostKind,+ pub(super) token: TokenSource,+ pub(super) listen_host: Option<String>,+ pub(super) listen_port: Option<u16>,+ pub(super) config: Option<Config>,+ pub(super) session: Option<Session>,+ pub(super) backend_url: Option<String>,+ pub(super) api_key: Option<ApiKey>,+ pub(super) backend_transport: Option<Arc<dyn BackendTransport>>,+ pub(super) memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,+ pub(super) session_store: Option<Arc<dyn SessionStoreProvider>>,+ pub(super) seams: HostSeams,}impl Default for RuntimeBuilder {@@@ -169,15 -250,14 +260,18 @@@ impl RuntimeBuilder/// Override which background services run.///- /// The default is deliberately minimal (only the harness init step):- /// cron, the login-gated services and the memory queue each write to the workspace on- /// their own schedule, turning a library call into a background process- /// the caller did not ask for.+ /// The library default is deliberately minimal (only the harness init+ /// step): cron, the login-gated services and the memory queue each write+ /// to the workspace on their own schedule, turning a library call into a+ /// 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- /// The runtime itself starts none of them: a transport that serves the- /// runtime (`openhuman-rpc`) calls `start_services` once its listener is- /// bound.++ /// A set that selects anything beyond `harness_init` (`cron: true` to let++ /// [`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`].++ /// [`Runtime::start_services`] / [`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.pub fn services(mut self, services: ServiceSet) -> Self {self.services = Some(services);selfdiff --cc crates/openhuman-embed/src/runtime/builder_tests.rsindex e5b07ee5f3,2bcb44d91c..7ca6b78de9--- a/crates/openhuman-embed/src/runtime/builder_tests.rs+++ b/crates/openhuman-embed/src/runtime/builder_tests.rs@@@ -66,16 -90,97 +90,111 @@@ async fn a_blank_api_key_is_refused_befassert!(!RUNTIME_LIVE.load(std::sync::atomic::Ordering::Acquire));}+#[test]+fn only_services_beyond_harness_init_start_background_work() {+ assert!(!requests_background_services(default_services()));+ assert!(!requests_background_services(ServiceSet::none()));+ assert!(requests_background_services(ServiceSet {+ cron: true,+ ..default_services()+ }));+ assert!(requests_background_services(ServiceSet {+ channels: true,+ ..ServiceSet::none()+ }));+}+++ #[test]+ fn token_defaults_to_env_or_file_and_is_overridable() {+ assert!(matches!(+ RuntimeBuilder::new().token,+ TokenSource::EnvOrFile+ ));+ let fixed = RuntimeBuilder::new().token(TokenSource::Fixed(Arc::new("bearer".into())));+ assert!(matches!(&fixed.token, TokenSource::Fixed(t) if t.as_str() == "bearer"));+ }++ #[test]+ fn listen_records_host_and_port_for_the_transport() {+ let builder = RuntimeBuilder::new();+ assert_eq!(+ (builder.listen_host.as_deref(), builder.listen_port),+ (None, None)+ );+ let builder = RuntimeBuilder::new().listen("0.0.0.0", 9000);+ assert_eq!(builder.listen_host.as_deref(), Some("0.0.0.0"));+ assert_eq!(builder.listen_port, Some(9000));+ let port_only = RuntimeBuilder::new().listen_port(7799);+ assert_eq!(+ (port_only.listen_host, port_only.listen_port),+ (None, Some(7799))+ );+ }++ #[test]+ fn raw_paths_are_recorded_beside_the_workspace_variant() {+ let builder = RuntimeBuilder::new()+ .workspace(Workspace::dir("/srv/oh/root"))+ .workspace_dir("/srv/oh/state")+ .action_dir("/srv/oh/action");+ assert!(matches!(builder.workspace, Workspace::Dir(_)));+ assert_eq!(+ builder.workspace_dir.as_deref(),+ Some(std::path::Path::new("/srv/oh/state"))+ );+ assert_eq!(+ builder.action_dir.as_deref(),+ Some(std::path::Path::new("/srv/oh/action"))+ );+ assert!(builder.validate().is_ok(), "Resolved accepts raw paths");+ }++ #[test]+ fn the_default_config_source_is_resolved() {+ assert_eq!(RuntimeBuilder::new().config_source, ConfigSource::Resolved);+ }++ #[test]+ fn discovered_config_needs_the_inherited_workspace() {+ let err = RuntimeBuilder::new()+ .config_source(ConfigSource::Discovered)+ .validate()+ .expect_err("ephemeral + discovered");+ assert!(+ matches!(err, RuntimeError::Invalid(ref m) if m.contains("Workspace::Inherit")),+ "{err:?}"+ );+ }++ #[test]+ fn discovered_config_refuses_every_knob_that_edits_the_boot_config() {+ let discovered = || {+ RuntimeBuilder::new()+ .workspace(Workspace::Inherit)+ .config_source(ConfigSource::Discovered)+ };+ assert!(discovered().validate().is_ok());+ let cases: Vec<(&str, RuntimeBuilder)> = vec![+ (+ "config",+ discovered().config(openhuman_core::config::Config::default()),+ ),+ (+ "backend_url",+ discovered().backend_url("http://127.0.0.1:1"),+ ),+ (+ "workspace_dir",+ discovered().workspace_dir("/tmp/never-created"),+ ),+ ("action_dir", discovered().action_dir("/tmp/never-created")),+ ("api_key", discovered().api_key("th_live_x")),+ ];+ for (knob, builder) in cases {+ let err = builder.validate().expect_err(knob);+ assert!(+ matches!(err, RuntimeError::Invalid(ref m) if m.contains(knob)),+ "{knob}: {err:?}"+ );+ }+ }diff --cc crates/openhuman-embed/src/runtime/mod.rsindex 7a436c22b0,c3b8ed7dcc..575f3ded50--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@@ -68,11 -68,18 +68,19 @@@//! worker stack overflows.mod api_key;+ mod build;pub(crate) mod builder;+mod host_agents;+ mod presets;+ mod run;+ mod seams;+ mod summary;pub use api_key::ApiKey;- pub use builder::RuntimeBuilder;+ pub use builder::{ConfigSource, RuntimeBuilder};+ pub use run::run_from_args;+ #[doc(hidden)]+ pub use summary::BuilderSummary;use std::collections::HashMap;use std::path::Path;@@@ -159,12 -166,9 +167,15 @@@ pub(crate) struct CoreGuardsession_store: Option<Arc<dyn openhuman_core::agent::session_store::SessionStoreProvider>>,previous_session_store:Option<Arc<dyn openhuman_core::agent::session_store::SessionStoreProvider>>,+ /// The resolver through which the core's cron and workflow drivers find+ /// this runtime's agents; removed with the runtime.+ host_agents: Arc<dyn openhuman_core::agent::host_agents::HostAgentResolver>,+ /// Handlers registered with [`Runtime::on_system_job`], by job name.+ system_jobs:+ 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>,}impl Drop for CoreGuard {@@@ -463,10 -431,10 +505,12 @@@ impl Runtimeworkspace,session_store,previous_session_store,+ host_agents: resolver,+ system_jobs: Mutex::new(HashMap::new()),+ seams,}),base_config,+ config_unavailable,inherited,domains,tool_groups,diff --cc gitbooks/developing/embedding.mdindex f789fe7bc9,c439fbd30c..53b0c86d3a--- a/gitbooks/developing/embedding.md+++ b/gitbooks/developing/embedding.md@@@ -265,68 -265,9 +265,64 @@@ println!("{}", outcome.reply)# Ok(()) }```- `.seed(history)` replaces a session's history for one turn with the caller's- own rows (`(role, content)` pairs) rather than reading the transcript; only- a runtime-owned `Agent` can honour it, since it silently discards whatever- that session held, and it is meant to be paired with a session id the turn- is not sharing with turns that expect their history intact. `.meter(f)`+ `.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.+## Harness: the one-agent shorthand`Harness` is a `Runtime` plus exactly one agent, built from one set ofdiff --cc vendor/tinyagentsindex 776ca72ad4,37185fdcfc..33a86887d5--- a/vendor/tinyagents+++ b/vendor/tinyagents@@@ -1,1 -1,1 +1,1 @@@- Subproject commit 776ca72ad43cd073b38583d2063e9369823f5b5e-Subproject commit 37185fdcfc513ea2d9ea53608c069683975966e0++Subproject commit 33a86887d52f1dba4e39fdb598b7694c20cfdc84