Skip to content

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

chore: files changed crates/openhuman-core/src/core/runtime/builder.rs,crates/openhuman-core/src/age

Steven Enamakel418f7ffd293b
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs
new file mode 100644
index 0000000000..0bd1476b14
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_protocol.rs
@@ -0,0 +1,71 @@
+//! OpenHuman's memory-protocol wiring: the tool vocabulary handed to the
+//! upstream `MemoryProtocolMiddleware`
+//! (`tinyagents_harness::middleware::MemoryProtocolMiddleware`).
+//!
+//! Agents are told to follow a **read-index → dedupe → write → update-index**
+//! cycle around durable memory. The state machine, the corrective notes and the
+//! middleware live upstream; which OpenHuman tools play which role is host
+//! vocabulary and is defined here.
+
+use std::sync::Arc;
+
+use tinyagents_harness::middleware::{MemoryProtocolMiddleware, MemoryProtocolSpec, ModeTool};
+
+/// Build the OpenHuman tool vocabulary for the memory protocol.
+///
+/// - `update_memory_md` edits either `MEMORY.md` **or** `SKILL.md`
+/// (`tinytools_std::filesystem::UpdateMemoryMdTool`); only a `MEMORY.md` edit
+/// reconciles the memory index, so a `SKILL.md` edit must not close the cycle.
+/// - The consolidated `memory_tree` tool
+/// (`crates/openhuman-core/src/memory/query/mod.rs`) is a read in every `mode`
+/// except `ingest_document`, which writes a document into the tree.
+/// - `remember_preference` / `save_preference` (#4458) DO persist via
+/// `Memory::store`, but into dedicated preference namespaces
+/// (`pinned_preferences` / `user_pref_{general,situational}`) surfaced by
+/// direct system-prompt injection or per-query recall. They are NOT part of the
+/// `MEMORY.md` curated wiki the archivist reconciles, so they are deliberately
+/// unlisted (classified `Other`): treating them as writes would resurrect the
+/// unsatisfiable "call update_memory_md" nag loop that issue removed.
+pub fn memory_protocol_spec() -> Arc<MemoryProtocolSpec> {
+ Arc::new(MemoryProtocolSpec {
+ index_update_tool: "update_memory_md".into(),
+ index_file_arg: "file".into(),
+ index_file: "MEMORY.md".into(),
+ // Durable mutations: create an entry, delete an entry, or ingest a
+ // document into the memory tree (the split-out ingest tool).
+ write_tools: [
+ "memory_store",
+ "memory_forget",
+ "memory_tree_ingest_document",
+ ]
+ .map(String::from)
+ .to_vec(),
+ // Dedupe reads: recall/search over stored memory, or a read-only walk of
+ // the memory tree.
+ read_tools: [
+ "memory_recall",
+ "memory_vector_search",
+ "memory_chunk_context",
+ "memory_hybrid_search",
+ "memory_tree_query_source",
+ "memory_tree_search_entities",
+ "memory_tree_fetch_leaves",
+ "memory_tree_drill_down",
+ "memory_tree_cover_window",
+ ]
+ .map(String::from)
+ .to_vec(),
+ mode_tool: Some(ModeTool {
+ name: "memory_tree".into(),
+ mode_arg: "mode".into(),
+ write_mode: "ingest_document".into(),
+ }),
+ recall_tool: "memory_recall".into(),
+ })
+}
+
+/// The memory-protocol middleware for an OpenHuman turn. `can_update_index`
+/// states whether `update_memory_md` is actually available this turn.
+pub fn memory_protocol_middleware(can_update_index: bool) -> MemoryProtocolMiddleware {
+ MemoryProtocolMiddleware::with_index_update_tool(memory_protocol_spec(), can_update_index)
+}
diff --git a/crates/openhuman-core/src/config/migration_helpers/mod.rs b/crates/openhuman-core/src/config/migration_helpers/mod.rs
new file mode 100644
index 0000000000..baf655919b
--- /dev/null
+++ b/crates/openhuman-core/src/config/migration_helpers/mod.rs
@@ -0,0 +1,13 @@
+//! Data migration helpers for OpenHuman.
+
+mod core;
+pub mod ops;
+mod schemas;
+
+pub use core::*;
+pub use ops as rpc;
+pub use ops::*;
+pub use schemas::{
+ all_controller_schemas as all_migration_controller_schemas,
+ all_registered_controllers as all_migration_registered_controllers,
+};
diff --git a/crates/openhuman-core/src/core/runtime/builder.rs b/crates/openhuman-core/src/core/runtime/builder.rs
index 612fa43cae..185c78e299 100644
--- a/crates/openhuman-core/src/core/runtime/builder.rs
+++ b/crates/openhuman-core/src/core/runtime/builder.rs
@@ -1,192 +1,825 @@
-#!/usr/bin/env node
-
-import fs from "node:fs";
-import path from "node:path";
-
-const ROOT = "crates/openhuman-core/src";
-const CRATES_ROOT = "crates";
-const CORE_MANIFEST = "crates/openhuman-core/Cargo.toml";
-// Root `tests/*.rs` / `examples/*.rs` targets are declared by the CLI crate,
-// which hosts the binary and every integration suite; the core is a library.
-const CLI_MANIFEST = "crates/openhuman-cli/Cargo.toml";
-const LINE_LIMIT = 750;
-// Files past this size are reported (without failing) so an author sees the
-// margin in their own PR's log instead of a later PR turning `main` red.
-const WARN_AT = 725;
-
-// Files over `LINE_LIMIT` that still need semantic decomposition. Each pin is
-// the file's exact size and is a ratchet, enforced below: a file may not grow
-// past its pin, and a file that shrinks must lower its pin in the same change
-// (or drop the entry once it fits `LINE_LIMIT`), so recovered lines cannot be
-// spent again. No new exception can appear, and one file may be listed only
-// once (a Map keeps the last duplicate, which silently discards the other pin).
-const LEGACY_LIMIT_ENTRIES = [
- // These orchestration files crossed the general limit in the already-merged
- // runtime compatibility work. They are being split along semantic seams.
- // `spawn_async_subagent_execute.rs`: 847 -> 821 when the argument prologue
- // moved to `spawn_async_subagent_args.rs`, 821 -> 809 via
- // `AbortReport::deliver`. Still exempt because the rest of that function's
- // phases close over locals whose types are not nameable from this module
- // (see that fragment's header); taking it under 750 needs a visibility
- // change in `subagent_sessions`.
- [
- "crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",
- 799,
- ],
- // `spawn_subagent_tool_impl.rs` had its entry DELETED, not lowered: the
- // parameter schema moved to `spawn_subagent_parameters.rs` and the file is
- // under the general 750 limit, so it needs no exception at all.
- // The session-todo integration added transcript metadata construction to
- // this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1902],
- // Session-host factory still assembles the product's deliberately coupled
- // provider, security, memory, tool and prompt policy. Generic session
- // state moved to tinyagents-runtime; this remaining composition is split in
- // a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 1181],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1309],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1152],
- ["crates/openhuman-core/src/tools/ops.rs", 1209],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1304],
- // These established external test modules grew with upstream coverage. Pin
- // their current sizes while follow-up work separates their test concerns.
- // `core/` was pruned from the line limit by name until these pins; its
- // oversized files are pinned at the size they had when enforcement began.
- ["crates/openhuman-core/src/core/all.rs", 1840], 1494],
- ["crates/openhuman-core/src/core/all_tests.rs", 2501], 1635],
- ["crates/openhuman-core/src/core/events.rs", 2005], 1808],
- ["crates/openhuman-core/src/core/events_tests.rs", 1062], 1003],
- ["crates/openhuman-core/src/core/observability.rs", 3631], 3502],
- ["crates/openhuman-core/src/core/runtime/builder.rs", 825], 815],
-];
-const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);
-
-// Every Rust file under a directory, no exclusions. The line limit applies to
-// every file under `ROOT` (an oversized file is pinned in
-// `LEGACY_LIMIT_ENTRIES`, never skipped); the naming and inline-test-module
-// checks apply to every crate.
-function allRustFiles(directory) {
- return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
- const file = path.join(directory, entry.name);
- if (entry.isDirectory()) {
- if (entry.name === "target") return [];
- return allRustFiles(file);
- }
- return entry.isFile() && entry.name.endsWith(".rs") ? [file] : [];
- });
-}
+//! `CoreBuilder` → `CoreRuntime`: the embeddable composition surface.
+//!
+//! This is the first-class library API for hosting the OpenHuman core. It
+//! splits the monolithic `run_server_inner` into two phases:
+//!
+//! 1. [`CoreBuilder::build`] — *initialization only*: register controllers, load
+//! the master key, seed the RPC bearer, initialize workspace-bound stores,
+//! and run the pure-registration part of [`bootstrap_core_runtime`]. No port
+//! is bound and `ServiceSet::none` / `ServiceSet::headless_api` start no
+//! background loops. After `build`, [`CoreRuntime::invoke`] can dispatch any
+//! RPC method in-process, and agent turns can run — so a harness-only embedder
+//! (`ServiceSet::none`) needs nothing more.
+//! 2. *Transport + background services*: `openhuman_rpc::server::serve` binds
+//! the HTTP listener, mounts the router, fires the readiness signal, calls
+//! [`CoreRuntime::start_services`], and serves until shutdown. A runtime
+//! with no transport calls `start_services` itself.
+//!
+//! The server entry points in `openhuman-rpc` (`run_server`,
+//! `run_server_embedded`, `run_server_embedded_with_ready`) are thin shims over
+//! this builder, so the desktop shell, the standalone CLI, and any new embedder
+//! share one path.
+//! See the pluggable-core work (`core::runtime`) for how this fits with
+//! [`context`](crate::core::runtime::context) and `services`.
+
+use std::sync::Arc;
+
+use crate::config::Config;
+use crate::core::all::DomainGroup;
+use crate::core::runtime::context::CoreContext;
+use crate::core::types::HostKind;
-const INLINE_TEST_MODULE_RE =
- /^\s*#\[cfg\([^\n]*\btest\b[^\n]*\)\]\s*\n(?:\s*#\[[^\n]+\]\s*\n)*\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*\{/m;
-
-const failures = [];
-const warnings = [];
-for (const file of allRustFiles(ROOT)) {
- const source = fs.readFileSync(file, "utf8");
- const lineCount = source.split("\n").length - (source.endsWith("\n") ? 1 : 0);
- const portableFile = file.split(path.sep).join("/");
- const legacyLimit = LEGACY_LIMITS.get(portableFile);
- if (lineCount > (legacyLimit ?? LINE_LIMIT)) {
- failures.push(
- `${file}: ${lineCount} lines (limit ${legacyLimit ?? LINE_LIMIT})`,
- );
- } else if (legacyLimit !== undefined && lineCount < legacyLimit) {
- failures.push(
- lineCount <= LINE_LIMIT
- ? `${file}: ${lineCount} lines now fits the ${LINE_LIMIT}-line limit; remove its legacy exception`
- : `${file}: ${lineCount} lines, below its legacy pin ${legacyLimit}; lower the pin to ${lineCount}`,
- );
- } else if (legacyLimit === undefined && lineCount > WARN_AT) {
- warnings.push(
- `${file}: ${lineCount} lines, ${LINE_LIMIT - lineCount} below the ${LINE_LIMIT}-line limit`,
- );
- }
+/// Selects which background services and transports a [`CoreRuntime`] runs.
+///
+/// Each flag is independent. Presets cover the common hosts:
+/// [`ServiceSet::desktop`] (everything — the Tauri shell / standalone CLI),
+/// [`ServiceSet::headless_api`] (HTTP JSON-RPC only — single-core cloud), and
+/// [`ServiceSet::none`] (no transport, no background work — library / harness).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ServiceSet {
+ /// Bind the axum HTTP server and serve `POST /rpc` (+ the other core routes).
+ pub rpc_http: bool,
+ /// Mount the Socket.IO realtime layer on the HTTP server (requires `rpc_http`).
+ pub socketio: bool,
+ /// Spawn the cron scheduler (still gated at runtime by `config.cron.enabled`).
+ pub cron: bool,
+ /// Spawn realtime channel listeners (Telegram, Discord, …).
+ pub channels: bool,
+ /// Spawn login-gated services (local AI, voice, autocomplete).
+ pub login_gated: bool,
+ /// Spawn the periodic self-update checker.
+ pub update_scheduler: bool,
+ /// Start memory queue workers during runtime bootstrap.
+ pub memory_queue: bool,
+ /// Run one-shot harness initialization during runtime bootstrap.
+ pub harness_init: bool,
+ /// Refresh the skill catalog during runtime bootstrap.
+ pub skill_catalog_refresh: bool,
+ /// Boot installed MCP servers and supervise reconnects during runtime bootstrap.
+ pub mcp_boot: bool,
+ /// Composio integration sync: periodic connection sync + one-shot memory-source reconcile.
+ pub integrations: bool,
+ /// Workspace memory-source periodic sync — repos, folders, RSS, web pages.
+ pub memory_sync: bool,
}
-for (const file of allRustFiles(CRATES_ROOT)) {
- const source = fs.readFileSync(file, "utf8");
- if (
- ["tests.rs", "test.rs"].includes(path.basename(file)) ||
- path.basename(file).endsWith("_test.rs")
- ) {
- failures.push(
- `${file}: test modules must use a descriptive *_tests.rs filename`,
- );
- }
- if (INLINE_TEST_MODULE_RE.test(source)) {
- failures.push(
- `${file}: inline test module; move it to a sibling *_tests.rs file`,
- );
- }
+impl ServiceSet {
+ /// Everything on — the desktop shell and the standalone `openhuman-core run`.
+ pub fn desktop() -> Self {
+ Self {
+ rpc_http: true,
+ socketio: true,
+ cron: true,
+ channels: true,
+ login_gated: true,
+ update_scheduler: true,
+ memory_queue: true,
+ harness_init: true,
+ skill_catalog_refresh: true,
+ mcp_boot: true,
+ integrations: true,
+ memory_sync: true,
+ }
+ }
+
+ /// HTTP JSON-RPC only — a single-core cloud/server deployment. No Socket.IO,
+ /// no cron/channels/login-gated services; the supervisor decides those per plan.
+ pub fn headless_api() -> Self {
+ Self {
+ rpc_http: true,
+ socketio: false,
+ cron: false,
+ channels: false,
+ login_gated: false,
+ update_scheduler: false,
+ memory_queue: false,
+ harness_init: false,
+ skill_catalog_refresh: false,
+ mcp_boot: false,
+ integrations: false,
+ memory_sync: false,
+ }
+ }
+
+ /// No transport and no background services — for library / harness embedders
+ /// that only drive the core through [`CoreRuntime::invoke`] and agent turns.
+ pub fn none() -> Self {
+ Self {
+ rpc_http: false,
+ socketio: false,
+ cron: false,
+ channels: false,
+ login_gated: false,
+ update_scheduler: false,
+ memory_queue: false,
+ harness_init: false,
+ skill_catalog_refresh: false,
+ mcp_boot: false,
+ integrations: false,
+ memory_sync: false,
+ }
+ }
+
+ /// A long-lived embedded host: no transport, but the background work such
+ /// a session expects.
+ ///
+ /// Named for the shape, not a consumer — see [`DomainSet::embedded`].
+ ///
+ /// `rpc_http: false` is the payoff of embedding through the typed facade
+ /// rather than HTTP — no port bound, no bearer-token handshake, no
+ /// loopback listener. Flip it on only if the host also needs to serve external clients.
+ ///
+ /// `socketio` stays off because an embedded host reads state through the
+ /// facade and the core event bus in-process; `channels` stays off because
+ /// such a host owns its own harness and networking transports.
+ pub fn embedded() -> Self {
+ Self {
+ rpc_http: false,
+ socketio: false,
+ cron: true,
+ channels: false,
+ login_gated: true,
+ update_scheduler: false,
+ memory_queue: true,
+ harness_init: true,
+ skill_catalog_refresh: true,
+ mcp_boot: false,
+ integrations: false,
+ memory_sync: true,
+ }
+ }
}
-// A Map silently keeps the last of two entries for one file, so a duplicate
-// hides whichever pin was written first.
-const seenLegacy = new Set();
-for (const [file] of LEGACY_LIMIT_ENTRIES) {
- if (seenLegacy.has(file))
- failures.push(`${file}: duplicate legacy exception; keep one entry`);
- seenLegacy.add(file);
+/// Selects which domain *families* exist at runtime on a [`CoreRuntime`] (#4796).
+///
+/// Sibling of [`ServiceSet`]: where `ServiceSet` selects background services and
+/// transports, `DomainSet` selects which controller/tool/store/subscriber
+/// surfaces are live. Each flag is an independent [`DomainGroup`]; presets cover
+/// the common hosts:
+/// [`DomainSet::full`] (every family — today's behavior, the default),
+/// [`DomainSet::harness`] (agent + memory + threads + config + security only —
+/// the embeddable agent core used by `examples/embed_headless.rs`), and
+/// [`DomainSet::none`] (all domain families disabled; transport built-ins and
+/// always-on core infrastructure still run).
+///
+/// `full()` is byte-identical to pre-#4796 registration, so the desktop shell
+/// and standalone CLI are unchanged. Per-gate Cargo `[features]` (children
+/// #4797–#4804) narrow the *compile-time* surface further; this struct is the
+/// *runtime* axis they compose with.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DomainSet {
+ /// Agent definition/registry/experience, orchestration, session DB/import.
+ pub agent: bool,
+ /// Documents, knowledge graph, memory tree/sources/sync/diff/goals.
+ pub memory: bool,
+ /// Conversation threads, per-thread goals, todos.
+ pub threads: bool,
+ /// Persisted runtime configuration.
+ pub config: bool,
+ /// Encryption, keyring consent, security policy, approval, plan-review.
+ pub security: bool,
+ /// Saved automation workflows (tinyflows graphs).
+ pub flows: bool,
+ /// SKILL.md skills, skill runtime, skill registry.
+ pub skills: bool,
+ /// MCP client subsystem (Smithery registry, local servers, audit).
+ pub mcp: bool,
+ /// Messaging channels + webview bridges (web channel, whatsapp data, …).
+ pub channels: bool,
+ /// Wallet, high-level web3 surface, x402 machine payments.
+ pub web3: bool,
+ /// Speech-to-text / text-to-speech, audio toolkit.
+ pub voice: bool,
+ /// Image/video media generation. NOTE: today this gates only the
+ /// `media_generate_*` **agent tools** — no controller/store/subscriber is
+ /// tagged `Media` (there is no `media` RPC namespace yet), so a custom set
+ /// with `media: false, platform: true` drops the media tools while any
+ /// future backing controller would stay live. Fold the media-generation
+ /// controller into this group when it lands.
+ pub media: bool,
+ /// Model inference: providers, routing, local engines, embeddings.
+ pub inference: bool,
+ /// External connectors (Composio, calendar, file storage, task sources).
+ pub integrations: bool,
+ /// Background initiative: scheduled cron jobs.
+ pub automation: bool,
+ /// Code-execution substrate: Node/Python runtimes, pool, sandbox.
+ pub runtimes: bool,
+ /// Desktop-shell-facing surfaces.
+ pub desktop: bool,
+ /// Clients of the hosted TinyHumans backend.
+ pub hosted: bool,
+ /// Loadable native modules: the module host, registry and `modules` RPC.
+ pub modules: bool,
+ /// Everything not in a named family — always on in `full()`.
+ pub platform: bool,
}
-for (const file of LEGACY_LIMITS.keys()) {
- if (!fs.existsSync(file))
- failures.push(`${file}: stale legacy exception; remove it from the gate`);
+impl DomainSet {
+ /// Every family on — today's behavior and the [`CoreBuilder`] default.
+ /// Registration is byte-identical to pre-#4796.
+ pub fn full() -> Self {
+ Self {
+ agent: true,
+ memory: true,
+ threads: true,
+ config: true,
+ security: true,
+ flows: true,
+ skills: true,
+ mcp: true,
+ channels: true,
+ web3: true,
+ voice: true,
+ media: true,
+ inference: true,
+ integrations: true,
+ automation: true,
+ runtimes: true,
+ desktop: true,
+ hosted: true,
+ modules: true,
+ platform: true,
+ }
+ }
+
+ /// The embeddable agent core: agent + memory + threads + config + security.
+ /// Every gate family AND `platform` are off. Used by
+ /// `examples/embed_headless.rs`.
+ pub fn harness() -> Self {
+ Self {
+ agent: true,
+ memory: true,
+ threads: true,
+ config: true,
+ security: true,
+ flows: false,
+ skills: false,
+ mcp: false,
+ channels: false,
+ web3: false,
+ voice: false,
+ media: false,
+ inference: false,
+ integrations: false,
+ automation: false,
+ runtimes: false,
+ desktop: false,
+ hosted: false,
+ modules: false,
+ platform: false,
+ }
+ }
+
+ /// A long-lived embedded host: the harness core plus the workflow engine
+ /// and the supporting
+ /// runtime, automation, integration, and platform surfaces it needs.
+ ///
+ /// Named for the *shape* rather than any downstream consumer — the core
+ /// does not know which host embeds it, and a preset naming one would invert
+ /// that. Suits any process that drives the core in-process through the
+ /// typed facade and owns its own presentation layer.
+ ///
+ /// Deliberately NOT built on [`DomainSet::harness`]: that preset sets
+ /// `platform: false`, which drops credentials, config, cron, task_sources
+ /// and todos, and leaves `channels` off — but `channel.web_chat` is tagged
+ /// `DomainGroup::Channels` and an embedded host drives chat turns through it.
+ ///
+ /// `flows: true` keeps the tinyflows engine and boot reconciliation on;
+ /// reconciliation keys off
+ /// `ctx.domains().flows` rather than a `ServiceSet` flag.
+ ///
+ /// An embedded host supplies its own harness wrappers, networking and
+ /// routing, so `web3` / `voice` / `media` / `mcp` stay off.
+ pub fn embedded() -> Self {
+ Self {
+ agent: true,
+ memory: true,
+ threads: true,
+ config: true,
+ security: true,
+ flows: true,
+ skills: true,
+ mcp: false,
+ channels: true,
+ web3: false,
+ voice: false,
+ media: false,
+ inference: true,
+ integrations: true,
+ automation: true,
+ runtimes: true,
+ desktop: false,
+ hosted: false,
+ modules: false,
+ platform: true,
+ }
+ }
+
+ /// The kernel floor: threads, config, security — and nothing else.
+ ///
+ /// Distinct from [`DomainSet::none`], which is "no domains at all". This is
+ /// "the minimum a host needs before opting a subsystem back in", so an
+ /// embedder can request kernel + exactly one family. `agent` and `memory`
+ /// are OFF on purpose: they are the two largest subsystems and the ones an
+ /// alternative driver would replace, so a host that wants them says so.
+ ///
+ /// See `examples/embed_kernel.rs`.
+ pub fn kernel() -> Self {
+ Self {
+ agent: false,
+ memory: false,
+ threads: true,
+ config: true,
+ security: true,
+ flows: false,
+ skills: false,
+ mcp: false,
+ channels: false,
+ web3: false,
+ voice: false,
+ media: false,
+ inference: false,
+ integrations: false,
+ automation: false,
+ runtimes: false,
+ desktop: false,
+ hosted: false,
+ modules: false,
+ platform: false,
+ }
+ }
+
+ /// Nothing on — every family disabled.
+ pub fn none() -> Self {
+ Self {
+ agent: false,
+ memory: false,
+ threads: false,
+ config: false,
+ security: false,
+ flows: false,
+ skills: false,
+ mcp: false,
+ channels: false,
+ web3: false,
+ voice: false,
+ media: false,
+ inference: false,
+ integrations: false,
+ automation: false,
+ runtimes: false,
+ desktop: false,
+ hosted: false,
+ modules: false,
+ platform: false,
+ }
+ }
+
+ /// Whether the given [`DomainGroup`] is enabled in this set.
+ pub fn allows(&self, group: DomainGroup) -> bool {
+ match group {
+ DomainGroup::Agent => self.agent,
+ DomainGroup::Memory => self.memory,
+ DomainGroup::Threads => self.threads,
+ DomainGroup::Config => self.config,
+ DomainGroup::Security => self.security,
+ DomainGroup::Flows => self.flows,
+ DomainGroup::Skills => self.skills,
+ DomainGroup::Mcp => self.mcp,
+ DomainGroup::Channels => self.channels,
+ DomainGroup::Web3 => self.web3,
+ DomainGroup::Voice => self.voice,
+ DomainGroup::Media => self.media,
+ DomainGroup::Inference => self.inference,
+ DomainGroup::Integrations => self.integrations,
+ DomainGroup::Automation => self.automation,
+ DomainGroup::Runtimes => self.runtimes,
+ DomainGroup::Desktop => self.desktop,
+ DomainGroup::Hosted => self.hosted,
+ DomainGroup::Modules => self.modules,
+ DomainGroup::Platform => self.platform,
+ }
+ }
+
+ /// Field-wise AND with `other`: a family is on in the result only if it
+ /// was on in both.
+ ///
+ /// Used to clamp a derived context's requested domains to what the
+ /// parent context actually registered — see
+ /// [`CoreContext::derive_with`](crate::core::runtime::CoreContext::derive_with).
+ /// A derived overlay is meant to *narrow* the parent, never state a
+ /// family the parent never registered back into existence.
+ #[must_use]
+ pub fn intersect(&self, other: &DomainSet) -> DomainSet {
+ DomainSet {
+ agent: self.agent && other.agent,
+ memory: self.memory && other.memory,
+ threads: self.threads && other.threads,
+ config: self.config && other.config,
+ security: self.security && other.security,
+ flows: self.flows && other.flows,
+ skills: self.skills && other.skills,
+ mcp: self.mcp && other.mcp,
+ channels: self.channels && other.channels,
+ web3: self.web3 && other.web3,
+ voice: self.voice && other.voice,
+ media: self.media && other.media,
+ inference: self.inference && other.inference,
+ integrations: self.integrations && other.integrations,
+ automation: self.automation && other.automation,
+ runtimes: self.runtimes && other.runtimes,
+ desktop: self.desktop && other.desktop,
+ hosted: self.hosted && other.hosted,
+ modules: self.modules && other.modules,
+ platform: self.platform && other.platform,
+ }
+ }
}
-// Integration tests and examples remain repository-level for now, so Cargo
-// cannot auto-discover them. Keep the explicit target list
-// exhaustive: otherwise adding a file can make `cargo test` silently run
-// nothing for it while still exiting successfully.
-const manifest = fs.readFileSync(CLI_MANIFEST, "utf8");
-const coreManifest = fs.readFileSync(CORE_MANIFEST, "utf8");
-for (const table of ["bin", "test", "example"]) {
- if (coreManifest.includes(`[[${table}]]`))
- failures.push(
- `${CORE_MANIFEST}: [[${table}]] target declared in the library crate; it belongs in ${CLI_MANIFEST}`,
- );
+/// How the per-process RPC bearer token is seeded.
+pub enum TokenSource {
+ /// An in-memory bearer supplied by the embedder (the Tauri shell hands its
+ /// `CoreProcessHandle.rpc_token` this way). Seeded via
+ /// [`crate::core::auth::init_rpc_token_with_value`] — never crosses the
+ /// process environment.
+ Fixed(Arc<String>),
+ /// Standalone fallback: read `OPENHUMAN_CORE_TOKEN` from the environment when
+ /// present (operator config), otherwise generate a fresh token and write
+ /// `{root}/core.token` (0o600 on Unix) so CLI callers can authenticate.
+ EnvOrFile,
}
-function declaredTargets(table) {
- const targets = new Set();
- for (const block of manifest.split(`[[${table}]]`).slice(1)) {
- const name = block.match(/^name\s*=\s*"([^"]+)"/m)?.[1];
- if (name) targets.add(name);
- }
- return targets;
+
+/// Builder for a [`CoreRuntime`]. Construct with [`CoreBuilder::new`], then
+/// [`CoreBuilder::build`] to initialize the core.
+pub struct CoreBuilder {
+ host_kind: HostKind,
+ token: TokenSource,
+ services: ServiceSet,
+ domains: DomainSet,
+ tool_groups: crate::tools::toolpacks::ToolGroups,
+ host: Option<String>,
+ port: Option<u16>,
+ config: Option<crate::config::Config>,
+ backend_transport: Option<std::sync::Arc<dyn crate::backend::transport::BackendTransport>>,
}
-for (const [directory, table] of [
- ["tests", "test"],
- ["examples", "example"],
-]) {
- const files = new Set(
- fs
- .readdirSync(directory)
- .filter((name) => name.endsWith(".rs"))
- .map((name) => name.slice(0, -3)),
- );
- const declared = declaredTargets(table);
- for (const name of files) {
- if (!declared.has(name))
- failures.push(`${directory}/${name}.rs: missing [[${table}]] entry in ${CLI_MANIFEST}`);
- }
- for (const name of declared) {
- if (!files.has(name))
- failures.push(`${CLI_MANIFEST}: stale [[${table}]] target ${name}`);
- }
+impl CoreBuilder {
+ /// Start a builder for the given host kind. Defaults: [`TokenSource::EnvOrFile`],
+ /// [`ServiceSet::desktop`], and [`DomainSet::full`].
+ pub fn new(host_kind: HostKind) -> Self {
+ Self {
+ host_kind,
+ token: TokenSource::EnvOrFile,
+ services: ServiceSet::desktop(),
+ domains: DomainSet::full(),
+ tool_groups: Default::default(),
+ host: None,
+ port: None,
+ config: None,
+ backend_transport: None,
+ }
+ }
+
+ /// Bind the transport this core's handlers reach the hosted TinyHumans
+ /// backend through (see [`crate::backend::transport`]).
+ ///
+ /// Optional: without it the core resolves the process-global transport
+ /// installed with
+ /// [`install_backend_transport`](crate::backend::transport::install_backend_transport),
+ /// and with neither every backend-touching call degrades to a typed
+ /// "backend unavailable" error while agents, memory, tools and RPC keep
+ /// working. Library hosts that build one runtime per process prefer this
+ /// builder form; the desktop shell and CLI, which boot the core through
+ /// `run_server_embedded_with_ready` / `run_core_from_args`, install the
+ /// global.
+ pub fn backend_transport(
+ mut self,
+ transport: std::sync::Arc<dyn crate::backend::transport::BackendTransport>,
+ ) -> Self {
+ self.backend_transport = Some(transport);
+ self
+ }
+
+ /// Choose which background services and transports this runtime runs.
+ pub fn services(mut self, services: ServiceSet) -> Self {
+ self.services = services;
+ self
+ }
+
+ /// Choose which domain families exist at runtime (default [`DomainSet::full`]).
+ /// `harness()` builds the embeddable agent core; `none()` disables every
+ /// domain family while retaining transport built-ins and core infrastructure.
+ pub fn domains(mut self, domains: DomainSet) -> Self {
+ self.domains = domains;
+ self
+ }
+
+ /// Choose how each tool group reaches the model (default: every group
+ /// withheld behind `use_skill`, the desktop app's shape).
+ ///
+ /// The third narrowing axis, independent of both `services` and `domains`:
+ /// `ServiceSet` picks the background services, `DomainSet` picks which
+ /// families exist, and this picks how the tools of the families that do
+ /// exist are disclosed — advertised on the wire, withheld behind the pack
+ /// proxy, or not registered at all.
+ ///
+ /// ```no_run
+ /// # use openhuman_core::core::runtime::CoreBuilder;
+ /// # use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};
+ /// # fn f(b: CoreBuilder) -> CoreBuilder {
+ /// b.tool_groups(
+ /// ToolGroups::none()
+ /// .with("documents", GroupMode::Advertised)
+ /// .with("workflows", GroupMode::Withheld),
+ /// )
+ /// # }
+ /// ```
+ ///
+ /// Narrowing only: a group set to `Advertised` whose tools are compiled
+ /// out, or whose `DomainGroup` is off under `domains`, stays absent.
+ pub fn tool_groups(mut self, tool_groups: crate::tools::toolpacks::ToolGroups) -> Self {
+ self.tool_groups = tool_groups;
+ self
+ }
+
+ /// Choose how the RPC bearer token is seeded.
+ pub fn token(mut self, token: TokenSource) -> Self {
+ self.token = token;
+ self
+ }
+
+ /// Override the bind host (default: `OPENHUMAN_CORE_HOST` env or `127.0.0.1`).
+ pub fn host(mut self, host: impl Into<String>) -> Self {
+ self.host = Some(host.into());
+ self
+ }
+
+ /// Override the bind port (default: `OPENHUMAN_CORE_PORT` env or `7788`).
+ pub fn port(mut self, port: u16) -> Self {
+ self.port = Some(port);
+ self
+ }
+
+ /// Supply the [`Config`](crate::config::Config) outright instead
+ /// of letting `build()` discover one from `config.toml` and the environment.
+ ///
+ /// Without this an embedder can only configure the core by setting
+ /// environment variables before `build()` — process-global, order-dependent
+ /// relative to a call it does not appear in, and silently wrong if a later
+ /// caller in the same process wants different values. With it, every knob
+ /// the core reads from config (workspace, action dir, autonomy tier, MCP
+ /// servers, provider routes) is an ordinary struct field.
+ ///
+ /// The config is used **verbatim**: no `config.toml` read and no env
+ /// overlay. Call
+ /// [`apply_env_overrides`](crate::config::Config::apply_env_overrides)
+ /// yourself first if you want the environment to participate.
+ pub fn config(mut self, config: crate::config::Config) -> Self {
+ self.config = Some(config);
+ self
+ }
+
+ /// Root the core's state at `dir` — sessions, memory, attachments, skills.
+ ///
+ /// Sugar over [`config`](Self::config) for the common case of "same
+ /// configuration, different workspace"; starts from the config already
+ /// supplied, or [`Config::default`](Default::default) when none is.
+ pub fn workspace(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
+ let dir = dir.into();
+ let mut config = self.config.take().unwrap_or_default();
+ config.workspace_dir = dir.clone();
+ // Credential profiles and the file-backed keyring resolve from
+ // `config_path`'s parent, not from `workspace_dir`. Rooting only the
+ // workspace while leaving the default config path would keep sessions
+ // and credentials in the previous config root even though this method
+ // documents `dir` as rooting "core state" — so set a deterministic
+ // config path beside the workspace, mirroring the harness's `Dir`
+ // layout (`<root>/config.toml` next to `<root>/workspace`).
+ config.config_path = dir.join("config.toml");
+ self.config = Some(config);
+ self
+ }
+
+ /// Set the agent's read/write root for acting tools (`action_dir`).
+ ///
+ /// Sugar over [`config`](Self::config), like [`workspace`](Self::workspace).
+ /// Distinct from the workspace on purpose: the workspace holds internal
+ /// state the agent must never write to, and `is_workspace_internal_path`
+ /// enforces that separation fail-closed.
+ pub fn action_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
+ let mut config = self.config.take().unwrap_or_default();
+ config.action_dir = dir.into();
+ self.config = Some(config);
+ self
+ }
+
+ /// Point the core's backend calls at `url` (`Config::api_url`).
+ ///
+ /// Sugar over [`config`](Self::config), like [`workspace`](Self::workspace).
+ /// Worth having as its own method because the value reaches more than the
+ /// obvious client: `/auth/me` session validation, the hosted-backend
+ /// surfaces all resolve through it. A host that sets only one of
+ /// those has the other two pointing at a different deployment, which fails
+ /// as "backend rejected session token" rather than as a mismatch.
+ pub fn backend_url(mut self, url: impl Into<String>) -> Self {
+ let mut config = self.config.take().unwrap_or_default();
+ config.api_url = Some(url.into());
+ self.config = Some(config);
+ self
+ }
+
+ /// Initialize the core: register controllers, load the master key, seed the
+ /// RPC bearer, initialize workspace-bound stores, and run
+ /// [`bootstrap_core_runtime`]. Binds no port and starts no transport.
+ ///
+ /// The init sequence itself is owned by [`CoreContext::init`] (Phase 2,
+ /// Stage A).
+ pub async fn build(self) -> anyhow::Result<CoreRuntime> {
+ let (ctx, has_operator_token, config) = CoreContext::init_with_config(
+ self.host_kind,
+ &self.token,
+ self.domains,
+ self.tool_groups.clone(),
+ self.config,
+ self.backend_transport,
+ )
+ .await?;
+
+ // Retired scheduled jobs must be pruned before `build()` exposes
+ // in-process RPC or agent turns. Running this from `serve()` is too
+ // late for embedders that only build and invoke.
+ if let Some(cfg) = config.as_ref() {
+ crate::core::runtime::services::run_legacy_migrations(cfg).await;
+ }
+
+ // Reap agent runs orphaned by a previous process (crash / restart /
+ // deploy). Here, and not with the other boot-once jobs, because those
+ // run from `serve()`: an embedder that only calls `build()` and then
+ // `invoke()` never reaches them, and `openhuman.agent_runs_active` is
+ // dispatchable the moment this returns. The core is a single in-process
+ // runtime, so a run left Pending/Running/Interrupted in the durable
+ // status store has no executor to advance it and would be listed as
+ // active forever. Best-effort — a store that cannot be read logs and
+ // reaps nothing rather than failing the build.
+ if let Some(cfg) = config.as_ref() {
+ crate::agent::tinyagents::reaper::reap_orphaned_runs(&cfg.workspace_dir).await;
+ }
+
+ Ok(CoreRuntime {
+ ctx,
+ config,
+ services: self.services,
+ has_operator_token,
+ host: self.host,
+ port: self.port,
+ })
+ }
}
-if (warnings.length) {
- console.warn("OpenHuman Rust layout check: files near the line limit:");
- warnings.forEach((warning) => console.warn(` - ${warning}`));
+/// A built, initialized core. Dispatch RPC in-process with [`CoreRuntime::invoke`],
+/// start its background services with [`CoreRuntime::start_services`], or hand it
+/// to `openhuman_rpc::server::serve` to run the selected transport as well.
+pub struct CoreRuntime {
+ ctx: Arc<CoreContext>,
+ config: Option<Config>,
+ services: ServiceSet,
+ has_operator_token: bool,
+ host: Option<String>,
+ port: Option<u16>,
}
-if (failures.length) {
- console.error("OpenHuman Rust layout check failed:");
- failures.forEach((failure) => console.error(` - ${failure}`));
- process.exit(1);
+impl CoreRuntime {
+ /// The services/transports this runtime is configured to run.
+ pub fn services(&self) -> ServiceSet {
+ self.services
+ }
+
+ /// The initialized core context (host identity + resolved workspace).
+ pub fn context(&self) -> &Arc<CoreContext> {
+ &self.ctx
+ }
+
+ /// Dispatch an RPC method in-process — the same path the HTTP `/rpc` handler
+ /// and the CLI use ([`crate::core::invoke::invoke_method`]). No network involved.
+ pub async fn invoke(
+ &self,
+ method: &str,
+ params: serde_json::Value,
+ ) -> Result<serde_json::Value, String> {
+ self.invoke_in(Arc::clone(&self.ctx), method, params).await
+ }
+
+ /// [`invoke`](Self::invoke) under a caller-supplied context instead of the
+ /// runtime's own — typically a per-agent child from
+ /// [`CoreContext::derive_with`], so the handler's config loader, DomainSet
+ /// gate and tool-group filter all read that agent's overlay.
+ pub async fn invoke_in(
+ &self,
+ ctx: Arc<CoreContext>,
+ method: &str,
+ params: serde_json::Value,
+ ) -> Result<serde_json::Value, String> {
+ log::trace!("[core-runtime] invoke_in method={method}");
+ CoreContext::scope(
+ ctx,
+ crate::core::invoke::invoke_method(
+ crate::core::invoke::default_state(),
+ method,
+ params,
+ ),
+ )
+ .await
+ }
+
+ /// Run an arbitrary future with `ctx` as the ambient [`CoreContext`] — the
+ /// native (non-RPC) counterpart of [`invoke_in`](Self::invoke_in) for
+ /// callers that reach a domain operation directly, such as an embedded
+ /// agent turn. Bypasses the registered-RPC dispatch gate, so the caller is
+ /// responsible for honouring `ctx.domains()` itself.
+ pub async fn run_in<F: std::future::Future>(&self, ctx: Arc<CoreContext>, fut: F) -> F::Output {
+ CoreContext::scope(ctx, fut).await
+ }
+
+ /// The host this runtime was built to bind, when the builder set one.
+ pub fn host(&self) -> Option<&str> {
+ self.host.as_deref()
+ }
+
+ /// The port this runtime was built to bind, when the builder set one.
+ pub fn port(&self) -> Option<u16> {
+ self.port
+ }
+
+ /// Whether the RPC bearer came from the operator (env or an in-memory
+ /// handoff) rather than the self-generated `{workspace}/core.token`. A
+ /// server must not bind a public address without one (#1919).
+ pub fn has_operator_token(&self) -> bool {
+ self.has_operator_token
+ }
+
+ /// Record that a transport bound its listener at `local_addr`.
+ pub fn listener_bound(&self, local_addr: std::net::SocketAddr) {
+ #[cfg(feature = "modules")]
+ crate::desktop::control::set_listener_is_loopback(local_addr.ip().is_loopback());
+ #[cfg(not(feature = "modules"))]
+ let _ = local_addr;
+ }
+
+ /// Mark the start of serving. Arms memory's exit gate for the eventual
+ /// exit (and clears one a previous server in this process may have left):
+ /// from here on a memory binding built during exit is refused rather than
+ /// missed.
+ pub fn serving_started(&self) {
+ crate::memory::exit::server_starting();
+ }
+
+ /// Cleanup to run once a transport has stopped serving, whether it ended
+ /// cleanly or with an error.
+ ///
+ /// Memory goes first. The engine's queue worker holds leases on in-flight
+ /// jobs, and releasing them is a write to the store, so it has to happen
+ /// while the store is still open and before anything else on the way out
+ /// (tinymemory#133). Bounded inside, on one shared deadline: a wedged
+ /// store costs at most that budget, never the exit. There is no local
+ /// model runtime to stop: the user runs Ollama / LM Studio / MLX
+ /// themselves and OpenHuman never spawns it.
+ pub async fn exit_cleanup(&self) {
+ crate::memory::exit::shutdown_for_exit().await;
+ log::debug!("[core] shutdown: exit cleanup done (no owned local runtime to stop)");
+ }
+
+ /// Spawn each selected background service.
+ ///
+ /// A transport calls this once its listener is bound, so a failed bind
+ /// never leaves pollers, one-shot jobs, MCP processes or socket
+ /// reconnect work running without a live runtime. A runtime with no
+ /// transport calls it directly.
+ pub async fn start_services(&self) {
+ use crate::core::runtime::services;
+ super::bootstrap::start_core_runtime_services(self.services, self.config.as_ref()).await;
+
+ if self.services.login_gated {
+ services::spawn_login_gated_services(self.ctx.host_kind().is_desktop_shell());
+ }
+ if self.services.update_scheduler {
+ services::spawn_update_scheduler();
+ }
+ if self.services.cron {
+ services::spawn_cron_service();
+ }
+ // Flow-run boot reconciliation is selected by the flows *domain*, not by
+ // a background service — runs can be started without cron in the
+ // ServiceSet, so their orphans must be reconcilable without it too.
+ if self.ctx.domains().flows {
+ services::spawn_flows_boot_reconcile();
+ }
+ if self.services.channels {
+ services::spawn_channels_service();
+ }
+ }
}
-console.log(
- `OpenHuman Rust layout check passed (new files <= ${LINE_LIMIT} lines; tests external).`,
-);
+#[cfg(test)]
+#[path = "builder_tests.rs"]
+mod tests;