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
chore: files changed crates/openhuman-core/src/desktop/accessibility/README.md,docs/library-benchmar
Steven Enamakele472f43d2fe4
diff --git a/crates/openhuman-core/src/core/runtime/README.md b/crates/openhuman-core/src/core/runtime/README.mdnew file mode 100644index 0000000000..7b50f2087f--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/README.md@@ -0,0 +1,140 @@+# core/runtime++The embeddable composition surface: `CoreBuilder` → `CoreRuntime`. This is+what `openhuman-embed`'s `Harness` and the standalone `openhuman-core`+binary both build on to host the core without duplicating+`run_server_inner`.++## Two-phase model++1. **`CoreBuilder::build()` — initialization only.** Registers controllers,+ loads the master key, seeds the RPC bearer, initializes the+ workspace-bound stores, and runs the pure-registration part of+ `bootstrap_core_runtime`. No port is bound. After `build()` returns,+ `CoreRuntime::invoke` can dispatch any RPC method in-process and agent+ turns can run — a harness-only embedder using `ServiceSet::none()` needs+ nothing more.+2. **`CoreRuntime::serve()` — transport + background services.** Binds the+ HTTP listener (when `ServiceSet::rpc_http` is set), mounts the router,+ fires the readiness signal, spawns the selected background services, and+ serves until shutdown. When `rpc_http` is unset it just spawns the+ selected background services and returns immediately — the caller owns+ the process lifetime. In a build compiled without the `http-server`+ feature, requesting `rpc_http` returns an `Err` rather than silently+ binding nothing.++`CoreRuntime::invoke(method, params)` dispatches an RPC method in-process+through `jsonrpc::invoke_method` — the same path the HTTP `/rpc` handler and+the CLI use, wrapped in `CoreContext::scope` so the ambient context resolves+correctly. `openhuman_embed::Harness` goes through this call, never through+domain operations directly.++## `ServiceSet` — which background services and transports run++Each flag is independent. Presets:++| Preset | Shape |+| --- | --- |+| `ServiceSet::desktop()` | Everything on — the Tauri shell and standalone `openhuman-core run`. |+| `ServiceSet::headless_api()` | HTTP JSON-RPC only (`rpc_http`) — no Socket.IO, cron, channels, or heartbeat; a single-core cloud/server deployment. |+| `ServiceSet::none()` | No transport, no background services — a library/harness embedder driving only `CoreRuntime::invoke`. |+| `ServiceSet::embedded()` | No transport (`rpc_http: false`), but the background work a long-lived embedded session expects: cron, heartbeat, memory queue, harness init, skill catalog refresh, memory sync. `socketio`/`channels` stay off because such a host reads state through the facade and owns its own networking. |++Individual services still honor their own runtime config gates inside+`runtime/services.rs` regardless of `ServiceSet` selection:+`config.cron.enabled`, `config.heartbeat.enabled`,+`OPENHUMAN_DISABLE_CHANNEL_LISTENERS`, and+`config.channels_config.has_listening_integrations()`. `ServiceSet` picks+*whether a service is spawned at all*; the config gate picks *whether it's+enabled for this user*.++## `DomainSet` — which domain families exist at runtime++Sibling of `ServiceSet`: where `ServiceSet` selects background services and+transports, `DomainSet` selects which controller/tool/store/subscriber+surfaces are live, one flag per `DomainGroup` (see+[`../all.rs`](../all.rs)'s `DomainGroup` for the full family list and the+harness/gate/platform split). `DomainSet::allows(group)` is the query the+registry filters on.++| Preset | Shape |+| --- | --- |+| `DomainSet::full()` | Every family on — today's default, byte-identical to registration with no runtime narrowing. |+| `DomainSet::harness()` | `agent` + `memory` + `threads` + `config` + `security` only; every gate family and `platform` off. The embeddable agent core (`examples/embed_headless.rs`). |+| `DomainSet::embedded()` | The harness families plus `medulla`, `flows` (the engine `medulla_workflows` runs on), `skills`, `channels` (for `channel.web_chat`), `inference`, `integrations`, `automation`, `runtimes`, and `platform`. Deliberately not built on `harness()` because that preset's `platform: false` also drops credentials, config, cron, task_sources, and todos. `mcp`/`web3`/`voice`/`media` stay off — an embedded host supplies its own routing for those. |+| `DomainSet::kernel()` | The floor: `threads` + `config` + `security` only. Distinct from `none()` — this is "opt a subsystem back in from nothing," so `agent` and `memory` (the two largest, most replaceable subsystems) are deliberately off. See `examples/embed_kernel.rs`. |+| `DomainSet::none()` | Every family off. |++## `TokenSource` — how the RPC bearer is seeded++- `TokenSource::Fixed(Arc<String>)` — an in-memory bearer supplied by the+ embedder (the Tauri shell's `CoreProcessHandle.rpc_token`), seeded via+ `auth::init_rpc_token_with_value`; never crosses the process environment.+- `TokenSource::EnvOrFile` — the standalone fallback: read+ `OPENHUMAN_CORE_TOKEN` from the environment if present, otherwise generate+ a fresh token and write `{root}/core.token` (0o600 on Unix).++## `CoreBuilder` setters++`CoreBuilder::new(host_kind)` defaults to `TokenSource::EnvOrFile`,+`ServiceSet::desktop()`, and `DomainSet::full()`. Setters (each narrows,+never widens, a default):++- `.services(ServiceSet)`, `.domains(DomainSet)`, `.tool_groups(ToolGroups)`+ — the three independent narrowing axes: which services run, which domain+ families exist, and 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).+- `.token(TokenSource)`, `.host(impl Into<String>)`, `.port(u16)`.+- `.config(Config)` — supply the config outright instead of letting+ `build()` discover one from `config.toml` + environment; used verbatim, no+ env overlay applied automatically.+- `.workspace(dir)` — sugar over `.config()`: roots `workspace_dir` at `dir`+ and sets `config_path` to `dir/config.toml` so credentials and sessions+ resolve beside the workspace rather than a previous config root.+- `.action_dir(dir)` — sugar over `.config()` for the agent's read/write+ root.+- `.backend_url(url)`.++## `CoreContext` and initialization order++`runtime/context.rs`'s `CoreContext` owns the core's initialization+*order*: register controllers, load the master key, seed the RPC bearer,+initialize the workspace-bound stores (`init_stores`: memory, image+attachments, WhatsApp data, people, plus the boot-time Sentry user binding),+and run the pure-registration part of `bootstrap_core_runtime`. It also+holds the `DomainSet` for its scope and, when supplied, the embedder's+`Config` — RPC handlers otherwise re-resolve config independently per+dispatch, so an embedder-supplied config would be silently ignored without+this seam.++`init_stores` deliberately guards against seeding stores against a+`Config::default()` fallback workspace (the "wrong-workspace guard",+Sentry OPENHUMAN-CORE-48 / TAURI-RUST-8NM) — a caller with no resolved+workspace should fail loudly rather than write into the wrong directory.++`CoreContext::scope(ctx, fut)` establishes the ambient context for the+duration of a future (used at the `try_invoke_registered_rpc` chokepoint and+by `CoreRuntime::invoke`); `CoreContext::current` falls back to a+process-wide default context when no scope is active, which is what lets+existing single-tenant call sites keep working unmodified.++## Shared tokio tuning constants++`runtime/mod.rs` declares two constants every multi-thread runtime that may+host an agent turn must set:++- `AGENT_WORKER_STACK_BYTES` (16 MiB) — a single agent turn is a very large+ async state machine (system prompt + hundreds of tool specs + the nested+ provider/tool loop), and delegating to a sub-agent nests another one. That+ overflows tokio's default 2 MiB worker stack and aborts the process.+- `MAX_BLOCKING_THREADS` (64) — tokio defaults this to 512, which combined+ with the raised stack size could pin up to `512 × 16 MiB` of idle stack.+ `spawn_blocking` on these runtimes backs SQLite, filesystem grep/glob,+ document parsing, and URL guarding: bounded, bursty concurrency, so 64+ leaves headroom while capping the idle footprint.++## Related docs++- [../README.md](../README.md) — the rest of `core/`: dispatch, registry,+ event bus, transport, CLI.diff --git a/crates/openhuman-core/src/desktop/accessibility/README.md b/crates/openhuman-core/src/desktop/accessibility/README.mdindex 267c1fe447..18301e9be3 100644--- a/crates/openhuman-core/src/desktop/accessibility/README.md+++ b/crates/openhuman-core/src/desktop/accessibility/README.md@@ -23,7 +23,8 @@ Re-exported from `mod.rs`:## Called by-- `crates/openhuman-core/src/voice/` — microphone permission and focused-text helpers (indirect, via re-exports).+- `crates/openhuman-core/src/voice/` (`server_part_01.rs`, `always_on_part_02.rs`, `audio_capture.rs`, `text_input.rs`) — microphone permission, focused-text, and terminal-context helpers.+- `crates/openhuman-core/src/core/all_tests.rs` — registry-level test coverage.## Testsdiff --git a/crates/openhuman-core/src/memory/sources/README.md b/crates/openhuman-core/src/memory/sources/README.mdnew file mode 100644index 0000000000..a5da705ff1--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/README.md@@ -0,0 +1,56 @@+# sources++The registry of connectors a workspace ingests from (Composio, folders,+GitHub repos, RSS, web pages, Twitter queries), the readers that pull items+out of them, per-source sync status, and the `memory_sources_*` JSON-RPC+surface over all three. See `mod.rs` for the #5560 rationale (why this used+to glob `tinymemory_core::sources::*` and what came home versus stayed+upstream) — this file is a map of the directory, not a repeat of that+history.++The vocabulary is the engine-neutral `tinymemory-sources` crate: `pub mod+types { pub use tinymemory_sources::types::{ContentType,+MemorySourceEntry, SourceContent, SourceItem, SourceKind}; }` at the bottom+of `mod.rs`.++## Files++| File | Role |+| ---- | ---- |+| `registry.rs` | Config discovery and write-locking around the source registry's CRUD. Reads/rewrites `[[memory_sources]]` in the host's own config file; the registry type itself is `tinymemory_sources::registry::SourceRegistry`. |+| `rpc.rs` + `rpc_part_0{1,2}.rs` | RPC handler implementations for memory sources. |+| `schemas.rs` + `schemas_part_0{1,2}.rs` | Controller-registry schemas for `openhuman.memory_sources_*`. |+| `status.rs` | Per-source sync status: the chunk-key prefix (derived from the registry entry) and freshness label are host-side; in-flight/chunk counts go through `MemoryChunks::source_ingest_status`. |+| `sync.rs` | `derive_scopes` — which tree scope and raw-archive id a configured source maps onto; the only production-reached piece of the old engine sync pipeline. |+| `reconcile.rs` | Startup/list-time reconciliation of active Composio connections into the registry, built on `memory::sync::composio::scan_active_sync_targets`. |+| `readers/mod.rs` | `SourceReader` trait plus one implementation per `SourceKind`: `composio`, `conversation`, `folder`, `github`, `rss`, `twitter`, `web_page`. Network readers (`twitter`, `web_page`, ...) are never handed out by kind-dispatch — a caller constructs them explicitly, keeping egress/OAuth/cost decisions with the host. |++## RPC surface (`memory_sources_*`)++`list`, `get`, `add`, `update`, `remove`, `list_items`, `read_item`, `sync`,+`reconcile`, `status_list`, `supported_toolkits`, `sync_audit_log`,+`estimate_sync_cost`, `monthly_cost_summary`, `apply_all_in`,+`coding_session_status`, `ingest_coding_sessions`.++## Wiring++`crates/openhuman-core/src/core/all.rs` (around line 844) registers this+family through `crate::memory::sources::all_memory_sources_registered_controllers()`,+re-exported from `schemas::all_registered_controllers`.++## Related modules++- [`../sync/`](../sync/) — the bus-driven side: Composio subscribers and+ providers (including Slack) that actually move data, plus `sync_status/`+ for per-connection sync progress. `sources/` owns *which* connectors are+ configured and *what* they map onto; `sync/` owns moving data for them.+- [`../read_rpc/`](../read_rpc/) — dashboard reads (list/inspect/search) over+ the memory tree; distinct from the write/ingest surface here.++## Tests++`rpc_tests.rs`, `rpc_budget_tests_tests.rs`, `rpc_filter_tests_tests.rs`,+`rpc_monthly_summary_tests_tests.rs`, `rpc_supported_toolkits_tests_tests.rs`,+`schemas_tests.rs`, `status_tests.rs`, `sync_tests.rs`, `reconcile_tests.rs`,+and per-reader tests under `readers/` (`composio_tests.rs`,+`twitter_tests.rs`).diff --git a/crates/openhuman-core/src/runtime/python_server/README.md b/crates/openhuman-core/src/runtime/python_server/README.mdnew file mode 100644index 0000000000..be887cb6a7--- /dev/null+++ b/crates/openhuman-core/src/runtime/python_server/README.md@@ -0,0 +1,146 @@+# runtime/python_server++The long-lived Python worker that keeps model-backed backends warm. This+module owns the process lifecycle and wire protocol; interpreter resolution+(finding or provisioning a `python` binary) belongs to the sibling+[`runtime/python`](../python/README.md) client, which this module calls into+to pick the interpreter it launches.++Two backends currently run inside the one worker process:++- **spaCy** (`spacy.rs`) — NER extraction for the memory tree's query+ extractor, gated by `config.memory_tree.spacy_enabled`.+- **Kompress** (`kompress.rs`) — TokenJuice's ModernBERT/torch plain-text+ compressor, gated by `config.tokenjuice.ml_compression_enabled`.++Both are gated behind `config.runtime_python.enabled`; `registry::enabled_backends`+computes the active set from all three flags together.++## Key files++| File | Role |+| --- | --- |+| `mod.rs` | Submodule decls and `pub use` re-exports. |+| `server.rs` | Process lifecycle: `RuntimePythonServer` (spawn, request/response, restart-on-failure, idle expiry), the process-wide `ensure_started`/`status` cache. |+| `protocol.rs` | JSONL wire types: `PythonServerRequest`, `PythonServerResponse`, `PythonServerError`, `ReadyLine`, `PROTOCOL_VERSION`. |+| `registry.rs` | `RuntimePythonBackend` enum (`Spacy`, `Kompress`) and `enabled_backends(config)`. |+| `kompress.rs` | Kompress venv provisioning (`ensure_kompress`, `install_into`) and the compress request (`request_kompress`). |+| `spacy.rs` | spaCy venv provisioning (`ensure_spacy`) and the extract request (`extract`). |+| `types.rs` | `BackendStatus`, `RuntimePythonServerStatus` serde types. |+| `server.py` | The worker script itself, embedded via `include_str!` and written to the cache dir at launch. |++## Lifecycle++`ensure_started(config)` is the single entry point. It caches one+`Arc<RuntimePythonServer>` behind a process-wide `OnceLock<Mutex<ServerCache>>`+(`Empty` / `Ready` / `Failed { message, retry_after }`):++- If the enabled backend set has changed since the cached server launched+ (e.g. Kompress toggled on after a spaCy-only start), the cache is discarded+ and a new server is started — the running process was never provisioned for+ the new backend.+- If the Kompress backend has been idle longer than+ `config.tokenjuice.ml_sidecar_idle_timeout_secs`, the server is torn down and+ restarted on the next request, freeing the torch process's memory.+- A startup failure caches `Failed` with a five-minute (`START_FAILURE_BACKOFF`)+ retry window so a broken venv does not retry on every call.+- `RuntimePythonServer::request` sends one request, and on failure resets the+ child and retries once before giving up.++`prepare_launch` picks **one** interpreter for the whole worker: if spaCy is+enabled it owns the venv and Kompress (if also enabled) installs torch ++transformers into it via `kompress::install_into`; if only Kompress is enabled+it gets its own dedicated venv via `kompress::ensure_kompress`; if neither+backend needs a venv the worker still runs under the base interpreter from+`runtime::python::PythonBootstrap`.++## Wire protocol++JSONL over the child's stdin/stdout (`protocol.rs`), one line per message:++- Startup handshake: the worker writes a `ReadyLine` (`ready`, `protocol`,+ `backends`, optional `error`) before any request is sent; a `protocol`+ mismatch against `PROTOCOL_VERSION` or `ready: false` fails the launch.+- Requests: `PythonServerRequest { id, method, params }`, methods namespaced by+ backend (`spacy.extract`, `kompress.compress`).+- Responses: `PythonServerResponse { id, ok, result, error }`, matched back to+ the request by `id`; the read loop skips lines with a stale/unparseable `id`+ and enforces a 60s per-request timeout (`REQUEST_TIMEOUT`, sized for the+ slower Kompress backend, not added latency for spaCy).++stderr is drained continuously by a background task and only logged at+`debug`/`trace`, never surfaced to callers.++## Backends++**spaCy** (`spacy.rs`): `ensure_spacy` provisions a dedicated or shared venv+(`pip install spacy click`, `python -m spacy download en_core_web_sm`),+tracked by a versioned ready marker (`SPACY_READY_MARKER_VERSION`) so a+package-set change forces re-provisioning; `spacy_provisioned` is a cheap,+network-free check used by `harness_init`. `extract` sends `spacy.extract` and+returns the shared `tinymemory_api::host::SpacyResponse` type. Called from+`modules::memory_host` for the memory tree's query extractor.++**Kompress** (`kompress.rs`): `ensure_kompress` provisions a CPU-only torch ++transformers venv and pre-downloads `config.tokenjuice.ml_model_id`;+`install_into` does the same into an existing (spaCy) venv when both backends+share one interpreter. The worker loads the model fully offline+(`HF_HUB_OFFLINE=1`, `TRANSFORMERS_OFFLINE=1`) so startup never depends on the+network once provisioned. `request_kompress` sends `kompress.compress` with+`target_ratio` / `max_input_chars` from `config.tokenjuice`. Called from+`inference::tokenjuice::ml`.++Both provisioning paths are serialized behind their own `tokio::sync::Mutex`+(`provision_lock` / `spacy_provision_lock`) so concurrent callers don't race+the same venv build.++## Status++`RuntimePythonServerStatus { enabled, running, backends: Vec<BackendStatus>, message }`+is returned by `status()` and reflects the cache directly — `Empty` reports+`disabled`, `Failed` reports the last error, `Ready` reports each backend's+`ready` flag from the worker's handshake `backends` list. There is no public+RPC method for this; `crates/openhuman-core/src/agent/harness_init/registry.rs`+polls it during startup to decide whether the `runtime_python_server` init+step is done. The about-app capability catalog+(`platform/about_app/catalog_part_02.rs`, id `local_ai.python_runtime_installer`,+domain `runtime_python`) describes the managed-interpreter capability this+worker depends on, not this module's own status.++## Persistence++No domain store. Provisioned venvs and the written `server.py` live under+`runtime_python.cache_dir` (or the OS cache dir, or `workspace_dir` as a last+resort) via `spacy::python_server_cache_root`; the Kompress HF cache is a+subdirectory of the same root.++## Security++The worker runs under whichever interpreter `runtime::python::PythonBootstrap`+or the venv provisioning resolved — it does not choose or sandbox that+interpreter itself. Environment is explicit and minimal: the enabled backend+list (`OPENHUMAN_RPS_BACKENDS`) and, for Kompress, the model id, device,+compression settings, and `HF_HOME`/offline flags. `process_util::apply_no_window`+suppresses the Windows console flash on every spawned step. Sandbox/approval+policy for what reaches this worker (e.g. text passed to `spacy.extract`) is+decided by the caller before the request is sent, not here.++## Used by++- `crates/openhuman-core/src/agent/harness_init/registry.rs` — the `runtime_python_server`,+ `spacy`, and `kompress` init steps.+- `crates/openhuman-core/src/modules/memory_host.rs` — `extract_spacy` for the memory+ tree's query extractor.+- `crates/openhuman-core/src/inference/tokenjuice/ml/mod.rs` — `request_kompress` for+ plain-text compression.++## Notes / gotchas++- The server always runs a **single** interpreter: enabling Kompress after+ spaCy is already running installs torch into the spaCy venv rather than+ starting a second process.+- Restart-on-failure in `RuntimePythonServer::request` means a transient+ worker crash is invisible to callers except for added latency on the retried+ call.+- `python_server_cache_root` also holds legacy `memory-nlp` spaCy venvs;+ `spacy.rs` migrates or reuses them so upgrades don't force re-provisioning.diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.mdnew file mode 100644index 0000000000..218953febd--- /dev/null+++ b/crates/openhuman-core/src/web3/x402/README.md@@ -0,0 +1,126 @@+# x402++HTTP 402 machine-payment protocol (x402.org / coinbase/x402 v2). Intercepts an+HTTP 402 response carrying a `PAYMENT-REQUIRED` header, builds a payment (a+Solana SPL/USDC transfer, or an EVM EIP-3009 `transferWithAuthorization`),+signs it with the wallet's key, and retries the request with the proof in a+`PAYMENT-SIGNATURE` header. A facilitator co-signs as fee payer and broadcasts,+so the client never needs native gas currency (SOL/ETH) to pay.++Sibling of the [`wallet`](../wallet/README.md) module in the+[`web3`](../README.md) family; unlike wallet-driven swaps/bridges, x402+payments are typically triggered transparently from inside a generic HTTP+tool call rather than through an explicit agent action.++## Compile-time gate (`web3` feature)++`pub mod x402;` (declared in `web3/mod.rs`) is ALWAYS compiled — it is a+facade. The real payment machinery (`ops`, `schemas`, `store`, `tools`,+`types`) is gated behind the default-ON `web3` Cargo feature (shared with+`web3` and `web3::wallet`). When the feature is off, `stub.rs` takes its+place and exposes only the three entry points with always-on callers:+`init_ledger` (a no-op; the boot call site in `core/jsonrpc.rs` is itself+runtime-gated on `DomainGroup::Web3`), `all_x402_registered_controllers`, and+`all_x402_controller_schemas` (both empty). `X402RequestTool`'s registration+and the `http_request` 402-retry path are `#[cfg(feature = "web3")]` at their+own call sites, so the rest of the payment surface (`PaymentRecord`, `store`,+`SettlementResponse`, …) is never referenced when the feature is off and does+not need a stub. Signatures must match the real ones exactly; `cargo check+--no-default-features` is the only thing that catches drift.++## Key files++| File | Role |+| --- | --- |+| `mod.rs` | Facade root: feature gate, re-exports (`handle_402`, `handle_402_and_pay`, `try_paid_request`, `X402Client`, `X402Error`, `X402PaymentResult`, `init_ledger`, the controller pair, wire types). |+| `ops.rs` | Thin include-based split (`include!("ops_part_01.rs")` / `ops_part_02.rs`) of the client logic: parse a 402 challenge, build the Solana (`exact` scheme: ComputeBudget limit/price, SPL `TransferChecked`, optional Memo) or EVM (`exact` scheme: EIP-3009 `transferWithAuthorization`) payment, sign, and retry with the proof. |+| `ops_part_01.rs` | Solana challenge parsing, `wallet_signer` (Solana signer resolution), payment building/signing, `X402Client`/`try_paid_request`. |+| `ops_part_02.rs` | EVM challenge parsing, `evm_signer` (EVM signer resolution), EIP-712 payload construction, `handle_402`/`handle_402_and_pay`. |+| `store.rs` | Append-only JSONL payment ledger (`PaymentLedger`) with session/daily/monthly budget enforcement; `PaymentRecord`, `PaymentStatus`, `SpendingSummary`, `SpendingBudget`, `BudgetCheck`, the process-global `GLOBAL_LEDGER`, and `with_ledger`/`with_ledger_mut` accessors. |+| `schemas.rs` | RPC controller schemas + handlers for the `x402` namespace: `get_summary`, `list_payments`, `update_budget`. |+| `tools.rs` | `X402RequestTool` (`x402_request`) — purpose-built agent tool for x402 endpoints, as opposed to the generic `http_request` tool's opportunistic 402 fallback. |+| `types.rs` | Wire types for the v2 protocol: header names, CAIP-2 network/asset constants (Solana mainnet/devnet, Base/Ethereum, USDC mints/contracts), `PaymentRequired`/`PaymentRequirements`/`PaymentPayload`/`PaymentProof` (Evm/Solana variants), `SettlementResponse`, `ResourceInfo`. |+| `stub.rs` | Disabled facade compiled when `web3` is off. See Compile-time gate above. |+| `x402_tests.rs`, `store_tests.rs`, `stub_tests.rs` | Behavior tests, `#[cfg(all(test, feature = "web3"))]` except `stub_tests.rs` which runs only in the disabled build. |++## RPC / controllers++Namespace `x402` (method form `openhuman.x402_<function>`), registered via+`all_x402_registered_controllers`:++| Function | Purpose |+| --- | --- |+| `get_summary` | Spending totals for session/day/month plus the current budget limits. |+| `list_payments` | Recent payment records, newest first (`limit`, default 50, max 500). |+| `update_budget` | Update `per_request_max` / `daily_max` / `monthly_max` (atomic USDC units; 1 USDC = 1,000,000). |++## Agent tool++`X402RequestTool` (`x402_request`, `PermissionLevel::Write`) makes an HTTP+request to an x402-payable endpoint, always expecting a payment challenge: it+sends the initial request, requires a `PAYMENT-REQUIRED`/`X-PAYMENT-REQUIRED`+header on a 402, builds and signs the payment via `handle_402_and_pay`,+records a `Pending` ledger entry, retries with `PAYMENT-SIGNATURE`, and+updates the ledger to `Settled`/`Failed` based on the retry's outcome and the+decoded `PAYMENT-RESPONSE` settlement header. This differs from the generic+`http_request` tool (`crates/openhuman-core/src/tools/impl/network/http_request.rs`),+which handles a 402 only as a silent fallback for any endpoint.++## Persistence++- **`{workspace_dir}/x402/payments.jsonl`** — one JSON `PaymentRecord` per+ line, appended on every pending/settled/failed payment. Loaded into memory+ at `PaymentLedger::new` (via `init_ledger`) and held in the process-global+ `GLOBAL_LEDGER`, guarded by a `parking_lot::Mutex`.+- **Budget enforcement** (`SpendingBudget`, defaults: 1 USDC per request, 10+ USDC per day, 100 USDC per month, in atomic units) is checked against the+ in-memory ledger before a payment is built; `update_budget` changes the+ limits for the running process only — it does not rewrite historical+ records.++## Dependencies++- `crate::web3::wallet::secret_material` — fetches the encrypted mnemonic ++ derivation path for the chain being paid on (`WalletChain::Evm` /+ `WalletChain::Solana`).+- `crate::security::encryption::rpc::decrypt_secret` — decrypts the mnemonic+ in this process just long enough to hand it to the signer.+- `crate::modules::wallet::{derive_account, sign_message}` — the actual+ derivation and signing happen inside the loaded `tinywallet` native module+ over a confidential bus call; this binary never derives a private key or+ holds one. Only the decrypted **mnemonic** passes through this process, in+ the `tinywallet_bus::wire::SecretMaterial` handed to those calls.+- `tinywallet_bus::wire::SecretMaterial`, `tinywallet_bus::Chain` — the wire+ types crossing that seam.+- `crate::config::rpc::load_config_with_timeout` — config needed to reach the+ wallet module and decrypt the mnemonic.++## Used by++- `crates/openhuman-core/src/tools/impl/network/http_request.rs` (~lines+ 165-225) — `handle_x402_payment`, gated `#[cfg(feature = "web3")]`, is the+ 402 fallback path any HTTP tool call can hit; it calls+ `x402::handle_402_and_pay` and records to the same ledger via+ `x402::store::with_ledger_mut`.+- `crates/openhuman-core/src/tools/ops.rs` — registers `X402RequestTool` as an+ agent tool.+- `crates/openhuman-core/src/core/all.rs` (~line 569) — wires+ `all_x402_registered_controllers` into the controller registry under+ `DomainGroup::Web3`.+- `crates/openhuman-core/src/core/jsonrpc.rs` (~line 2477) — calls+ `init_ledger(&workspace_dir, &x402_session)` at boot, itself runtime-gated on+ `DomainGroup::Web3`.++## Notes / gotchas++- The paying account never needs SOL (or ETH/native gas) for the payment+ transaction itself — the facilitator is the fee payer / on-chain submitter.+ The wallet does still need the payment asset (typically USDC) on the target+ chain.+- Budgets are enforced per-process against the in-memory ledger snapshot; they+ are not a substitute for on-chain spending limits and reset only when the+ limits are explicitly updated via `update_budget`.+- Two distinct paths reach a payment: the purpose-built `x402_request` agent+ tool (always expects a 402) and the generic `http_request` tool's+ opportunistic 402 fallback. Both funnel through `handle_402_and_pay` and the+ same ledger, so spending is tracked consistently regardless of entry point.diff --git a/docs/library-benchmarking.md b/docs/library-benchmarking.mdindex 1a28baaab2..44d94c991e 100644--- a/docs/library-benchmarking.md+++ b/docs/library-benchmarking.md@@ -13,10 +13,10 @@ startup cost, steady-state footprint, and growth curve.This document describes the benchmark environment built to measure that: apinned `library-profile` binary with eight scenarios, four driver scriptsunder `scripts/profile/`, and the comparison point the team cares about-(ZeroClaw). It builds on the manual investigation in-`docs/resource-profiling-session-2026-07-21.md`;-read that document for the deep memory/CPU attribution work. This document is-about running repeatable benchmarks, not re-deriving those findings.+(ZeroClaw). It builds on an earlier manual investigation into deep memory/CPU+attribution (removed from the tree; see git history at `0017c58d86~1` for the+original write-up). This document is about running repeatable benchmarks, not+re-deriving those findings.## The eight scenarios@@ -371,4 +371,4 @@ attribution + cap before real 1000-agent runs), and p95 latency at N=500 on- `docs/resource-profiling-session-2026-07-21.md` — the full manual investigation (deep attribution, cold-path CPU, library-design implications, recommended optimization order).- [`scripts/profile/README.md`](../scripts/profile/README.md) — script quick reference.-- `src/bin/library_profile/main.rs` — the scenario implementations.+- `crates/openhuman-core/src/bin/library_profile/main.rs` — the scenario implementations.