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(core): rewrite the core README around the kernel's actual behaviour
Steven Enamakel28e0ebef1f76
diff --git a/crates/openhuman-core/src/core/README.md b/crates/openhuman-core/src/core/README.mdindex 013f1e2c15..36c8858f01 100644--- a/crates/openhuman-core/src/core/README.md+++ b/crates/openhuman-core/src/core/README.md@@ -1,246 +1,445 @@# core-The controller contract, in-process dispatch, the controller registry, the-event bus, auth, the CLI, and runtime composition. `core/` is not a domain: it holds no business-logic. Every controller it exposes is implemented by a domain module under-`crates/openhuman-core/src/<domain>/` and wired in here.--## Responsibilities--- Define the transport-agnostic controller contract that both RPC and CLI- invoke against: `ControllerSchema`, `FieldSchema`, `TypeSchema` (`mod.rs`),- the [`Outcome`](outcome.rs) every operation returns, the structured error- envelope (`structured_error.rs`) and the params rules (`params.rs`).-- Own the single registry of every controller (`all.rs`) and the coarse- `DomainGroup` tagging that lets a runtime narrow its live surface.-- Dispatch every call in-process through `invoke::invoke_method`, which- validates params, runs the tiered router (`dispatch.rs`) and publishes- `SessionExpired` on a confirmed expiry (`session_expiry.rs`).-- Own the process-wide typed event bus (`bus.rs`, `events.rs`).-- Provide the CLI surface (`cli.rs` and friends). Serving JSON-RPC and- Socket.IO over HTTP is `openhuman-rpc`'s job; the CLI's `run` / `serve`- start it through the launcher a host installs (`server_launcher.rs`).-- Seed and check the per-process RPC bearer token (`auth.rs`,- `event_bind_tokens.rs`).-- Compose an embeddable `CoreRuntime` from domain modules (`runtime/`) and- track subsystem driver health (`subsystem/`).-- Redact secrets before anything reaches a log line or Sentry- (`log_redaction.rs`, `rpc_log.rs`, `observability.rs`).--## Key files--| File | Role |-| --- | --- |-| `mod.rs` | `ControllerSchema`/`FieldSchema`/`TypeSchema`: the controller contract; module declarations. |-| `all.rs` | The controller registry: `RegisteredController`, `RegisteredCliAdapter`, `DomainGroup`, `all_registered_controllers()`, `all_controller_schemas()`, `rpc_method_name()`, `validate_params()`, `all_http_method_schemas()`. |-| `dispatch.rs` | `dispatch()`: the 4-tier RPC router. |-| `bus.rs` | The `BUS: OnceBus<DomainEvent>` singleton, `EVENTS_ROOT`/`EVENTS_INTERFACE`/`EVENTS_VERSION`, `init`. |-| `events.rs` | `DomainEvent`: the full event catalog, `domain()` routing. |-| `outcome.rs` | `Outcome<T>`, `apply_log_envelope`, `unwrap_rpc`: the controller result and its wire shape. |-| `structured_error.rs` | `StructuredRpcError`: typed error envelope sentinel-encoded into a controller's `Err(String)`. |-| `params.rs` | Params shape (`params_to_object`) and the validation messages `all::validate_params` emits, with their matcher. |-| `invoke.rs` | `invoke_method` / `default_state`: in-process dispatch every transport and the CLI use. |-| `session_expiry.rs` | `is_session_expired_error`: which failures mean the OpenHuman session expired. |-| `server_launcher.rs` | `ServerLauncher` port the CLI `run` / `serve` subcommands start a server through. |-| `auth.rs` | Per-process RPC bearer token: init paths, `get_rpc_token`, `verify_bearer_token`, `bearer_matches`. The HTTP route policy is `openhuman_rpc::server::auth`. |-| `event_bind_tokens.rs` | Single-shot bind tokens for the `/events` SSE stream. |-| `cli.rs`, `agent_cli.rs`, `memory_cli.rs`, `subsystems_cli.rs`, `cli_capability.rs` | CLI argument parsing and dispatch, routed through the same registry as RPC. |-| `types.rs` | `AppState`, `HostKind`, `InvocationResult`, `approval_gate_boot_decision`. |-| `legacy_aliases.rs` | `resolve_legacy`: rewrites retired method names before dispatch; mirrors `app/src/services/rpcMethods.ts`'s `LEGACY_METHOD_ALIASES`. |-| `observability.rs` | `report_error` + Sentry `before_send` filters that drop deterministic provider/updater noise. |-| `log_redaction.rs` | `scrub_secrets`: regex secret scrubbing shared by the Sentry path and always-on log path. |-| `rpc_log.rs` | `redact_params_for_log` (key-name redaction for the `[rpc:dispatch]` trace log in `dispatch.rs`) |-| `logging.rs` | `init_for_cli_run` / `init_for_embedded`: logger setup for each host kind. |-| `shutdown.rs` | Graceful shutdown signal plumbing. |-| `sentry_transport.rs` | Sentry client setup, gated by the `crash-reporting` feature. |-| `http_server_status.rs` | `HTTP_SERVER_COMPILED_IN`: ungated compile-time marker so a listener-less core fails the build instead of shipping silently. |-| `bus_testing.rs` | `isolated_bus()`: a private bus for tests that must observe events without racing the process-global singleton. |-| `runtime/` | `CoreBuilder` → `CoreRuntime` composition API: see [runtime/README.md](runtime/README.md). |-| `subsystem/` | The `subsystems` status namespace (`SubsystemStatus` row, RPC and CLI table); memory fills its row. |--## Controller registration and `DomainGroup`--Every controller is registered exactly once, in `all.rs`, tagged with a-`DomainGroup`: the coarse family (`Agent`, `Memory`, `Security`, `Flows`,-`Inference`, `Platform`, …) it belongs to. `DomainGroup` variants track the-`crates/openhuman-core/src/` family directories 1:1. The live surface-(schema dump, dispatch, agent tools, stores, subscribers) is filtered by-whether the active `runtime::context::CoreContext`'s `DomainSet` allows that-group; `DomainSet::full()` allows every group, so registration stays-byte-identical to a build with no runtime narrowing. Adding a new family-directory means adding the matching `DomainGroup` variant, a `DomainSet`-field, an arm in `DomainSet::allows()`, and an entry in each preset: the-compiler enforces all four.--`rpc_method_name(schema)` turns a controller's dotted key (`memory.doc_put`)-into its wire method name (`openhuman.memory_doc_put`); the two are-intentionally different strings and callers must not conflate them.-`validate_params()` checks required/unknown params and each present value's-declared `TypeSchema` before a handler ever runs. `all_http_method_schemas()`-adds the two Tier-1 internal methods (`core.ping`, `core.version`) to the-registered set for `/schema`.--Wire controllers only through this registry: do not add namespace branches-to `cli.rs` or the JSON-RPC server. RPC namespace strings are wire contracts and do-not follow directory renames.--## Dispatch--`dispatch::dispatch()` is the single entry point every transport (`/rpc`,-Socket.IO, the CLI, `CoreRuntime::invoke`) calls through. It resolves in four-tiers:--1. **Tier 0: legacy alias rewrite.** `legacy_aliases::resolve_legacy`- rewrites a retired method name to its canonical form before any lookup,- symmetric with the frontend's `normalizeRpcMethod`.-2. **Tier 1: internal core methods.** `core.ping`, `core.version`, and- `core.events_subscribe_token` (mints a bind token for `/events`) are- handled directly, with no controller registration.-3. **Tier 2: registered controllers.** Looked up by RPC method name in the- `all.rs` registry, validated with `validate_params`, and invoked.-4. **Tier 3: unknown method.** Always a method-not-found error; only the- Sentry severity differs by whether the method is a known non-actionable- probe (`is_known_probe_method`).--## Event bus--`bus.rs` declares the process-wide `BUS: OnceBus<DomainEvent>`: the one-thing a generic bus crate (`tinybus`) cannot own, since it is generic over-the event type. `events.rs` is the vocabulary half: `DomainEvent`, a-`#[non_exhaustive]` enum whose `domain()` method is the routing key appended-to `EVENTS_ROOT` (`/ai/tinyhumans/openhuman/events`). `EVENTS_VERSION` is-currently `1.4.0`; bump the minor for an added variant or field, the major-(and rename `EVENTS_INTERFACE`) for a breaking change.--Two surfaces, pick by what the call needs to carry:+`core/` is the kernel of the `openhuman` crate. It defines the controller+contract every domain implements, keeps the one registry of those+controllers, dispatches calls to them in-process, and owns the process-wide+event bus, the RPC bearer token, the CLI, logging and crash reporting, and+the `CoreBuilder` runtime composition API. It holds no business logic: every+controller it exposes is implemented by a domain under+`crates/openhuman-core/src/<domain>/` and only wired in here.++Callers are the hosts above the core. The JSON-RPC server in+`crates/openhuman-rpc`, the `openhuman-core` binary in `crates/openhuman-cli`,+the desktop shell, the TUI and `openhuman-embed` all reach domain behavior+through the entry points in this folder.++## How it works++### The controller contract++A domain exposes an operation by building a `RegisteredController`: a+`ControllerSchema` (namespace, function, description, typed inputs and+outputs) paired with a `ControllerHandler`, which is a plain+`fn(Map<String, Value>) -> ControllerFuture`. The schema types+(`ControllerSchema`, `FieldSchema`, `TypeSchema`) live in `mod.rs`.+`TypeSchema` covers scalars, arrays, maps, options, string enums, nested+objects, named refs, and `BoundedU64` for fields backed by a narrower+integer type, so an out-of-range value is refused before dispatch.++Inside the handler, the domain's `ops.rs` returns an `Outcome<T>`+(`outcome.rs`): a value plus log lines. `Outcome::into_cli_compatible_json`+serializes it through `apply_log_envelope`, which is the single definition of+the wire shape. With no logs the value goes out bare; with logs it is wrapped+as `{ "result": value, "logs": [...] }`. That means a response's shape depends+on its log vector rather than its schema (issue #6080). The rule is kept+byte-for-byte on purpose, because changing it is a wire change for every+client. `unwrap_rpc` peels `result` and `data` envelopes back off.++Errors travel as `Err(String)`. When a controller needs a typed error, it+encodes a `StructuredRpcError` (`structured_error.rs`) into that string behind+the `STRUCTURED_RPC_ERROR_SENTINEL` prefix, and the transport decodes it. A+few surfaces (`threads`, desktop provider surfaces) wrap results in the+`{data, error, meta}` envelope built by `envelope.rs`.++### Registration++`all.rs` is the registry. `build_registered_controllers` calls every domain's+`all_*_registered_controllers()` and tags each batch with a `DomainGroup`+through the private `push` helper, so domain modules never see groups.+`build_internal_only_controllers` does the same for methods that are callable+over RPC but hidden from schema discovery and agent tool lists (desktop+control, the MCP write audit, the `modules` namespace). Both registries are+built lazily on first access, and `validate_registry` panics at that moment+on duplicate controllers, duplicate RPC method names, empty names, or+repeated required inputs.++Crates above the core add controllers at runtime through+`register_controller_extension(ControllerExtension { group, controllers,+namespaces })`. `openhuman-tinyhumans` uses it for the hosted backend proxies+(`DomainGroup::Hosted`) and `openhuman-rpc` uses it for the `http_host`+static file server. Extensions are validated against the union of the+built-in, internal and previously extended sets, re-registering an identical+set is a no-op, and the only ordering rule is to install before the first+dispatch of one of the extension's methods.++```text+ domain/schemas.rs host crates above core+ all_*_registered_controllers() register_controller_extension()+ | |+ v v+ +-----------------+ +------------------+ +------------++ | REGISTRY | | INTERNAL_REGISTRY| | EXTENSIONS |+ | (agent-visible) | | (RPC only) | | |+ +-----------------+ +------------------+ +------------++ \ | /+ +---- filtered by the ambient DomainSet ----++ |+ /schema, dispatch, agent tools+```++Every entry carries a `DomainGroup`: `Agent`, `Memory`, `Threads`, `Config`,+`Security`, `Flows`, `Skills`, `Mcp`, `Channels`, `Web3`, `Voice`, `Media`,+`Inference`, `Integrations`, `Automation`, `Runtimes`, `Desktop`, `Hosted`,+`Modules` and `Platform`. The variants track the family directories under+`crates/openhuman-core/src/`. The live surface (schema listing, dispatch,+agent tools, stores, subscribers) is filtered by whether the `DomainSet` of+the ambient `runtime::context::CoreContext` allows the group. With no context+yet (some unit tests), nothing is filtered. Adding a family directory means+adding a `DomainGroup` variant, a `DomainSet` field, an arm in+`DomainSet::allows()` and an entry in each preset; the compiler enforces all+four, and `DomainGroup::ALL`, `COUNT` and `index()` are pinned by a test.++Names come in two forms that must not be confused. `ControllerSchema::method_name`+gives the dotted key (`memory.doc_put`); `rpc_method_name` gives the wire+name (`openhuman.memory_doc_put`). RPC namespace strings are wire contracts+and do not follow directory renames.++### Dispatch++Every transport calls `invoke::invoke_method(state, method, params)`: the+`/rpc` handler and Socket.IO in `openhuman-rpc`, the CLI's `call` and+namespace commands, the device tunnel, and `CoreRuntime::invoke`.++```text+ invoke_method(method, params)+ |+ +-- schema_for_rpc_method(method) (built-in, internal, extensions)+ | found: params_to_object -> validate_params -> try_invoke_registered_rpc+ | | group disabled under DomainSet -> treated as unknown+ | | else run handler inside CoreContext::scope+ | v+ | result+ |+ +-- not found (or no handler): dispatch::dispatch+ | tier 0 legacy_aliases::resolve_legacy rewrites retired names+ | tier 1 core.ping, core.version, core.events_subscribe_token+ | tier 2 registry lookup again (catches rewritten names)+ | tier 3 Err("unknown method: <name>")+ |+ +-- on Err: is_session_expired_error?+ yes, backend credential -> BUS.publish(SessionExpired)+ yes, local credential -> BACKEND_UNAVAILABLE: error instead+ 401 that is not confirmed -> logged, session left alone+```++`validate_params` (in `all.rs`, with message builders and the matcher+`is_param_validation_error` in `params.rs`) rejects missing required params,+unknown params and values that do not match their declared `TypeSchema`, so+handlers only deserialize input that already passed the schema.++The `DomainSet` gate is enforced in `try_invoke_registered_rpc`, not in+schema lookup: a gated method answers exactly like an unregistered one. The+handler future is wrapped in `CoreContext::scope` and re-boxed as a+`ControllerFuture`; that type erasure keeps the `Send` solver from+overflowing on the largest handler futures, and together with the deep axum+and harness futures it is also why `lib.rs` sets+`#![recursion_limit = "256"]`.++Unknown methods always fail with the `UNKNOWN_METHOD_PREFIX` error. The+transport decides severity: names in `KNOWN_PROBE_METHODS` (generic probes+such as `rpc.discover`, and retired calls) stay debug-only, and anything else+is reported to Sentry at warn.++Session expiry is classified narrowly by `session_expiry.rs`. Only OpenHuman+backend failures (explicit "Session expired" text, the scheduler-gate+`SESSION_EXPIRED` sentinel, missing session guards, and 401s formatted as+`"{METHOD} /path failed (401 ...)"`) count. A provider's 401 does not, so a+broken BYOK key or Discord token never signs the user out.++### Event bus++`bus.rs` declares `BUS: OnceBus<DomainEvent>`, the process-wide `tinybus`+singleton. The bus implementation lives in the `tinybus` submodule; the core+keeps only the static, because `OnceBus<E>` is generic over the event type+and the host is the one that knows `E`. `events.rs` is the event catalog:+`DomainEvent`, a `#[non_exhaustive]` enum whose `domain()` value is appended+to `EVENTS_ROOT` (`/ai/tinyhumans/openhuman/events`) as the routing key.+The catalog is published under `EVENTS_INTERFACE`+(`ai.tinyhumans.openhuman.Events`) at `EVENTS_VERSION`, currently `1.8.0`.++`bus::init()` starts the in-process broker and announces a peer manifest+(advisory; failure only logs). Every accessor is safe before `init`:+publishing is a no-op logged at trace and subscribing returns `None`.+`TracingSubscriber` (`core::bus::tracing`) logs every event at debug.++Pick the surface by what the call carries:| Need | Use || --- | --- || tell anyone who cares that something happened | `BUS.publish` |-| call another module with a payload that is plain data | `BUS.publish` + a reply event, or a native request |+| call another module with a payload that is plain data | `BUS.publish` plus a reply event, or a native request || call another module passing `Arc`s, trait objects, or channels | `BUS.native()` || call an out-of-process integration | a `tinybus::Proxy` off `BUS.get()?.connection()` |-Adding an event requires four steps: add the variant to `DomainEvent`,-extend the `domain()` match, register its subscriber at startup, and bump-`EVENTS_VERSION` in `bus.rs`. Native request/response types must be-`Send + 'static` and never need serialization: they are the sanctioned-escape hatch for values (live channels, `Arc<dyn Tool>`) that cannot cross a-serialized transport.--Each subscribing domain owns a `bus.rs`; subscriber names use-`<domain>::<purpose>` (e.g. `health::registry`).--## RPC and HTTP transport--Every transport resolves a method through `invoke::invoke_method`, which checks-the registry schema, validates params-(`all::validate_params`, messages from `params.rs`), dispatches, and on a-confirmed session expiry publishes `DomainEvent::SessionExpired`.-`CoreRuntime::invoke` wraps it for embedders; the CLI's `call` subcommand-uses it directly.--The HTTP and Socket.IO server that exposes these methods lives in-`crates/openhuman-rpc` (`openhuman_rpc::server`): the axum router, `/rpc`,-`/health`, `/schema`, `/events`, `/oauth/mcp/callback`, the SSE streams, auth-middleware, CORS, Socket.IO and the listener bind. Host-owned `/auth` and-`/auth/telegram` callbacks are not served by this router. It mounts the-domain-owned HTTP handlers that stay here behind the `http-server` feature-(`inference::http`'s `/v1` router, the-dictation WebSocket in `voice::streaming`). `CoreRuntime` exposes the hooks-the server needs around a listener (`start_services`, `listener_bound`,-`serving_started`, `exit_cleanup`).--## Auth--`auth.rs` seeds the per-process RPC bearer through one of three paths, in-order of preference: an in-memory handoff from the Tauri shell-(`init_rpc_token_with_value`, never touches the process environment), the-`OPENHUMAN_CORE_TOKEN` env var (operator-supplied for Docker/cloud), or a-freshly generated token written to `{workspace_dir}/core.token`-(owner-read-only) for standalone CLI clients. Once set, the `OnceLock` is-the single source of truth for every transport: the HTTP auth middleware-in `openhuman-rpc`, Socket.IO, the SSE query-token fallback, and the approval-gate session id.-`event_bind_tokens.rs` mints the separate short-lived, single-shot tokens-`/events` needs because browser `EventSource` cannot send an `Authorization`-header.--## CLI--`cli.rs` is the CLI entry point (`run_from_cli_args`): it parses arguments,-prints the banner, resolves controller schemas grouped by namespace, and-dispatches through the same registry RPC uses. `agent_cli.rs`,-`memory_cli.rs`, and `subsystems_cli.rs` are domain-specific CLI subcommand-trees. `cli_capability.rs` is the one CLI-only exception to "degradation is-absence": over `/rpc` and in the agent tool list an unadvertised memory-capability family is simply unregistered, but the CLI keeps its subcommand-arm and reports the build/config fact (`capability_unavailable_message`:-which bound memory driver does not advertise which family) so a human does-not mistake silence for a typo. It resolves the binding itself because plain-CLI invocations never build a `CoreContext`, so the ambient gate would-answer "everything allowed".--`run` / `serve` start the JSON-RPC server through the launcher a host-installs in `server_launcher.rs` (`openhuman_rpc::server::install_cli_server`-in the `openhuman-core` binary and the desktop app); without one they fail-and say so.--## `runtime/` and `subsystem/`--`runtime/` is the embeddable composition API: `CoreBuilder` builds a-`CoreRuntime` in two phases (initialization, then serve); see-[runtime/README.md](runtime/README.md) for the full builder reference.-`AGENT_WORKER_STACK_BYTES` (20 MiB) and `MAX_BLOCKING_THREADS` (64) live in-`runtime/mod.rs`: a single agent turn is a very large async state machine,-and delegating to a sub-agent nests another one, which overflows tokio's-default 2 MiB worker stack; every multi-thread runtime that can host a turn-(the desktop shell, `openhuman-core run`, `agent_cli`) sets both constants.--`subsystem/` owns the generic `SubsystemStatus` wire row behind the `subsystems`-RPC namespace and the `openhuman subsystems` CLI table. Memory is the only-occupant: `crate::memory::status` projects the bound Memory v2 engine into its-row, and a later subsystem appends its own adapter call in-`subsystem::schemas::subsystems_status`.--## The controller contract--`Outcome<T>` (`outcome.rs`) is what every domain operation returns: a value-plus log lines, turned into JSON by `Outcome::into_cli_compatible_json`,-whose shape `apply_log_envelope` decides. `StructuredRpcError`-(`structured_error.rs`) is the typed error a controller can return through-its `Err(String)` channel, and `params.rs` defines the params shape and the-validation messages. They live in core so every domain and host shares one-definition; `crates/openhuman-rpc` depends on core for them.--## A note on `#![recursion_limit = "256"]`--`lib.rs` raises the crate's recursion limit because the RPC dispatch-chokepoint wraps each handler future in an ambient `CoreContext::scope`-(`runtime/context.rs`); combined with the already-deep async type stacks in-the Axum routes that fan out into the tinyagents harness, the extra future-layer pushes the compiler's `Send` auto-trait solver past the default depth.--## Notes / gotchas--- `bus::init()` binds the in-process broker's tokio tasks to whatever- runtime calls it first: a trap under `cargo test`, where every- `#[tokio::test]` builds its own runtime. Tests that need to observe events- should use `bus_testing::isolated_bus()` instead of the shared singleton.-- `HostKind::TauriShell` always installs the approval gate at boot and- ignores `OPENHUMAN_APPROVAL_GATE=0`; `Cli`, `Docker`, and `Library` honor- the env override (`types::approval_gate_boot_decision`).-- `KNOWN_PROBE_METHODS` in `dispatch.rs` silences recurring but harmless- unknown-method noise (generic RPC probes, retired calls) from Sentry.- `openhuman.harness_init_status` is on that list for client/core surface- skew only: it is a live, registered method, and a dedicated test pins- that fact so a real regression cannot go silent behind the allow-list.-- `http_server_status::HTTP_SERVER_COMPILED_IN` exists so a build without the- `http-server` feature fails loudly at compile time if the desktop shell- (which always needs a listener) tries to link it, rather than shipping- silently without one.+The native registry is in-process by design. Types such as+`AgentTurnRequest` carry `Arc<Vec<Box<dyn Tool>>>` and live progress channels+that cannot cross a serialized transport. Native request and response types+must be `Send + 'static` and need no serialization.++Adding an event takes four steps: add the variant to `DomainEvent`, extend+the `domain()` match, register its subscriber at startup, and bump+`EVENTS_VERSION`. Bump the minor for an added variant or field; for a change+an older subscriber cannot parse, bump the major and rename the interface.+Each subscribing domain owns a `bus.rs`, and subscriber names use+`<domain>::<purpose>`.++### Auth++`auth.rs` seeds the per-process RPC bearer into a `OnceLock`, choosing the+first available source:++1. an in-memory handoff from the desktop shell (`init_rpc_token_with_value`),+ which never touches the process environment;+2. the `OPENHUMAN_CORE_TOKEN` env var (`CORE_TOKEN_ENV_VAR`), for Docker and+ cloud operators;+3. a freshly generated token written owner-read-only to+ `{workspace_dir}/core.token` by `init_rpc_token`, for standalone CLI+ clients.++Once set, that value is what every transport checks: the HTTP middleware in+`openhuman_rpc::server::auth`, Socket.IO, the SSE query-token fallback, and+the approval-gate session id. `verify_bearer_token` and `bearer_matches` do+the comparison.++Browser `EventSource` cannot send an `Authorization` header, so `/events`+uses separate bind tokens from `event_bind_tokens.rs`. An authenticated+caller invokes `core.events_subscribe_token { client_id }` and then opens+`/events?client_id=<id>&token=<bind>`. A bind token is 256 random bits, tied+to one `client_id`, consumed on first use, and expires after 60 seconds by+default (30 minutes at most). The store caps at 4096 live tokens.++This is the RPC transport bearer only. User credentials (session JWT, API+key, offline local token) arrive through `auth.set_credential` in+`security::credentials`, not here.++### CLI++`cli::run_from_cli_args` is the entry point for the `openhuman-core` binary.+It loads `.env` (`load_dotenv_for_cli`), applies the process-local+`--provider` / `--model` overrides, prints the banner to stderr (except for+`mcp`, `mcp-server`, `tui` and `chat`, which keep stdout clean), and matches+the first argument:++| Subcommand | Behavior |+| --- | --- |+| `run`, `serve` | start the JSON-RPC server through the installed `ServerLauncher` |+| `mcp`, `mcp-server` | run the stdio MCP server (`mcp::server::run_stdio_from_cli`) |+| `tui`, `chat` | print a pointer to the separate `openhuman-tui` binary |+| `call --method <m> --params <json>` | one raw RPC call through `invoke_method` (`--params-stdin` reads params from stdin) |+| `agent dump-prompt / dump-all / prompt-size / list` | prompt inspection tools in `agent_cli.rs` |+| `sentry-test` | send a test event to Sentry |+| `<namespace> <function> [--flags]` | generic dispatcher over the registry schemas |++The generic dispatcher groups registered schemas by namespace, prints help+from their descriptions (`namespace_description` in `all.rs`), and turns+flags into params. A namespace with no function can fall through to a+standalone `RegisteredCliAdapter`: today `voice` (which stays registered with+the `voice` feature off and reports that voice is disabled) and `subsystems`+(`subsystems_cli.rs`, which prints the subsystem table). Wire new CLI+behavior through the registry; do not add namespace branches to `cli.rs` or+the JSON-RPC server.++`run` and `serve` need a server, which the core does not contain.+`server_launcher.rs` holds a `ServerLauncher` port; the host installs one+(`openhuman_rpc::server::install_cli_server()` in the `openhuman-core` binary+and the desktop app) before calling `run_from_cli_args`. Without it those+subcommands fail with an explanation.++### Logging, redaction and crash reporting++`logging.rs` sets up the logger per host: `init_for_cli_run`,+`init_for_embedded` and `init_for_tui` (which also buffers lines for the TUI+through `tui_log_lines`). Two redaction passes keep secrets out of logs.+`rpc_log::redact_params_for_log` strips sensitive keys (`api_key`, `token`,+`authorization`, `password`, `client_secret` and similar) from structured+params before the `[rpc:dispatch]` trace line. `log_redaction::scrub_secrets`+pattern-matches secrets in free text and is shared by the Sentry path and the+always-on log path, so the two cannot drift.++`observability.rs` is the error-reporting policy: `report_error`,+`report_error_or_expected` and `report_warning_message`, the expected-error+classifier (`expected_error_kind`), and the Sentry `before_send` predicates+that drop deterministic noise (transient provider HTTP statuses and transport+failures, updater blips, session expiry, max-iteration events). It also+defines the shared `BACKEND_UNAVAILABLE_PREFIX`. `sentry_transport.rs` is a+bounded, nonblocking Sentry transport over the core's reqwest stack, compiled+only with the `crash-reporting` feature.++`shutdown.rs` listens for SIGINT and SIGTERM (`signal`) and runs cleanup+hooks that domains `register`, sequentially in registration order.++### Runtime composition and subsystems++`runtime/` is the embeddable composition API. `CoreBuilder::build()` does+initialization only (controllers, master key, RPC bearer, workspace stores,+event subscribers) and returns a `CoreRuntime` that can already `invoke`+methods and run agent turns. Serving and background services come second,+through `openhuman_rpc::server::serve` or `CoreRuntime::start_services`.+`ServiceSet`, `DomainSet` and `ToolGroups` narrow what runs. See+[runtime/README.md](runtime/README.md) for the full reference.+`runtime/mod.rs` also holds `AGENT_WORKER_STACK_BYTES` (20 MiB) and+`MAX_BLOCKING_THREADS` (64). One agent turn is a very large async state+machine and a sub-agent nests another, which overflows tokio's default 2 MiB+worker stack, so every multi-thread runtime that can host a turn (the desktop+shell, `openhuman-core run`, `agent_cli`) sets both.++`subsystem/` serves the `subsystems` RPC namespace and its CLI table: one+`SubsystemStatus` row per kernel capability slot (class, health, contract+version, advertised capabilities). It is the one controller registered from+`core/` itself, tagged `DomainGroup::Platform`, because the subsystem table is+a kernel binding table like the controller registry. Memory is the only+occupant today; `crate::memory::status` builds its row, and a new subsystem+appends its adapter call in `subsystem::schemas::subsystems_status`.++## Layout++Contract and registry:++| Path | What it does |+| --- | --- |+| `mod.rs` | `ControllerSchema`, `FieldSchema`, `TypeSchema`; module declarations; re-exports `Outcome` and `StructuredRpcError`. |+| `outcome.rs` | `Outcome<T>`, `apply_log_envelope` (the one wire-shape rule) and `unwrap_rpc`. |+| `structured_error.rs` | `StructuredRpcError`, a typed error sentinel-encoded into a controller's `Err(String)`. |+| `envelope.rs` | `ApiEnvelope`, `ApiError`, `ApiMeta`, `PaginationMeta`: the `{data, error, meta}` shape some namespaces use. |+| `params.rs` | Params shape (`params_to_object`, `parse_json_params`), validation messages and `is_param_validation_error`. |+| `all.rs` | The registry: `RegisteredController`, `RegisteredCliAdapter`, `DomainGroup`, `ControllerExtension`, `register_controller_extension`, `validate_params`, `schema_for_rpc_method`, `try_invoke_registered_rpc`, `all_http_method_schemas` (adds `core.ping` and `core.version` for `/schema`), `namespace_description`. |+| `types.rs` | `AppState`, `HostKind`, `InvocationResult`, `approval_gate_boot_decision`. |++Dispatch and auth:++| Path | What it does |+| --- | --- |+| `invoke.rs` | `invoke_method` and `default_state`: the in-process entry point and the session-expiry hook. |+| `dispatch.rs` | `dispatch`: legacy rewrite, `core.*` methods, registry fallback, unknown-method handling, `KNOWN_PROBE_METHODS`. |+| `legacy_aliases.rs` | `resolve_legacy`: retired method names to canonical ones; mirrors `LEGACY_METHOD_ALIASES` in `app/src/services/rpcMethods.ts`. |+| `session_expiry.rs` | `is_session_expired_error` and `is_unconfirmed_unauthorized_error`. |+| `auth.rs` | The per-process RPC bearer: init paths, `get_rpc_token`, `verify_bearer_token`, `bearer_matches`. |+| `event_bind_tokens.rs` | Single-shot bind tokens for the `/events` SSE stream (`issue`, `consume`). |+| `server_launcher.rs` | `ServerLauncher` port that `run` / `serve` start a server through. |+| `http_server_status.rs` | `HTTP_SERVER_COMPILED_IN`, an ungated marker the desktop shell asserts so a core built without `http-server` fails the build. |++Bus:++| Path | What it does |+| --- | --- |+| `bus.rs` | `BUS`, `EVENTS_ROOT`, `EVENTS_INTERFACE`, `EVENTS_VERSION`, `init`, `manifest`, `TracingSubscriber`. |+| `events.rs` | `DomainEvent`, the full event catalog, and its `domain()` routing. |+| `bus_testing.rs` | Test helpers: `isolated_bus`, `BUS_HANDLER_LOCK`, `mock_bus_stub` and the RAII `MockBusGuard` for native stubs. |++CLI:++| Path | What it does |+| --- | --- |+| `cli.rs` | `run_from_cli_args`, launch flags, help output, `call` and the generic namespace dispatcher. |+| `agent_cli.rs` | `openhuman-core agent ...`: `dump-prompt`, `dump-all`, `prompt-size`, `list`. |+| `subsystems_cli.rs` | `run_subsystems_command`, the table printed by bare `openhuman-core subsystems`. |++Process plumbing:++| Path | What it does |+| --- | --- |+| `logging.rs` | Logger setup per host kind, log directory, file-guard shutdown. |+| `rpc_log.rs` | `redact_params_for_log`, key-name redaction for dispatch trace logs. |+| `log_redaction.rs` | `scrub_secrets`, pattern-based secret scrubbing for free-text log and Sentry messages. |+| `observability.rs` | Error reporting, expected-error classification, Sentry `before_send` filters, shared error prefixes. |+| `sentry_transport.rs` | Sentry transport over reqwest (`crash-reporting` feature). |+| `shutdown.rs` | SIGINT/SIGTERM signal and the registered shutdown hooks. |+| `runtime/` | `CoreBuilder`, `CoreRuntime`, `CoreContext`, `ServiceSet`, `DomainSet`, bootstrap and subscribers. See [runtime/README.md](runtime/README.md). |+| `subsystem/` | `SubsystemStatus` and the `subsystems` controller. |++## Key types and entry points++- `ControllerSchema` / `TypeSchema` (`mod.rs`): what a domain declares for each operation; drives validation, `/schema`, CLI help and agent tool schemas.+- `RegisteredController` (`all.rs`): schema plus handler, the unit every domain's `all_*_registered_controllers()` returns.+- `Outcome<T>` (`outcome.rs`): the return type of every domain operation.+- `StructuredRpcError` (`structured_error.rs`): a typed error through the string error channel.+- `invoke::invoke_method`: call any method in-process with validation and session-expiry handling.+- `all::register_controller_extension`: how a crate above the core adds a namespace.+- `BUS` and `DomainEvent` (`bus.rs`, `events.rs`): publish, subscribe and native requests.+- `auth::init_rpc_token` / `init_rpc_token_with_value`: seed the transport bearer.+- `cli::run_from_cli_args`: the CLI entry point a host binary calls.+- `HostKind` (`types.rs`): which host booted the core; affects approval-gate policy and log tags.+- `runtime::CoreBuilder`: compose a runtime for an embedding host.++## RPC / CLI surface++Methods handled directly in `dispatch.rs`, with no registry entry:++- `core.ping`: liveness, returns `{ "ok": true }`.+- `core.version`: the running core's version.+- `core.events_subscribe_token`: mint a bind token for `/events`.++Registered from `core/`:++- `openhuman.subsystems_status`: one `SubsystemStatus` row per kernel slot (CLI: `openhuman-core subsystems`).++Every other method belongs to a domain and is listed in that domain's README.+`GET /schema` on a running server and `openhuman-core --help` list the live+surface.++## Boundaries++- Business logic belongs in `crates/openhuman-core/src/<domain>/`. Do not add+ domain behavior or new namespaces to `core/`; register them in `all.rs`.+- The JSON-RPC 2.0 server (axum router, `/rpc`, `/health`, `/schema`,+ `/events`, `/oauth/mcp/callback`, auth middleware, CORS, Socket.IO,+ `/dev/connect`, listener bind, `run_server*`) lives in `crates/openhuman-rpc`.+ Core has no server and does not depend on that crate. Domain-owned HTTP+ handlers the router mounts (`inference::http`, the dictation WebSocket)+ stay in their domains behind core's `http-server` feature.+- The bus runtime, broker, native registry and proxies belong to the+ `tinybus` submodule (`vendor/tinybus`). Only the `BUS` static and the event+ catalog live here.+- Hosted backend proxies (`billing`, `team`, `referral`, `announcements`,+ `webhooks`, `channel_link`, `oauth`) are registered by+ `crates/openhuman-tinyhumans` as an extension, not built into the core.+- Login, token exchange and `/auth/me` belong to the host's session owner+ (`openhuman_tinyhumans::session`, `openhuman_embed::Auth`). Credential+ storage and `auth.set_credential` are in `security::credentials`.+- The CLI binary itself and its developer bins are in `crates/openhuman-cli`;+ this folder only provides the argument handling it calls.++## Gotchas++- `bus::init()` binds the broker's tokio tasks to whichever runtime calls it+ first. Under `cargo test` each `#[tokio::test]` has its own runtime, so the+ singleton can end up attached to a dead reactor. Tests that observe events+ should use `bus_testing::isolated_bus()`, and tests that stub native+ handlers should use `mock_bus_stub` under `BUS_HANDLER_LOCK`.+- `HostKind::TauriShell` always installs the approval gate and ignores+ `OPENHUMAN_APPROVAL_GATE=0`; `Cli`, `Docker` and `Library` honor it+ (`approval_gate_boot_decision`). `HostKind::detect_standalone` picks+ `Docker` from `/.dockerenv` or `OPENHUMAN_DOCKER=1`; the shell must pass+ `TauriShell` explicitly.+- `openhuman.harness_init_status` is in `KNOWN_PROBE_METHODS` because older+ cores, narrowed `DomainSet`s and slim builds legitimately lack it, not+ because it is retired. It is a live method, and a test pins that it is+ registered in a full build.+- `openhuman.auth_clear_session` is a legacy alias whose params get+ `kind: "session"` filled in during dispatch, preserving its session-only+ contract while the canonical method clears every kind by default.+- Registry lookups for validation and CLI routing search the full,+ unfiltered registry; only dispatch applies the `DomainSet` gate. A gated+ method therefore passes validation and then reports as unknown.+- The log-dependent response shape from `apply_log_envelope` is deliberate.+ Adding a log line to a handler that had none changes its wire shape.+- `http_server_status::HTTP_SERVER_COMPILED_IN` is ungated on purpose: the+ desktop shell asserts it, so a core built without `http-server` fails at+ compile time instead of shipping without a listener.++## Tests++Tests live beside their modules as `<module>_tests.rs` (`core_mod_tests.rs`+for `mod.rs`; the registry, observability and event catalog have several+split files). Run them with:++```bash+cargo test -p openhuman core::+pnpm debug rust core::+```## Related docs- [runtime/README.md](runtime/README.md)- [../security/README.md](../security/README.md)-- [../../../../gitbooks/developing/architecture.md](../../../../gitbooks/developing/architecture.md)+- [Architecture overview](../../../../gitbooks/developing/architecture.md)diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.mdindex 82a8df83ee..a89d13b63b 100644--- a/crates/openhuman-core/src/memory/README.md+++ b/crates/openhuman-core/src/memory/README.md@@ -28,7 +28,13 @@ the `[memory]` config into either `Binding::On(BoundEngine)` orThe core never keeps a TinyHumans credential of its own. The bearer isfetched from the host's credential seam (`resolve_backend_credential`) onevery request, so a refreshed session takes effect at once and signing out-turns memory off. Built engines are cached per config fingerprint (engine+turns memory off. The hosted engine does not go through the core's+`BackendTransport`: `engine.rs` hands TinyMemory's CortexDB client an+`EngineSettings` with the endpoint, the attribution headers from+`backend::attribution_headers` and an `EngineCredential::Dynamic(HostBearer)`,+and TinyMemory's own HTTP client calls the backend's `/memory/*` routes. The+`cortexdb` engine calls CortexDB directly with the stored key+(`EngineCredential::Static`). Built engines are cached per config fingerprint (engineid, endpoint, credential identity, layout), so a config change, a sign-in ora new key rebuilds the engine on the next call without any event plumbing.@@ -80,10 +86,13 @@ identity is never taken from model arguments.Under `[memory] layout = "v3"` everything sits below the signed-in person'sown scope root (`org:<id>`, `scope::user_root`), and every agent's chatsshare one chat node (`ws:main`, `scope::chat_node`), with the agent id kept-on each turn. A signed-out session gets a root of `user:local-<install id>`,-a random UUID minted once and recorded in `<workspace>/memory/local_root.json`-(`local_root.rs`). If that file cannot be written or read, the session has-no root and memory stays off.+on each turn. The person's actor is `user:<id>` (`scope::actor_of_root`),+which is also the retired root still read during the move while+`[memory] legacy_user_segment_read` is on. A signed-out session gets its+root from a random install id minted once and recorded in+`<workspace>/memory/local_root.json` as `user:local-<id>` (`local_root.rs`),+used as `org:local-<id>`. If that file cannot be written or read, the+session has no root and memory stays off.### Around every turn