Skip to content

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

docs(inference): add README for the inference module

Steven Enamakel02b36935303e
diff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.md
index bf8be06e26..3cb950743c 100644
--- a/crates/openhuman-core/src/inference/README.md
+++ b/crates/openhuman-core/src/inference/README.md
@@ -1,143 +1,323 @@
# inference
-OpenHuman's inference integration domain. Reusable model, provider transport,
-embedding, capability, temperature, and failure behavior belongs to
-`tinyinference`; this domain owns product configuration, credentials, access
-policy, the endpoint seam to a user-run local runtime (Ollama / LM Studio /
-MLX / OMLX / OpenAI-compatible), RPC/controller surfaces, OpenAI/Codex subscription OAuth, and the OpenAI-compatible HTTP
-endpoint. The RPC surface is `inference.*`; older `local_ai_*` method names are
-compatibility aliases in `crates/openhuman-core/src/core/legacy_aliases.rs`.
-
-## Responsibilities
-
-- Resolve workload names (`chat`, `reasoning`, `agentic`, `coding`, `memory`, `embeddings`, `learning`, etc.) and provider strings (`openhuman`, `cloud`, `ollama:<model>`, `lmstudio:<model>`, `claude_agent_sdk:<model>`, `claude-code:<model>`, `<slug>:<model>[@<temp>]`) to a concrete `Arc<dyn tinyinference_llm::ChatModel<()>>` + model id.
-- Talk to the local AI runtime the **user** runs (Ollama, LM Studio, MLX, OMLX, any OpenAI-compatible server): probe the configured endpoint (`ready` / `degraded` / `unreachable`), report which configured models it serves, and enforce a minimum-context-window floor. OpenHuman never installs or launches a runtime, never pulls or downloads a model, never installs Piper, and does not pick models by RAM tier; a missing model is reported with "run `ollama pull <model>`" guidance. Local STT (whisper.cpp) was retired; STT is now cloud/engine-configurable via `voice_server.stt_engine` (see `config/migrations/retire_local_whisper_stt.rs`).
-- Provide chat, vision (multimodal), summarization, embeddings, sentiment, and "should react" inference operations.
-- Preserve product-specific config-rejection, billing, and authentication policy while TinyInference owns provider-failure classification and TinyAgents owns model-call retry execution.
-- Resolve abstract tier names (`hint:reasoning`, `hint:agentic`, `hint:coding`, etc.) through the TinyAgents `ModelRouter` in `crates/openhuman-core/src/agent/tinyagents/routes.rs` and the provider factory here.
-- Run ChatGPT/Codex OAuth (PKCE) for the `openai` cloud slug and persist tokens in the encrypted auth-profile store.
-- Expose an OpenAI-compatible `/v1/*` HTTP endpoint guarded by a stable user-managed external bearer.
-- Maintain the built-in BYOK provider preset catalog used by Connections → API keys → LLM.
- The current matrix is `tinymemory_api::host::cloud_providers`, re-exported through
- `config/schema/cloud_providers.rs`; credentials are stored under `provider:<slug>` in the auth-profile store.
-
-## Key files
-
-| File / dir | Role |
-| --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `mod.rs` | Domain root; module decls + re-exports; wires `inference.*` controller schemas/controllers. |
-| `ops.rs` | Canonical handler file, `inference_*` business logic returning `Outcome<T>`; delegates to `host_runtime`, `provider`, `sentiment`, `openai_oauth`. Includes Sentry-noise suppression for expected provider/user-config failures. |
-| `schemas.rs` + `schemas/` (`catalog.rs`, `prompt_handlers.rs`, `oauth_handlers.rs`, `claude_code_handlers.rs`, `settings_handlers.rs`) | `inference.*` controller schemas + `handle_*` fns + param DTOs. |
-| `tinyinference_llm::{classification,completion,sentiment}` | Reusable language-model parsing and classification called directly by the host. |
-| `tinyinference_core::sanitize` | Credential-safe diagnostic formatting. |
-| `tinyinference_llm::model::model_id_supports_vision` | Upstream capability hint used directly for local model ids when the runtime cannot return an authoritative profile. |
-| `tinyinference_llm::model::effective_temperature` | Applies unsupported-model glob patterns and overrides before provider serialization. |
-| `tinyinference_local::status` | Serde DTOs re-exported from `mod.rs`: `LocalAiStatus`, `LocalAiEmbeddingResult`, `LocalAiSpeechResult`, `LocalAiTtsResult`. |
-| `model_context.rs` | Static context-window guesses (`static_context_window_for_model`: tier aliases, cost catalog, id patterns) and `context_window_for_model`, which prefers the window a turn last resolved from the provider. |
-| `context_window.rs` | Turn context-window resolution: config override (`model_registry[].context_window`) → provider-reported (`tinyinference_llm::model::discover`, bounded + cached, corrected by overflow-learned limits) → local profile → static guess (`warn` once). Request built by `provider::factory::model_limits_request`. |
-| `paths.rs` | Host-owned on-disk model artifact paths. Completion and sentiment parsing live in `tinyinference`. |
-| `local/` | Local runtime manager (was `local_ai/`). See `local/README.md`. |
-| `host_runtime/core.rs` | `LocalAiService` singleton (`global`). |
-| `host_runtime/ops.rs` + `host_runtime/ops/` (`runtime_ops.rs`, `agent_chat.rs`, `turn_guards.rs`) | Local RPC entrypoints (`local_ai_status/prompt/summarize/vision_prompt/transcribe/tts`); re-exported as `host_runtime::rpc`. |
-| `local/schemas.rs` | Local-runtime `inference.*` controller schemas + handlers. |
-| `tinyinference_local` | Endpoint-only local inference: Ollama/LM Studio wire types, URL handling, model requirements, runtime profiles, provider selection, endpoint probe, and inference calls. No download, install, or process management. |
-| `host_runtime/service/` | OpenHuman speech bindings (`speech.rs`, `transcription.rs`) over `tinyinference_local::service::LocalAiService`. |
-| `provider/` | Native TinyAgents model construction plus host provider configuration, auth, error taxonomy, DTOs, and RPC helpers (was `providers/`). See `provider/README.md`. |
-| `provider/types.rs` | Host request/response, streaming delta, tool-call, and usage DTOs retained at product/RPC boundaries. |
-| `provider/factory.rs` + `provider/factory/` (`routing.rs`, `tiers.rs`, `turn_model.rs`, `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`, `primary_cloud.rs`) | `create_chat_model*`, `provider_for_role`, provider-string grammar, access gates, and local/cloud/CLI model construction; `BYOK_INCOMPLETE_SENTINEL`. |
-| `tinyinference_llm::providers::{openai,anthropic}` | OpenAI-compatible and Anthropic model builders, including Codex metadata and local-runtime construction. |
-| `provider/openhuman_backend_model.rs` | Managed OpenHuman backend `ChatModel` with session JWT, billing metadata, and thread context. |
-| `provider/openai_codex.rs` | `pub(crate)` Codex routing metadata (`OpenAiCodexRouting`, `resolve_openai_codex_routing`): re-targets the `openai` slug at the ChatGPT Codex backend with account/originator headers when Codex OAuth tokens exist. Not a `ChatModel` itself. |
-| `tinyagents_harness::providers::claude_agent_sdk` | Claude Agent SDK subprocess provider and prompt-guided tool adapter. |
-| `tinyagents_harness::providers::claude_code` | Claude Code CLI provider (`claude-code:<model>`), stream-json parser/driver, auth probes, settings, and subprocess lifecycle. OpenHuman supplies only its MCP endpoint and product routing. |
-| `provider/error_classify.rs` | OpenHuman policy layered on the reusable classifiers in `tinyinference_llm::classification`. |
-| `tinyinference_llm::providers::openai::AuthStyle` | Wire auth style consumed directly by crate-native builders. |
-| `provider/ops/` | Host HTTP policy, model catalog RPC, and provider configuration; reusable sanitization lives in `tinyinference_core::sanitize`. |
-| `provider/schemas.rs` | Defines a `providers.list_models` controller that is **not** wired into `core/all.rs`; the live method is `inference.list_models` (`openhuman.providers_list_models` survives only as a legacy alias). |
-| `voice/` | Inference implementations imported by `crate::voice`. |
-| `voice/cloud_transcribe.rs`, `voice/local_speech.rs` | Hosted STT and local Piper TTS. |
-| `voice/streaming.rs`, `voice/postprocess.rs` | Streaming transcription and post-processing. |
-| `openai_oauth/` | ChatGPT/Codex OAuth: `config.rs` (Codex OAuth config), `flow.rs` (start/complete/status/disconnect), `store.rs` (token persistence). |
-| `http/` | OpenAI-compatible endpoint: `server.rs` (`router()`, gated on the `http-server` feature), `types.rs`; `EXTERNAL_OPENAI_COMPAT_PROVIDER` bearer id stays ungated because `core::auth` reads it. |
-| `embeddings/` | Embedding provider selection/RPC. See `embeddings/README.md`. |
-| `tokenjuice/` | Host adapter for the separately released TinyJuice token-compression module. See `tokenjuice/README.md`. |
-
-## Public surface
-
-From `mod.rs` re-exports:
-
-- `model_context::context_window_for_model`
-- `{LocalAiStatus, LocalAiEmbeddingResult, LocalAiSpeechResult, LocalAiTtsResult}` (from `tinyinference_local::status`), `local_vision_mode`, `disabled_local_ai_status`, `local_runtime_config`
-- `local::all_local_inference_controller_schemas` / `local::all_local_inference_registered_controllers` (legacy export names; registered schemas are in the `inference` namespace)
-- `rpc` (alias for `ops`) and `all_inference_controller_schemas` / `all_inference_registered_controllers`
-
-Provider-layer (via `provider::`): `ChatRequest`, `ChatResponse`, `ProviderDelta`, `ToolCall`, `UsageInfo`, `create_chat_model*`, `provider_for_role`, `BYOK_INCOMPLETE_SENTINEL`, `OpenHumanBackendModel`, plus error classifiers. Local runtime: `host_runtime::global` → `Arc<LocalAiService>`.
-
-## RPC / controllers
-
-One namespace is wired into the controller registry (`crates/openhuman-core/src/core/all.rs`).
-
-`inference.*` (`schemas.rs`, `local/schemas.rs`): `resolve_model`, `status`, `get_client_config`, `update_model_settings`, `update_local_settings`, `list_models`, `provider_auth_errors`, `diagnostics`, `openai_oauth_start`, `openai_oauth_complete`, `openai_oauth_import_codex_cli`, `openai_oauth_status`, `openai_oauth_disconnect`, `summarize`, `prompt`, `vision_prompt`, `test_provider_model`, `analyze_sentiment`, `claude_code_status`, `claude_code_auth_status`, `claude_code_settings`, `claude_code_set_full_access`, `agent_chat`, `agent_chat_simple`, `transcribe`, `transcribe_bytes`, `tts`, `test_connection`.
-
-The model-download, asset-status, Piper-installer, preset and device-profile
-controllers (`assets_status`, `downloads_progress`, `download_asset`,
-`install_piper`, `piper_install_status`, `presets`, `apply_preset`,
-`device_profile`) and their `local_ai_*` aliases were removed: the user runs
-their own runtime and pulls models there.
-
-Legacy `openhuman.local_ai_*` and `openhuman.update_local_ai_settings` method names are rewritten to canonical `openhuman.inference_*` methods by `crates/openhuman-core/src/core/legacy_aliases.rs` and `app/src/services/rpcMethods.ts`.
-
-Also exposes a non-RPC HTTP router (`http::router()`) nested at `/v1` by `crates/openhuman-rpc/src/server/http/mod.rs` (`/v1/chat/completions`, `/v1/models`), accepting either the core bearer or a stable external API key.
-
-## Events
-
-- Publishes `DomainEvent::SessionExpired` from `provider/ops/http_error/auth_failure.rs` (`publish_backend_session_expired`) and `provider/openhuman_backend_model.rs` when the managed backend rejects a session, so the credentials layer can clear/refresh it.
-- Publishes `DomainEvent::ProviderApiKeyRejected` once per provider from `provider/ops/http_error/auth_failure.rs` the first time a BYO key is rejected (401/403), gated by the OpenHuman-owned `auth_error_registry`.
-- No `bus.rs` / `EventHandler` subscribers in this domain.
-
-## Persistence
-
-- `openai_oauth/store.rs` persists OAuth tokens via the credentials auth-profile store (`AuthProfilesStore`, `auth-profiles.json`, encrypted at rest) under profile key `provider:openai` / profile `oauth`.
-- `LocalAiService` holds in-process probe state (the last endpoint verdict) via the `host_runtime::global` `OnceCell` singleton, process-lifetime, not durably persisted. `inference.update_local_settings` resets it so the next status poll re-probes.
-- No model artifacts are stored by OpenHuman; models live in the user's runtime. Local TTS uses a Piper binary the user installed (`PIPER_BIN` / PATH).
-- Routing/provider/local settings persisted through `config` (no dedicated `store.rs`).
-
-## Dependencies
-
-- `crate::config`: `Config`, `config::rpc` (load/save, `ModelSettingsPatch`, `LocalAiSettingsPatch`), cloud-provider schema (`AuthStyle`, slug reservation, id generation), abstract tier model constants. Heaviest dependency.
-- `crate::security::credentials`: `AuthService`, `AuthProfilesStore`/`AuthProfile`/`TokenSet`, state dir, for OAuth token storage and provider auth resolution.
-- `crate::tools`: tool schemas and product tool metadata projected into TinyAgents requests.
-- `crate::agent::tinyagents`: native model, route, message, usage, and thread-context seams used by the agent harness.
-- `crate::voice`: voice RPC/audio layer that imports these inference STT/TTS implementations (also a consumer).
-- `crate::security::prompt_injection`: prompt-injection handling on the inference path.
-- `crate::util`: small shared helpers.
-- `crate::core::all`: `ControllerFuture`, `RegisteredController` (controller registry).
-- `crate::core::types`: `ControllerSchema`, `FieldSchema`, `TypeSchema`.
-- `crate::core::bus` (`BUS.publish`) / `crate::core::events::DomainEvent`: `SessionExpired` / `ProviderApiKeyRejected` publishing on auth failure.
-- `crate::security::live_policy` + `crate::security::egress`: Privacy-Mode `LocalOnly` enforcement and egress descriptors at the chat-factory chokepoint (`enforce_local_only_inference`, `emit_inference_egress` in `provider/factory/access_gates.rs`).
-- `crate::core::observability`: `expected_error_kind` for Sentry-noise classification.
-- `openhuman_rpc::server::build_core_http_router`: mounts this router at `/v1`.
-- `crate::core::auth`: bearer auth for the OpenAI-compatible endpoint.
-- External: `reqwest`.
-
-## Used by
-
-Widely depended on by the agent layer, voice, memory, channels, web chat,
-flows, scheduling, threads, credentials, runtime shutdown, and configuration.
-Reusable embedding and local-runtime behavior is consumed directly from the
-TinyInference crates; `host_runtime` retains OpenHuman policy and RPC wiring.
-
-## Notes / gotchas
-
-- TinyInference owns effective chat, vision, embedding, STT, and TTS model
- resolution (a configured id passes through unchanged; defaults apply only
- when it is empty); OpenHuman implements its configuration view and
- calls `tinyinference_local::models` directly.
-- Provider strings carry an optional `@<temp>` suffix that pins a per-workload temperature; the suffix is stripped before the model id is sent upstream.
-- `update_model_settings` silently drops reserved cloud-provider slugs (`openhuman`/`cloud`/`pid` built-ins the frontend echoes back); `apply_model_settings` re-injects them from stored config so they aren't lost.
-- `ops.rs` deliberately demotes known provider/user-config failures (unknown cloud provider, 401/429, model-not-found) to `warn!` to keep them out of Sentry; only unclassified failures escalate to `error!`.
-- `diagnostics` returns its payload unwrapped (no `{result, logs}` envelope) to match the legacy `local_ai_diagnostics` shape that `json_rpc_e2e` asserts against.
-- OpenHuman never spawns or stops a local runtime, so shutdown has no local-runtime cleanup step.
-- `host_runtime::global` lazily initialises the `LocalAiService` singleton.
-- The `/v1/*` endpoint uses a stable external bearer (`EXTERNAL_OPENAI_COMPAT_PROVIDER`) separate from the core launch bearer, so external OpenAI-compatible harnesses can call it.
-- Tests serialize through `inference_test_guard()` (a process-global mutex) since the runtime singleton and config are shared.
+The inference domain turns OpenHuman configuration into working language models. Given a workload
+name such as `chat` or `reasoning`, it decides which provider serves it (the managed OpenHuman
+backend, a bring-your-own-key cloud provider, a local runtime the user runs, or a CLI subprocess),
+builds a native `ChatModel`, and applies product policy around it: credentials, Privacy Mode, error
+copy, Sentry demotion, and context-window sizing. It also owns the `inference.*`, `embeddings.*`
+and `tokenjuice.*` RPC surfaces and the OpenAI-compatible `/v1` HTTP endpoint.
+
+Reusable model, provider-transport, embedding, capability, temperature and failure-classification
+code lives in the vendored `tinyinference` crates. The agent loop and model-call retries live in
+`tinyagents`. This folder is the product layer over both. The agent harness, voice, memory, web
+chat, flows, scheduling and channels all call into it.
+
+## How it works
+
+### Resolving a workload to a model
+
+Every caller starts with a role (`chat`, `reasoning`, `agentic`, `coding`, `vision`, `memory`,
+`embeddings`, `learning`, and so on) or a model hint like `hint:reasoning`. The factory in
+`provider/factory.rs` resolves that in three steps.
+
+```text
+ caller (agent turn, memory summarizer, flows node, RPC prompt)
+ |
+ | role or hint:* e.g. "reasoning", "hint:coding"
+ v
+ routing.rs / tiers.rs role -> provider string from config
+ | (chat_provider, reasoning_provider, ...)
+ | provider string e.g. "openhuman", "ollama:[email protected]"
+ v
+ access_gates.rs Privacy Mode LocalOnly check, session check,
+ | egress descriptor
+ v
+ constructor by prefix:
+ +-- managed_backend.rs "openhuman" / "cloud" -> OpenHumanBackendModel
+ +-- local_runtime.rs ollama / lmstudio / mlx / local-openai
+ +-- cloud_slug.rs "<slug>:<model>" BYOK, OpenAI or Anthropic wire
+ +-- subprocess_providers.rs claude_agent_sdk:, claude-code:
+ v
+ (Arc<dyn ChatModel<()>>, resolved model id)
+```
+
+The provider-string grammar is documented at the top of `provider/factory.rs`:
+
+```text
+"openhuman" managed backend, model = config.default_model
+"cloud" / empty primary_cloud (legacy inference_url wins while
+ primary still points at OpenHuman)
+"ollama:<model>[@<temp>]" local Ollama at config.local_ai.base_url
+"lmstudio:<model>[@<temp>]" local LM Studio
+"mlx:<model>[@<temp>]" local MLX-compatible server
+"local-openai:<model>[@<temp>]" any local OpenAI-compatible server
+"<slug>:<model>[@<temp>]" cloud_providers entry keyed by slug
+"claude_agent_sdk:<model>" Claude Agent SDK subprocess
+"claude-code:<model>" Claude Code CLI subprocess
+```
+
+The optional `@<temp>` suffix pins a temperature for that workload. It is stripped
+(`routing::split_model_and_temperature`) before the model id goes upstream. Unknown slugs and
+missing credentials produce actionable errors instead of a silent fallback.
+
+Background roles (`vision`, `embeddings`, `memory`, `agentic`, `burst`) fall back to the primary
+cloud provider when their own route is unset, because they run tier models that local runtimes and
+most BYOK slugs do not serve. `provider/fallback_diagnostics.rs` exists so that when this fallback
+lands on a provider with no credentials, the error says it was a background role that fell back,
+instead of naming a slug the user never configured.
+
+Hints and retired tier slugs never reach the managed backend verbatim. `tiers.rs` maps them to a
+role (`role_for_model_tier`) or to the concrete managed default (`resolve_model_for_hint`), while
+raw catalog ids a user pins on an agent (for example `openrouter/deepseek/deepseek-v4-pro`) pass
+through unchanged (`is_raw_passthrough_model`). The TinyAgents workload router that consumes this
+for agent turns is in `agent/tinyagents/routes.rs`.
+
+There are two families of entry points. `create_chat_model*` in `factory/chat_model.rs` is for
+one-shot callers (summaries, sentiment, prompts). `create_turn_chat_model*` in
+`factory/turn_model.rs` is for agent turns and carries native-tool and route options. Both go
+through the same gates and constructors.
+
+### The managed backend model
+
+`provider/openhuman_backend_model.rs` is a host `ChatModel` for the OpenHuman backend. It cannot be
+a plain `tinyinference` OpenAI preset for three reasons: the session bearer is resolved fresh per
+call, the request carries a top-level `thread_id` so the backend can group logs and align cache
+keys, and the response carries an `openhuman.{billing,usage}` envelope with the charged USD that
+the generic parser drops. The model re-projects that envelope
+(`openhuman_backend_model_usage.rs`) so usage meters see real costs. When the bearer's `exp` has
+already passed, or the backend rejects it, it publishes `DomainEvent::SessionExpired`.
+
+`provider/openai_codex.rs` is related but is not a model. When ChatGPT/Codex OAuth tokens exist
+for the `openai` slug, `resolve_openai_codex_routing` re-targets that slug at the Codex backend
+with the account and originator headers. The OAuth flow itself (start, complete, import from the
+Codex CLI, status, disconnect) and its token store live in `security/credentials/openai_oauth/`;
+this domain only exposes the RPC wrappers in `ops.rs`.
+
+### Local runtimes
+
+The local runtime (Ollama, LM Studio, MLX, OMLX, any OpenAI-compatible server) is installed,
+started and stocked with models by the user. OpenHuman never downloads a model, never launches or
+stops the runtime, never installs Piper, and does not pick models by RAM tier. It probes the
+configured endpoint (`ready`, `degraded`, `unreachable`), reports which configured models are
+served, enforces a minimum context window, and points the user at `ollama pull <model>` when a
+model is missing.
+
+`tinyinference_local` does the endpoint work. `host_runtime/` keeps the product side:
+
+```text
+ config.local_ai --local_runtime_config()--> tinyinference_local::RuntimeConfig
+ |
+ host_runtime::global(config) ---- OnceCell ----> LocalAiService (probe state)
+ |
+ +-- ops/runtime_ops.rs status, summarize, prompt, vision, transcribe, tts
+ +-- ops/agent_chat.rs agent_chat, agent_chat_simple, agent_chat_for
+ +-- ops/turn_guards.rs prompt-injection gate, cwd grant, turn origin
+ +-- service/speech.rs transcribe / tts bindings used by crate::voice
+```
+
+`LocalAiService` is a process-lifetime singleton holding the last probe verdict.
+`inference.update_local_settings` resets it so the next status poll re-probes. Local STT through
+whisper.cpp is retired; speech-to-text goes through the engine configured in
+`voice_server.stt_engine` (see `config/migrations/retire_local_whisper_stt.rs`), and the speech
+bindings call `crate::voice::create_stt_provider` for it. Local TTS uses a Piper binary the user
+installed (`PIPER_BIN` or `PATH`).
+
+`agent_chat_for` in `host_runtime/ops/agent_chat.rs` is the native agent-turn entry used by
+`openhuman-rpc` and `openhuman-embed`. It runs the turn under the agent's own `CoreContext`,
+resumes the thread's session with `ResumeMode::Session`, and is boxed on purpose so other crates
+do not each instantiate its state machine.
+
+### Context windows
+
+The context window drives pre-dispatch trimming and the compaction trigger, so `context_window.rs`
+resolves it per turn in this order:
+
+```text
+ 1. config override model_registry[].context_window (non-zero)
+ 2. provider-reported tinyinference_llm::model::discover, cached per
+ endpoint+model, lowered by any limit learned from
+ a context-overflow error on that endpoint
+ 3. local profile for local runtimes
+ 4. static guess model_context::static_context_window_for_model,
+ logged at warn once per model
+```
+
+The discovery request comes from `provider/factory/discovery.rs` (`model_limits_request`), built
+from the same endpoint and credential resolution the chat factory uses. The resolved value is
+remembered, so the synchronous `context_window_for_model` (usage meters, the context breakdown)
+reports the same number the turn used. `model_context.rs` also answers vision capability through
+`model_supports_vision` and the user's `model_registry` `vision` flag.
+
+### Failures
+
+A failed provider call passes through several layers, each with one job:
+
+```text
+ HTTP / transport error
+ |
+ v
+ provider/ops/http_error/dispatch.rs api_error(): run every classifier
+ | quota_and_credits, local_provider, policy_rejection,
+ | context_window, auth_failure
+ |
+ +--> auth_failure.rs: 401 from managed backend -> SessionExpired event
+ | 401/403 on a BYO key -> auth_error_registry::record
+ | -> ProviderApiKeyRejected (once per episode)
+ v
+ provider/error_code.rs managed errorCode present? backend owns Sentry
+ provider/error_classify.rs rate-limit / upstream-unhealthy / retry-after
+ v
+ failure_copy/table.rs class -> error_type, source, retryable, copy
+ (consumed by web_chat::web_errors)
+```
+
+Provider-text matching itself (including the budget-phrase matcher) is upstream in
+`tinyinference`. `auth_error_registry.rs` is the single record of rejected BYO keys: the
+notification center gets one event per failure episode, and the AI settings page reads the live
+list through `inference.provider_auth_errors`. Entries clear when the user updates or removes the
+key in the credentials domain. `failure_copy/halt.rs` holds the summaries the loop guards record
+when they stop a turn for repeated tool failures.
+
+### The OpenAI-compatible endpoint
+
+`http/server.rs` serves `/v1/chat/completions` (with SSE streaming) and `/v1/models`.
+`openhuman-rpc` mounts it with `.nest("/v1", openhuman_core::inference::http::router())`, so it sits
+behind the same bearer middleware as `/rpc`. The bearer may be either the per-launch core token or
+a stable user-managed key stored under the `EXTERNAL_OPENAI_COMPAT_PROVIDER` auth profile, which
+lets external harnesses use OpenHuman as an OpenAI-compatible router. The request's `model` field
+picks the provider the same way a provider string does.
+
+## Layout
+
+| Path | What it does |
+| --- | --- |
+| `mod.rs` | Module declarations and re-exports. Also `local_runtime_config` (projects `config.local_ai` into TinyInference's input), `local_vision_mode`, `disabled_local_ai_status`, the `LocalModelConfig` impl for `Config`, and `INFERENCE_COMPILED_IN`. |
+| `ops.rs` | `inference_*` business operations returning `Outcome<T>`: status, prompt, summarize, vision, sentiment, provider tests, model listing, settings updates, OpenAI OAuth wrappers, diagnostics. Demotes expected user-config failures to `warn!`. |
+| `schemas.rs`, `schemas/` | The `inference.*` controller registry. `catalog.rs` has the schemas; `prompt_handlers.rs`, `settings_handlers.rs`, `oauth_handlers.rs` and `claude_code_handlers.rs` hold the thin handlers. |
+| `context_window.rs` | Per-turn context-window resolution (override, provider, local profile, static guess). |
+| `model_context.rs` | Static context-window table, the remembered window lookup, and vision capability checks. |
+| `auth_error_registry.rs` | Process-lived registry of rejected BYO provider keys, with a once-per-episode latch. |
+| `failure_copy/` | `table.rs` maps a failure class to the wire `error_type`, source, retry verdict and user copy. `halt.rs` has loop-guard halt summaries. |
+| `provider/` | Model construction and provider policy. See [`provider/README.md`](provider/README.md). |
+| `provider/factory.rs`, `provider/factory/` | Provider-string grammar and model construction: `routing`, `tiers`, `primary_cloud`, `access_gates`, `credentials`, `managed_backend`, `local_runtime`, `cloud_slug`, `subprocess_providers`, `discovery`, `chat_model`, `turn_model`. |
+| `provider/openhuman_backend_model*.rs` | Managed backend `ChatModel`, its call path and its usage/billing projection. |
+| `provider/openai_codex.rs` | Codex routing metadata for the `openai` slug when Codex OAuth is connected. |
+| `provider/error_code.rs`, `provider/error_classify.rs` | Managed `errorCode` extraction and Sentry ownership; OpenHuman policy over TinyInference's classifier. |
+| `provider/fallback_diagnostics.rs` | Explains background-role fallback when it hits a provider with no credentials. |
+| `provider/ops/` | `http_error/` (classification and `api_error`), `models/` (model catalog listing, local-runtime and OpenRouter entries), `provider_factory.rs` (`ProviderRuntimeOptions`, `list_providers`). |
+| `provider/types.rs` | Host DTOs kept at product and RPC boundaries: `ChatResponse`, `ProviderDelta`, `BilledUsage`, `AGENT_TURN_MAX_OUTPUT_TOKENS`. |
+| `host_runtime/` | Product policy, RPC and speech bindings over `tinyinference_local`. See [`host_runtime/README.md`](host_runtime/README.md). |
+| `embedding_host/` | Embedding provider selection (managed, Voyage, OpenAI, Cohere, Ollama, custom, noop) and the `embeddings.*` RPC. See [`embedding_host/README.md`](embedding_host/README.md). |
+| `tokenjuice/` | Host adapter for the TinyJuice tool-output compression module, the `juice_retrieve` recovery tool, and the `tokenjuice.*` RPC. See [`tokenjuice/README.md`](tokenjuice/README.md). |
+| `http/` | OpenAI-compatible `/v1` endpoint. `server.rs` (router and handlers) is behind the `http-server` feature; `types.rs` and `EXTERNAL_OPENAI_COMPAT_PROVIDER` stay ungated because `core::auth` reads them. |
+
+## Key types and entry points
+
+- `create_chat_model`, `create_chat_model_with_model_id`, `create_chat_model_from_string` (in
+ `provider/factory/chat_model.rs`) build a model for one-shot work from a role or an explicit
+ provider string.
+- `create_turn_chat_model*` (`provider/factory/turn_model.rs`, crate-private) build the model for
+ an agent turn.
+- `provider_for_role` (`provider/factory/routing.rs`) returns the configured provider string for a
+ role. `resolve_model_for_hint` and `role_for_model_tier` (`provider/factory/tiers.rs`) handle
+ `hint:*` markers.
+- `probe_inference_readiness` (`provider/factory/chat_model.rs`) checks that a role can actually
+ run: it builds the model and, for the managed backend, makes one cheap completion.
+- `BYOK_INCOMPLETE_SENTINEL` (`provider/factory.rs`) marks a BYOK route with missing pieces.
+- `OpenHumanBackendModel` (`provider/openhuman_backend_model.rs`) is the managed backend model.
+- `host_runtime::global` (`host_runtime/core.rs`) returns the `LocalAiService` singleton.
+- `agent_chat_for` and `agent_chat_reply_for` (`host_runtime/ops/agent_chat.rs`) run an agent turn
+ natively. `INFERENCE_AGENT_CHAT` (`schemas.rs`) is the wire method name hosts reference.
+- `context_window_for_model` (`model_context.rs`) and `resolve_context_window`
+ (`context_window.rs`) answer window sizes.
+- `api_error` (`provider/ops/http_error/dispatch.rs`) is the single entry for turning a failed
+ provider response into a classified error.
+- `auth_error_registry::{record, clear, snapshot}` track rejected BYO keys.
+- `test_provider_override` (`provider/factory.rs`) injects a mock `ChatModel` process-wide. It
+ exists only under `cfg(test)` or the `e2e-test-support` / `rss-bench` features.
+
+## RPC / CLI surface
+
+All controllers are pushed into the registry in `core/all.rs` under `DomainGroup::Inference`.
+
+`inference.*` from `schemas.rs`:
+
+- Models and routing: `resolve_model`, `list_models`, `test_provider_model`.
+- Status and settings: `status`, `get_client_config`, `update_model_settings`,
+ `update_local_settings`, `diagnostics`, `provider_auth_errors`.
+- One-shot inference: `summarize`, `prompt`, `vision_prompt`, `analyze_sentiment`.
+- OpenAI/Codex OAuth: `openai_oauth_start`, `openai_oauth_complete`,
+ `openai_oauth_import_codex_cli`, `openai_oauth_status`, `openai_oauth_disconnect`.
+- Claude Code: `claude_code_status`, `claude_code_auth_status`, `claude_code_settings`,
+ `claude_code_set_full_access`.
+
+`inference.*` from `host_runtime/schemas.rs`: `agent_chat`, `agent_chat_simple`, `transcribe`,
+`transcribe_bytes`, `tts`, `test_connection`.
+
+`embeddings.*` from `embedding_host/schemas.rs`: `get_settings`, `update_settings`, `set_api_key`,
+`clear_api_key`, `embed`, `test_connection`.
+
+`tokenjuice.*` from `tokenjuice/schemas.rs`: `detect`, `compress`, `cache_stats`, `retrieve`,
+`settings_get`, `settings_update`, `savings_stats`, `savings_reset`.
+
+Legacy names such as `openhuman.local_ai_*`, `openhuman.update_local_ai_settings` and
+`openhuman.providers_list_models` are rewritten to the canonical methods by
+`core/legacy_aliases.rs` (and `app/src/services/rpcMethods.ts` on the frontend). The download,
+asset-status, Piper-installer, preset and device-profile controllers no longer exist.
+
+Outside JSON-RPC, `http::router()` serves `/v1/chat/completions` and `/v1/models`.
+
+## Events and persistence
+
+This domain publishes but does not subscribe; there is no `bus.rs`. `SessionExpired` comes from
+`provider/ops/http_error/auth_failure.rs` and `provider/openhuman_backend_model.rs`.
+`ProviderApiKeyRejected` comes from `auth_failure.rs`, gated by `auth_error_registry`.
+
+There is no `store.rs`. Routing, provider and local settings persist through `config` (`config/ops/
+model.rs` and friends). Provider keys live in the encrypted auth-profile store under
+`provider:<slug>` (`provider/factory/credentials.rs` also tries the legacy bare `<slug>`). The
+built-in BYOK presets behind Connections, API keys, LLM are in `config/schema/cloud_providers.rs`.
+OpenHuman stores no model artifacts.
+
+## Boundaries
+
+- `tinyinference` (vendored at `vendor/tinyagents/vendor/tinyinference`) owns provider wire
+ clients, model capability hints, temperature rules, provider-neutral error classification,
+ endpoint probing for local runtimes, effective model-id resolution, and embedding providers.
+ Fix provider-transport bugs there.
+- `tinyagents` owns the agent loop, model-call retries and the Claude Agent SDK and Claude Code
+ providers (`tinyagents_harness::providers::{claude_agent_sdk, claude_code}`). This domain only
+ supplies routing and the MCP endpoint for Claude Code.
+- `tinyjuice` owns compression; `tokenjuice/` is only the host adapter.
+- OpenAI OAuth flow and token storage belong to `security/credentials/openai_oauth/`.
+- Privacy Mode policy and egress descriptors come from `security::live_policy` and
+ `security::egress`; the factory only enforces them at `access_gates.rs`.
+- Voice capture, dictation and the STT engine choice belong to `crate::voice`.
+- Error classification ladders for chat replies live in `web_chat::web_errors`; this domain owns
+ only the copy table.
+
+## Gotchas
+
+- `update_model_settings` drops reserved cloud-provider slugs (the `openhuman`/`cloud` built-ins
+ the frontend echoes back), and `config::ops::model::apply_model_settings` re-injects them from
+ stored config so they are not lost.
+- `inference.diagnostics` returns its payload without the `{result, logs}` envelope, matching the
+ legacy `local_ai_diagnostics` shape that `json_rpc_e2e` asserts on.
+- `ops.rs` logs known provider and user-config failures (unknown provider, 401, 429,
+ model-not-found) at `warn!` to keep them out of Sentry. Only unclassified failures reach
+ `error!`.
+- A managed response carrying an `errorCode` is owned by the backend for Sentry purposes; the core
+ must not double-report it, except for a backend-flagged malformed `BAD_REQUEST`.
+- `test_provider_override` is process-global. Tests that install it must run serially and drop the
+ guard.
+- `http::router()` only exists with the `http-server` feature. `INFERENCE_COMPILED_IN` reports
+ whether the `inference` feature (and the `cpal` audio stack) was compiled in.
+- There is no local-runtime shutdown step because OpenHuman never spawns one.
+
+## Tests
+
+Tests sit beside their modules as `<module>_tests.rs` (for example `ops_tests.rs`,
+`context_window_tests.rs`, `provider/factory_tests.rs`). Tests that touch the runtime singleton or
+shared config take `inference_test_guard()` / `inference_test_guard_async()` from
+`host_runtime/mod.rs`. Run them with `cargo test -p openhuman inference::` or
+`pnpm debug rust inference`. JSON-RPC behavior is covered in `tests/json_rpc_e2e.rs`.