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
docs: add READMEs for test support and embed agent modules
Steven Enamakel03691f7505ee
diff --git a/crates/openhuman-core/src/test_support/README.md b/crates/openhuman-core/src/test_support/README.mdindex c52ee37553..a020c23d1a 100644--- a/crates/openhuman-core/src/test_support/README.md+++ b/crates/openhuman-core/src/test_support/README.md@@ -1,80 +1,165 @@# test_support-Test-support domain: wipe-and-reset plus read-only introspection RPCs that let E2E specs drive the in-process core between tests without restarting the process. `openhuman.test_reset` returns the running core to a fresh-install baseline; the `test_support.*` introspection RPCs let specs verify that a UI action actually flowed through to disk and to live Rust state (workspace tree, files, the `IN_FLIGHT` chat map, wallet prepared quotes). Everything here is gated behind the `/rpc` bearer token (only written in debug builds) and, for the destructive reset, an explicit `OPENHUMAN_E2E_MODE` env flag: so it is effectively unreachable in release.--## Responsibilities--- Reset persistent core state in-place to the "fresh install" baseline: no authenticated user (`active_user.toml` removed, `api_key` cleared), onboarding not completed (`onboarding_completed=false`, `chat_onboarding_completed=false`), no cron jobs. Memory v2 lives in a remote engine and is not wiped.-- Short-circuit and surface errors on any individual wipe step (partial resets are treated as worse than a clear failure).-- Gate `reset` behind `OPENHUMAN_E2E_MODE` (`1`/`true`/`TRUE`/`yes`/`YES`).-- Provide narrow, read-only introspection RPCs: resolve the active workspace root, list workspace files (depth- and count-capped), read a workspace file (lossy UTF-8, 1 MiB cap), snapshot the in-flight chat map, and snapshot the wallet prepared-quote store.-- Enforce workspace-jail path safety: reject `..` escapes, canonicalize the root (handles macOS `/var`→`/private/var` symlink), and skip symlinks during directory walks so listings can't escape the workspace.--## Key files--| File | Role |+RPCs that let the desktop E2E specs control and inspect a running core+without restarting it. `openhuman.test_reset` puts the core back to a+fresh-install baseline between specs, and the `test_support.*` methods are+read-only probes that let a spec confirm a UI action reached disk and live+Rust state (the workspace tree, file contents, the in-flight chat map, the+wallet's prepared quotes).++None of this ships. The module only compiles with the `e2e-test-support`+Cargo feature, which is off in the contributor default set and absent from+`scripts/ci/product-features.txt`.++## How it works++The E2E build turns the feature on, the registry picks the controllers up,+and the WDIO runner calls them over JSON-RPC with the debug-only bearer.++```text+app/scripts/e2e-build.sh+ pnpm tauri build --debug --features e2e-test-support+ |+ v+crates/openhuman-app e2e-test-support = ["openhuman_core/e2e-test-support"]+ |+ v+lib.rs #[cfg(feature = "e2e-test-support")] pub mod test_support;+core/all.rs push(DomainGroup::Platform,+ all_test_support_registered_controllers())+ |+ v+running core (debug build)+ core_process.rs writes the /rpc bearer to+ ${tmpdir}/openhuman-e2e-rpc-token (debug_assertions only, mode 0600)+ ^+ | JSON-RPC: openhuman.test_reset, openhuman.test_support_*+ |+WDIO specs (app/test/e2e/specs/, helpers/reset-app.ts)+```++### Reset++`rpc::reset()` refuses to run unless `OPENHUMAN_E2E_MODE` is `1`, `true`,+`TRUE`, `yes` or `YES`. It then loads the config and wipes, in order:++1. Cron jobs (`cron::clear_all_jobs`), so the post-onboarding seed recreates+ `morning_briefing`.+2. Config fields: `onboarding_completed` and `chat_onboarding_completed` set+ to `false`, `api_key` cleared, then `Config::save`.+3. The active user: `config::clear_active_user` removes `active_user.toml`+ under `default_root_openhuman_dir()`.++Any failed step returns an error immediately. A partial reset is treated as+worse than a clear failure, because it lets later specs pass on contaminated+state. The result is a `ResetSummary` (`cron_jobs_removed`,+`onboarding_was_completed`, `api_key_was_set`, `active_user_cleared`). Memory+lives in a remote engine and is not wiped.++The core process keeps running. Specs reload the webview after the call so+the renderer also starts blank.++### Introspection++The `introspect.rs` functions read state and change nothing.+`workspace_root` reports `Config::workspace_dir` and whether it exists.+`list_workspace_files` walks the tree with an explicit stack (no async+recursion), defaulting to depth 2, clamped to 6, and stopping at 2000 entries+with `truncated: true`. `read_workspace_file` reads up to `max_bytes`+(capped at 1 MiB) and converts it with lossy UTF-8; `returned_bytes` is the+raw byte count before conversion, so specs can assert truncation exactly.+`in_flight_chats` snapshots the web chat `IN_FLIGHT` map+(`web_chat::in_flight_entries_for_test`), and `wallet_prepared_quotes`+snapshots the in-memory prepared-quote store+(`web3::wallet::prepared_quotes_for_test`).++Every path argument goes through `resolve_workspace_relative`, which keeps+reads inside the workspace:++1. A lexical component walk rejects `..` and any root or prefix component+ (`C:\`, `\\?\`) before touching the filesystem. `./` is allowed.+2. The workspace root is canonicalized (on macOS `/var` resolves to+ `/private/var`), the relative path is joined onto it, and the candidate is+ canonicalized and checked with `starts_with`. This second step catches a+ symlink pointing out of the workspace, which the lexical walk cannot see.++The lexical step matters because `canonicalize` fails on a missing path, and+without it a `..` path to a nonexistent target used to pass the prefix check+(openhuman#6085). `walk_dir` uses `symlink_metadata` and skips symlinks, so+listings never follow a link out of the workspace.++## Layout++| Path | What it does || --- | --- |-| `crates/openhuman-core/src/test_support/mod.rs` | Export-only module: declares `introspect`, `rpc`, `schemas`; re-exports `all_test_support_controller_schemas` / `all_test_support_registered_controllers`. |-| `crates/openhuman-core/src/test_support/rpc.rs` | `openhuman.test_reset` implementation: `reset()` wipes cron, config fields, and active user; returns a `ResetSummary`. Includes the `OPENHUMAN_E2E_MODE` guard. |-| `crates/openhuman-core/src/test_support/rpc_tests.rs` | Tests for the `OPENHUMAN_E2E_MODE` guard (`reset` rejects when unset; `1`/`true`/`yes` accepted). |-| `crates/openhuman-core/src/test_support/introspect.rs` | Read-only introspection RPCs: `workspace_root`, `list_workspace_files`, `read_workspace_file`, `in_flight_chats`, `wallet_prepared_quotes`, plus the `resolve_workspace_relative` path guard and the iterative `walk_dir`. |-| `crates/openhuman-core/src/test_support/introspect_tests.rs` | Tests for `resolve_workspace_relative` only: `..` traversal (missing and existing targets), leading `/` and `./` handling, and (unix) a symlink pointing out of the workspace. The RPC functions themselves have no unit tests here; E2E specs exercise them. |-| `crates/openhuman-core/src/test_support/schemas.rs` | `ControllerSchema` definitions, the registered-controller list, and `handle_*` dispatchers that delegate to `rpc`/`introspect` and serialize via `Outcome::into_cli_compatible_json`. |--## Public surface--From `mod.rs`:-- `all_test_support_controller_schemas()`: `Vec<ControllerSchema>` for the six controllers.-- `all_test_support_registered_controllers()`: `Vec<RegisteredController>` (schema + handler pairs).--From `rpc` / `introspect` (used by handlers, also `pub`):-- `rpc::reset() -> Outcome<ResetSummary>`.-- `introspect::workspace_root()`, `list_workspace_files(rel_root, max_depth)`, `read_workspace_file(rel_path, max_bytes)`, `in_flight_chats()`, `wallet_prepared_quotes()`.-- Result types: `ResetSummary`, `WorkspaceRoot`, `ListEntry`/`ListResult`, `ReadFileResult`, `InFlightEntryView`/`InFlightResult`, `PreparedQuotesResult`.--## RPC / controllers--Six controllers, registered into the global registry via `crates/openhuman-core/src/core/all.rs`:--| Namespace.function | Inputs | Purpose |+| `mod.rs` | Declares `introspect`, `rpc` and `schemas`; re-exports `all_test_support_controller_schemas` and `all_test_support_registered_controllers`. |+| `rpc.rs` | `reset()`, the `OPENHUMAN_E2E_MODE` guard and `ResetSummary`. |+| `introspect.rs` | The read-only probes, their result types, `resolve_workspace_relative` and `walk_dir`. |+| `schemas.rs` | Controller schemas and thin `handle_*` functions that call `rpc` or `introspect` and serialize with `Outcome::into_cli_compatible_json`. |++## Key types and entry points++- `rpc::reset() -> Result<Outcome<ResetSummary>, String>` (`rpc.rs`).+- `introspect::workspace_root`, `list_workspace_files(rel_root, max_depth)`,+ `read_workspace_file(rel_path, max_bytes)`, `in_flight_chats`,+ `wallet_prepared_quotes` (`introspect.rs`).+- Result types: `WorkspaceRoot`, `ListEntry` and `ListResult`,+ `ReadFileResult`, `InFlightEntryView` and `InFlightResult`,+ `PreparedQuotesResult` (`introspect.rs`).+- `all_test_support_registered_controllers()` (`mod.rs`), which+ `core/all.rs` pushes under `DomainGroup::Platform`.+ `all_test_support_controller_schemas()` has no consumer outside this module.++## RPC / CLI surface++| Method | Inputs | Purpose || --- | --- | --- |-| `test.reset` | none | Wipe auth, onboarding, and cron to a fresh-install baseline. Requires `OPENHUMAN_E2E_MODE`. |-| `test_support.workspace_root` | none | Return active `workspace_dir` path + existence. |-| `test_support.list_workspace_files` | `rel_root?`, `max_depth?` | Recursive listing, capped at depth 6 / 2000 entries. |-| `test_support.read_workspace_file` | `rel_path`, `max_bytes?` | Lossy-UTF-8 file read, capped at 1 MiB; rejects `..` escapes. |-| `test_support.in_flight_chats` | none | Snapshot the `IN_FLIGHT` chat map (`(client_id, thread_id)` → `request_id`). |-| `test_support.wallet_prepared_quotes` | none | Snapshot the in-memory wallet prepared-quote store. |--Note the `reset` controller uses namespace `test` (method `openhuman.test_reset`) while the introspection controllers use namespace `test_support`.--## Persistence--This module owns no state of its own. It mutates and reads state owned by other domains:-- Wipes: cron jobs (`cron::clear_all_jobs`), config fields (`onboarding_completed`, `chat_onboarding_completed`, `api_key`), and `active_user.toml` (`config::clear_active_user` under `default_root_openhuman_dir`).-- Reads: workspace files under `Config::workspace_dir`, the in-process `IN_FLIGHT` chat map, and the in-memory wallet prepared-quote store.--## Dependencies--- `crate::config`: `Config::load_or_init`/`save`, `workspace_dir`, `clear_active_user`, `default_root_openhuman_dir`; config is the source of truth for the workspace root and the fields reset wipes.-- `crate::cron`: `clear_all_jobs` to wipe scheduled jobs during reset.-- `crate::web_chat`: `in_flight_entries_for_test` to snapshot the live `IN_FLIGHT` chat map.-- `crate::web3::wallet`: `prepared_quotes_for_test` and `PreparedTransaction` to snapshot prepared quotes.-- `crate::core::all`: `ControllerFuture`, `RegisteredController` for handler wiring.-- `crate::core::{ControllerSchema, FieldSchema, TypeSchema}`: controller schema types.-- `crate::core::Outcome`: the controller result type.--## Used by--- `crates/openhuman-core/src/core/all.rs`: pushes `all_test_support_registered_controllers()` into the global registry under `DomainGroup::Platform`, behind the same `#[cfg(feature = "e2e-test-support")]`. Method names come from the registry's `openhuman.{namespace}_{function}` rule. `all_test_support_controller_schemas()` has no consumer outside this module.-- `crates/openhuman-core/src/lib.rs`: declares `pub mod test_support;` behind `#[cfg(feature = "e2e-test-support")]`. The feature is off in the contributor default set (`default = [...]` in `crates/openhuman-core/Cargo.toml`) and absent from `scripts/ci/product-features.txt`, so neither a bare `cargo check` nor the shipped app compiles this module. It is turned on by the E2E build (`app/scripts/e2e-build.sh`, forwarded through `crates/openhuman-app/Cargo.toml`'s `e2e-test-support` feature) and by a dedicated CI Lite lane (`.github/workflows/ci-lite.yml`) that `cargo check`s it and runs the `test_support::introspect::` tests with `--no-default-features --features e2e-test-support`.-- Consumed at runtime by E2E specs (WDIO) calling `openhuman.test_reset` and `openhuman.test_support_*` over JSON-RPC.--## Notes / gotchas--- Double gating: `reset` is fail-closed behind both the `/rpc` bearer token and `OPENHUMAN_E2E_MODE`; introspection RPCs rely on the bearer token alone. The token file specs read is written by `crates/openhuman-app/src/core_process.rs` under `#[cfg(debug_assertions)]` only.-- In-process reset: the core process is not restarted; specs reload the webview afterward so the renderer also starts blank.-- Add new persistent state to `reset`. Per the module docstring, any new domain that survives `test_reset` is a leak that lets specs interfere, so extend `rpc::reset` when adding persistent state.-- Path-jail ordering: `resolve_workspace_relative` rejects `..` (and root/prefix components) lexically before touching the filesystem; the `canonicalize` + `starts_with` check underneath only catches symlink escapes and used to fail open for non-existent targets (openhuman#6085). It canonicalizes the root first (macOS `/var`→`/private/var`); `walk_dir` uses `symlink_metadata` and skips symlinks so listings can't follow links out of the workspace.-- CI runs only the `introspect` tests (the CI Lite lane filters to `test_support::introspect::`). Run `cargo test -p openhuman --features e2e-test-support --lib -- test_support::` locally to cover both files.-- `read_workspace_file` byte accounting: `returned_bytes` is the raw byte count before lossy UTF-8 conversion (which substitutes U+FFFD and can change length) so specs can assert byte-accurate truncation.-- `list_workspace_files` schema omits `entries` for brevity, but the runtime payload includes them. `max_depth` defaults to 2, clamped to 6; entry cap is 2000.+| `test.reset` (wire `openhuman.test_reset`) | none | Wipe cron, onboarding flags, `api_key` and the active user. Requires `OPENHUMAN_E2E_MODE`. |+| `test_support.workspace_root` | none | Active `workspace_dir` and whether it exists. |+| `test_support.list_workspace_files` | `rel_root?`, `max_depth?` | Recursive listing, depth 2 by default, max 6, at most 2000 entries. |+| `test_support.read_workspace_file` | `rel_path`, `max_bytes?` | Lossy UTF-8 read, capped at 1 MiB; rejects paths that leave the workspace. |+| `test_support.in_flight_chats` | none | Snapshot of `IN_FLIGHT` (`(client_id, thread_id)` to `request_id`). |+| `test_support.wallet_prepared_quotes` | none | Snapshot of the in-memory prepared-quote store. |++The reset uses namespace `test`; the probes use `test_support`. Wire names+follow the registry's `openhuman.{namespace}_{function}` rule.++## Boundaries++This module owns no state. It writes to state owned by `config` (onboarding+flags, `api_key`, `active_user.toml`) and `cron` (jobs), and reads state owned+by `config` (workspace root), `web_chat` (`IN_FLIGHT`) and `web3::wallet`+(prepared quotes). Those domains expose the `*_for_test` accessors it calls.++The E2E runner, its helpers and the token-file reader live under+`app/test/e2e/`. The bearer file is written by+`crates/openhuman-app/src/core_process.rs`.++## Gotchas++- Reset is gated twice: the `/rpc` bearer and `OPENHUMAN_E2E_MODE`. The+ probes rely on the bearer alone, which is only exposed to the test runner+ in debug builds. Both sit behind the Cargo feature.+- When a domain adds persistent state, extend `rpc::reset` to wipe it. State+ that survives `test_reset` lets specs interfere with each other.+- The `list_workspace_files` schema leaves `entries` out of its declared+ outputs for brevity, but the runtime payload includes them.+- `scripts/ci/assert-coverage-presence.sh` lists this folder as uncovered by+ design, because the default coverage build does not enable the feature.++## Tests++`rpc_tests.rs` covers the `OPENHUMAN_E2E_MODE` guard. `introspect_tests.rs`+covers `resolve_workspace_relative` (`..` with missing and existing targets,+leading `/` and `./`, and on Unix a symlink out of the workspace); the RPCs+themselves are exercised by the E2E specs.++The feature must be enabled to compile any of it:++```bash+cargo test -p openhuman --no-default-features --features e2e-test-support --lib -- test_support::+```++CI runs only the introspect tests, in the `gate-contract-tests-features` lane+of `scripts/ci/self-hosted/lanes-plan.mjs`+(`--features mcp,e2e-test-support ... test_support::introspect::`).diff --git a/crates/openhuman-embed/src/agent/README.md b/crates/openhuman-embed/src/agent/README.mdindex a310e523c4..355482a90d 100644--- a/crates/openhuman-embed/src/agent/README.md+++ b/crates/openhuman-embed/src/agent/README.md@@ -1,84 +1,148 @@# agent-One fully described, independently configured participant on a `Runtime`.-See [`gitbooks/developing/embedding.md`](../../../../gitbooks/developing/embedding.md)+An agent is one fully described, independently configured participant on a+`Runtime`. This folder holds the pure-data `AgentSpec` a host writes, the+build step that turns it into a live `Agent`, and the handle the host keeps.+`Runtime::agent` is the only caller of the build step; hosts call `Agent::run`+and `Agent::turn`. See+[`gitbooks/developing/embedding.md`](../../../../gitbooks/developing/embedding.md)for how agents fit into the two-step library API.-## Contents--- `mod.rs`: `Agent`, the cheap-to-clone handle a host holds: `run()` /- `turn()` to talk to it, `action_dir()` / `workspace_dir()` / `home_dir()` /- `skills_dir()` / `transcripts_dir()` for its paths, `provider()` /- `access()` / `config()` for inspection. `AgentInner` is the shared state- behind every clone, and `AgentError` covers the ways building or driving an- agent can fail (duplicate id, invalid id, widening the runtime's surface, a- workspace I/O failure).-- `spec.rs`: `AgentSpec`, the pure-data description a host builds before an- agent exists: id, `AgentDefinitionSpec`, provider, access, tool groups,- domains, MCP servers (`mcp` feature), a skills directory (`skills`- feature), `action_dir`, trusted paths, an escape-hatch config closure, and- an optional per-turn tool factory (`tools()`). `Runtime::agent` applies- these, in order, onto a clone of the runtime's base config.-- `definition.rs`: `AgentDefinitionSpec`, `ToolScopeSpec` and- `SandboxModeSpec`: a thin re-spelling of the core's `AgentDefinition` so- the library surface does not track that struct field by field. The default- is the built-in orchestrator's definition under the agent's own id, with- every registered tool visible.-- `layout.rs`: `AgentLayout`: where one agent's files live under the- runtime's workspace (`agents/<id>/` for its home and skills,- `session_raw/` for transcripts, plus its resolved `action_dir`).-- `build.rs`: `instantiate`, the function that turns an `AgentSpec` plus a- `Runtime` into the assembled `AgentInner` (lays out directories, copies- skills, builds the `Config`, derives the `CoreContext`).--## Isolation between agents--Two agents on one runtime never read each other's settings. Each turn-dispatches under its own derived `CoreContext`, so the core's config loader,-`DomainSet` gate, tool-group filter and skill discovery all read the agent-that turn belongs to, not any other agent sharing the runtime.+## How it works++`AgentSpec::new(id)` starts with every setting unset, meaning "use the+runtime's default". Builder methods fill in the provider, access, definition,+MCP servers, skills, `action_dir`, trusted paths, Composio credential, memory+binding, a config escape hatch and a tool factory. A spec does nothing on its+own.++`Runtime::agent(spec)` holds the runtime's agent registry lock (so two calls+with the same id cannot both pass the duplicate check), then calls+`build::instantiate`. That function runs in a fixed order:++```text+ AgentSpec+ |+ v+ 1. validate id ^[a-z0-9][a-z0-9_-]{0,63}$+ 2. config = runtime base config (clone)+ 3. action_dir spec value, else AgentLayout::default_action_dir+ 4. access.apply tier, trusted roots (replaced, not merged)+ 5. provider model route stays per turn, never written to config+ 6. MCP servers appended to mcp_client.servers (mcp feature)+ 7. Composio credential pinned for this agent only+ 8. memory binding memory.agent_id and memory.root+ 9. config escape hatch then config_path is reset to the runtime's+10. create dirs action_dir, agents/<id>/, agents/<id>/skills/+11. copy skills (skills feature)+12. definition AgentDefinitionSpec -> core AgentDefinition+13. narrowing checks DomainSet and ToolGroups may only shrink+14. CoreContext::derive_with(ContextOverlay { config, domains, ... })+ |+ v+ AgentInner (shared by every Agent clone and every Turn it issues)+```++The `action_dir` is read back from the config after step 9, so a `config`+closure that moves it gets the directory it asked for. When MCP servers are+declared and the definition uses a named tool belt, step 12 adds+`tool_search` to the belt, because MCP tools are registered as deferred+`mcp_<server>_<tool>` entries that a named belt can only reach through+discovery.++The derived `CoreContext` is what makes agents independent. Every turn runs+inside it (`CoreRuntime::run_in`), so the core's config loader, `DomainSet`+gate, tool-group filter and skill discovery read this agent's overlay and no+other. The overlay also carries `session_agent`, which a host session store+uses to keep each agent's conversations apart.++`AgentInner` holds an `Arc<CoreGuard>`, so the core (and an ephemeral+workspace) stays alive while any agent handle or in-flight `Turn` exists,+even after the host drops its `Runtime`. The id is released for reuse once+the last clone of an agent is dropped. Dropping an agent does not delete its+directories; transcripts and memory persist with the workspace.++## Layout++| File | What it does |+| --- | --- |+| `mod.rs` | `Agent`, the cheap clone handle (`run`, `turn`, `id`, `action_dir`, `workspace_dir`, `home_dir`, `skills_dir`, `transcripts_dir`, `provider`, `access`, `config`), the shared `AgentInner`, and `AgentError`. |+| `spec.rs` | `AgentSpec`, the builder a host fills in, and `MemoryBinding`. |+| `definition.rs` | `AgentDefinitionSpec`, `ToolScopeSpec` and `SandboxModeSpec`: a small re-spelling of the core's `AgentDefinition`. |+| `layout.rs` | `AgentLayout`: where one agent's home, skills, transcripts and `action_dir` live. |+| `build.rs` | `instantiate`, plus `check_domains_narrow` and `check_tool_groups_narrow`. |+| `attachments.rs` | `Agent::attach_tools`, `runtime_id`, `same_agent`, `ToolAttachmentError`, and the policy that composes attached sources with the agent's own. |++## Key types++- `AgentSpec` (`spec.rs`): the description. `system_prompt` and `definition`+ set what the agent is; `provider`, `model` and `access` set where it runs+ and with what authority; `tool_groups` and `domains` narrow its surface;+ `mcp` and `skills_dir` add servers and skills; `include_user_skills(true)`+ lets it see the operator's `~/.openhuman/skills` (off by default);+ `action_dir` and `trust` set its filesystem reach; `composio` pins its own+ Composio key and entity; `memory` binds its memory; `config` is the escape+ hatch; `tools` is the per-turn tool factory.+- `AgentDefinitionSpec` (`definition.rs`): the default is the built-in+ orchestrator's definition under the agent's own id, except that every+ registered tool is visible (`ToolScopeSpec::Wildcard`). Narrow with+ `tools(ToolScopeSpec::Named(..))` or `disallow_tools`. Also sets+ `sandbox` (`None`, `ReadOnly`, `Sandboxed`), `max_iterations`,+ `temperature`, `display_name` and `when_to_use`.+- `MemoryBinding` (`spec.rs`): the memory agent id the turns are logged+ under, and optionally a layout root such as `team:acme`.+- `AgentLayout` (`layout.rs`): `home` is `<workspace>/agents/<id>/`, `skills`+ is `<workspace>/agents/<id>/skills/`, `transcripts` is+ `<workspace>/session_raw/`, and `action_dir` is the resolved acting root.+- `AgentError` (`mod.rs`): `DuplicateId`, `InvalidId`, `WidensRuntime`,+ `Workspace` (an I/O failure laying out directories), `Invalid`, and `Call`+ for a failed turn.## Tool factories`AgentSpec::tools` supplies a host's own in-process tools when an agent is-created. `Agent::attach_tools` adds permanent tools to an existing agent. The factory runs once per session build,-which in practice means once per turn, because a session is rebuilt from the-spec's data every time; see the doc comment on `AgentSpec::tools` for why-this is forced (an `Agent` is `Clone`, `Box<dyn Tool>` is not) and useful (a-belt bound to something shorter-lived than the agent can vary per turn).+created. Each tool is a real tool with its own schema on the wire, unlike a+tool reached through an MCP server's `mcp_call_tool` envelope. The factory+runs once per session build, which in practice is once per turn: an `Agent`+is `Clone` and `Box<dyn Tool>` is not, so a stored belt could not survive the+rebuild. The factory receives a `TurnContext` with the agent id and the+session id the caller named, so a host whose tools are bound to one episode+or room can return a different belt per conversation.-## Where to look next--- [`../runtime/README.md`](../runtime/README.md): what instantiates an- agent and what stays runtime-wide instead of per-agent.-- [`../harness/README.md`](../harness/README.md): the one-runtime,- one-agent shorthand.+The prompt's tool catalogue is rendered from the same belt in the same+build. A resumed session reuses its persisted system messages, though, so a+belt that changes under a long-lived thread is still described by the prompt+that thread opened with. Vary a belt only on turns that run in a session of+their own.## Attach tools to an existing agent`Agent::attach_tools(key, factory)` permanently adds a named `HostTools`-source without rebuilding the agent. All clones share the attachment. Reusing-both the source key and the same factory `Arc` is idempotent; another factory-under the same key or a colliding tool name returns `ToolAttachmentError`.-The factory is sampled without a session during registration, then runs per-turn. Keep its tool names stable and support the registration occasion.--Attached tools always have direct provider schemas and a separate system-catalogue, including tools originally declared deferred. Adding a source to-an existing conversation updates only that managed section on the next turn:-the configured prompt, skills, memory, and other frozen system sections stay-intact. TinyAgents seals the prior transcript generation and writes a successor-with the conversation preserved. Identical catalogues do not create generations.--Attachments do not replace the original host's tool gate. Each source's policy-applies to its own tool names; absent a source policy, those callbacks are-admitted and must perform their own operation authorization. Other tools keep-the agent's original policy, including its denials.+source without rebuilding the agent. All clones share the attachment.+Attaching the same key with the same factory `Arc` again is a no-op; another+factory under that key returns `ToolAttachmentError::SourceConflict`, and a+tool name that collides with one already registered returns+`NameCollision`. The factory is sampled once without a session at+registration to learn its tool names, then runs per turn. Keep its tool names+stable and make it work for that registration call.++Attached tools always get direct provider schemas and their own system+catalogue section, including tools that declare themselves deferred. Adding a+source to an existing conversation updates only that managed section on the+next turn; the configured prompt, skills, memory and other frozen system+sections stay as they were. TinyAgents seals the prior transcript generation+and writes a successor with the conversation preserved. An identical+catalogue does not create a new generation.++Attachments do not replace the agent's original tool gate. Each source's+policy applies to its own tool names. A source without a policy admits its+tools, so their callbacks must authorize their own operations. Every other+tool keeps the agent's original policy, including its denials.Use `runtime_id()` to check that supplied agents belong to one runtime and-`same_agent()` to distinguish an existing handle from a conflicting agent ID.-Runtime identities are opaque and valid for that runtime's lifetime; they are-not persistence keys.+`same_agent()` to tell an existing handle from a different agent with a+conflicting id. Runtime ids are opaque and valid only for that runtime's+lifetime; they are not persistence keys.```rust,no_runuse std::sync::Arc;@@ -86,7 +150,47 @@ use openhuman_embed::{Agent, HostTools, HostTurnTools, Tool};# fn connect(agent: &Agent, make_tools: impl Fn() -> Vec<Box<dyn Tool>> + Send + Sync + 'static) -> Result<(), openhuman_embed::ToolAttachmentError> {let source: HostTools = Arc::new(move |_| HostTurnTools::advertised(make_tools()));agent.attach_tools("tinyhivemind", source.clone())?;-agent.clone().attach_tools("tinyhivemind", source)?;+agent.clone().attach_tools("tinyhivemind", source)?; // idempotent# Ok(())# }```++## Boundaries++- What a turn does once dispatched (the agent loop, transcripts, tool-call+ parsing) belongs to `vendor/tinyagents`; the definition types and+ `agent_chat_for` belong to the core (`openhuman_core::agent::harness` and+ `inference::host_runtime`).+- Process-scoped state (keyring, bus, services, the registered domain set)+ belongs to the runtime. See [`../runtime/README.md`](../runtime/README.md)+ and the crate README's list of settings that are still runtime-wide.+- `Access`, `Provider` and `McpServer` are defined in+ [`../harness/`](../harness/README.md) and shared with the one-agent+ `Harness`.++## Gotchas++- `Access::apply` replaces the trusted roots; it does not add to the+ runtime's. A `readonly()` agent on a runtime whose default trusts extra+ paths trusts none of them.+- The `config` closure cannot move `config_path`. It is reset to the+ runtime's after the closure runs, because every agent shares one+ credential store and keyring.+- An agent cannot widen the runtime. Asking for a domain family the runtime+ did not register, or a tool group more exposed than the runtime's+ (`Off` < `Withheld` < `Advertised`), fails with `AgentError::WidensRuntime`.+- Avoid built-in agent ids such as `orchestrator` and `summarizer`; the+ runtime-wide delegation catalogue resolves those to the shipped+ definitions.++## Tests++`build_tests.rs`, `definition_tests.rs`, `layout_tests.rs`, `spec_tests.rs`+and `attachments_tests.rs` sit beside their modules. The end-to-end proof of+agent isolation is `tests/runtime_agents.rs`, and attachments are covered by+`tests/attached_tools.rs`.++```bash+cargo test -p openhuman-embed --features inference,mcp,skills agent::+cargo test -p openhuman-embed --features inference,mcp,skills --test attached_tools+```