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
GitBook: Export content from OpenHuman
Steven Enamakelb95dedf395b7
diff --git a/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/demo.png b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/demo.pngnew file mode 100644index 0000000000..ea63fb287aBinary files /dev/null and b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/demo.png differdiff --git a/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/image.png b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/image.pngnew file mode 100644index 0000000000..fb25afeb78Binary files /dev/null and b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/image.png differdiff --git a/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/orchestration.png b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/orchestration.pngnew file mode 100644index 0000000000..93a9131dd3Binary files /dev/null and b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/orchestration.png differdiff --git a/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/workflows.png b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/workflows.pngnew file mode 100644index 0000000000..e83e42ae16Binary files /dev/null and b/docs/gitbooks/docs/gitbooks/en/.gitbook/assets/workflows.png differdiff --git a/docs/gitbooks/docs/gitbooks/en/README.md b/docs/gitbooks/docs/gitbooks/en/README.mdnew file mode 100644index 0000000000..807de16705--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/README.md@@ -0,0 +1,38 @@+---+description: >-+ Personal AI super intelligence for your desktop: a brain that builds a+ persistent memory of your life, an orchestrator of agent fleets and workflows,+ and a deep researcher across the services you conn+icon: diamond+---++# Welcome to OpenHuman++<figure><img src=".gitbook/assets/demo.png" alt=""><figcaption></figcaption></figure>++OpenHuman is an open-source AI assistant built to be three things most assistants aren't: **a brain** (a persistent, local, readable memory of your world); **an orchestrator** (durable agent graphs, visual workflows, sub-agent fleets, and [end-to-end encrypted agent-to-agent sessions](features/orchestration.md)); and **a deep researcher** (it sweeps your data and the web before you finish asking). It's built on a Rust core wrapped in a Tauri desktop shell, and licensed under GNU GPL3. The source is at [github.com/tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman).++Every model in the world, all 200+ of them, shares the same fundamental limitation: they are stateless. You type a prompt, get a response, and the context evaporates. Even the ones with "memory" store a few bullet points. A few bullet points is a sticky note, not intelligence.++OpenHuman solves this with a stack that's calmly, deliberately different:++* [**Memory you choose and can inspect**](features/memory.md)**.** Documents (folders, files, links, GitHub, RSS, connected apps), conversations and learnings are stored in a memory engine, either hosted TinyHumans or your own CortexDB. The agent asks it questions with citations, and a short brief about you opens every new chat. You can see and delete everything stored.+* [**Third-party integrations**](features/integrations/)**.** One-click OAuth into Gmail, GitHub, Slack, Notion, Stripe, Calendar, Drive, Linear, Jira and more, across the 119 managed-auth toolkits the app knows about, with no API keys to wire by hand and no plugin marketplace to navigate.+* **An agent built for big data.** [Smart token compression (TokenJuice)](features/token-compression.md) compacts verbose tool output before it ever enters the model's context, so sweeping through your last six months of email costs single-digit dollars. [Automatic model routing](features/model-routing/) sends each task to the right model, `hint:reasoning` to a frontier model, `hint:fast` to a cheap one, vision to vision, all under one subscription and one TinyHumans API key. Optional [local AI via Ollama or LM Studio](features/model-routing/local-ai.md) keeps supported workloads on-device, and every LLM, embedding, memory, and web search engine underneath is swappable through config rather than code.+* **Fast, cheap decisions.** Before an agent burns a full model call choosing which of dozens of tools to use, a small classifier called Jev scores the options and answers in about 150 milliseconds instead of generating text. It shortlists tools, decides whether a tool is needed at all, and drives routine browser steps, so the expensive model gets called for the things that actually need it.+* [**Batteries included**](features/native-tools/)**.** A complete agent toolbelt is wired in by default: [web search](features/native-tools/web-search.md), a [web-fetch scraper](features/native-tools/web-scraper.md), a full [coder toolset](features/native-tools/coder.md) (filesystem, git, lint, test, grep), [browser & computer control](features/native-tools/browser-and-computer.md), [cron & scheduling](features/native-tools/cron.md), [memory tools](features/native-tools/memory-tools.md), [agent coordination](features/native-tools/agent-coordination.md) for spawning sub-agents, and [native voice](features/native-tools/voice.md), STT in, TTS out, mascot lip-sync, and a live voice agent you can interrupt mid-sentence. No "install a plugin to read files" friction.+* [**Workflows**](features/workflows.md)**.** Durable, visual automations on the open-source tinyflows engine. Describe the automation in chat, the agent proposes a workflow graph, you review it on a canvas and save it. Flows fire on schedules or live app events, pause at approval gates, and resume exactly where they stopped, with full step-by-step run history.+* [**A harness that finishes the job**](developing/architecture/agent-harness.md)**.** Every turn runs on the open-source tinyagents graph engine: durable checkpointing (sub-agents pause for your input and resume, instead of dying), a no-progress circuit breaker that stops identical-call loops and hands back a root-cause summary, classified tool failures rendered as actionable timeline cards, and durable, replayable run journals with per-call token and cost accounting.+* **Light enough to run in-process.** The Rust core that powers all of this runs in the same process as the desktop app rather than as a bag of background services: we've measured 500 agents alive in one process at about 1.77 MiB of marginal memory each, and thousands of agents on a single box is the direction it's heading. The same core ships as a library ([`crates/openhuman-embed`](../../../../../crates/openhuman-embed/), with a [one-key setup](developing/tinyhumans-api-key.md)), so another product can boot a runtime and add agents to it in a few lines of Rust. See [Performance](developing/performance.md) (with the public [benchmarks repo](https://github.com/tinyhumansai/openhuman-benchmarks)), [Pluggable engines](developing/engines.md), and [Embedding OpenHuman](developing/embedding.md) if you're building on top of it.+* [**Privacy Mode**](features/privacy-and-security/privacy-mode.md)**.** One switch, enforced in the Rust core: local-only mode structurally blocks every cloud model call and permits only on-device runtimes (Ollama, LM Studio, MLX, local OpenAI-compatible).+* **Simple, UI-first.** A clean desktop experience and short onboarding paths take you from install to a working agent in a few clicks, no config-first setup, no terminal required. The agent has [a face](features/mascot.md): a desktop mascot that speaks, reacts to its surroundings, remembers you across weeks, and keeps thinking in the background even when you've stopped typing.++Together, these turn OpenHuman into something fundamentally different from a chatbot. It is an AI agent that consumes large amounts of personal data at low cost, maintains a persistent and evolving understanding of your world, and takes proactive actions on your behalf.++{% hint style="warning" %}+OpenHuman is not AGI. But it is a meaningful architectural step closer, with better memory, better orchestration, and better tooling.+{% endhint %}++## For developers++Building on or contributing to OpenHuman? Start with [Getting set up](developing/getting-set-up.md), then [Building the Rust core](developing/building-rust-core.md) and the [Architecture](developing/architecture/) overview. To use the core from your own Rust product, read [Embedding OpenHuman](developing/embedding.md) and [One TinyHumans API key](developing/tinyhumans-api-key.md). [Loadable modules](developing/loadable-modules.md) covers the native module system, and [Performance and footprint](developing/performance.md) has the numbers; the benchmark rig and results are public at [tinyhumansai/openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks).diff --git a/docs/gitbooks/docs/gitbooks/en/SUMMARY.md b/docs/gitbooks/docs/gitbooks/en/SUMMARY.mdnew file mode 100644index 0000000000..15d859c595--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/SUMMARY.md@@ -0,0 +1,105 @@+# Table of contents++## Overview++* [Welcome to OpenHuman](README.md)+* [Getting Started](overview/getting-started.md)+* [Roadmap](overview/roadmap.md)+* [Auto-update](overview/auto-update.md)+* [Troubleshooting Sign-In](overview/troubleshooting-sign-in.md)++## Guides++* [Guides](guides/guides/README.md)+ * [Create my personal AI assistant](guides/guides/personal-assistant.md)+ * [Use OpenHuman with a local model](guides/guides/local-model.md)+ * [Use multiple local LLM servers](guides/guides/multiple-local-llm-servers.md)+ * [Keep sensitive data private](guides/guides/privacy-sensitive-data.md)+ * [Recover from a failed installation](guides/guides/recover-failed-installation.md)+ * [Move OpenHuman to a new PC](guides/guides/move-to-new-pc.md)+ * [Organize my project folders](guides/guides/organize-project-folders.md)+ * [Create a doctor-specific assistant](guides/guides/doctor-assistant.md)+ * [Create a safe companion for a child](guides/guides/child-safe-companion.md)++## Features++* [Chat](features/chat.md)+* [Memory](features/memory.md)+* [Connections](features/connections.md)+* [Settings](features/settings.md)+* [The Mascot](features/mascot.md)+* [Third-party Integrations](features/integrations/README.md)+ * [Triggers](features/integrations/triggers.md)+ * [MCP Servers & Skills](features/integrations/mcp-and-skills.md)+* [The Orchestrator](features/orchestration.md)+* [Workflows](features/workflows.md)+* [Messaging Channels](features/channels.md)+* [Goals & Todos](features/goals-and-todos.md)+* [Personalization & Self-Learning](features/personalization.md)+* [Themes & Theme Studio](features/theming.md)+* [Smart Token Compression](features/token-compression.md)+* [Automatic Model Routing](features/model-routing/README.md)+ * [Local models & bring your own key](features/model-routing/local-and-byok-models.md)+ * [Local AI (optional)](features/model-routing/local-ai.md)+* [Native Tools](features/native-tools/README.md)+ * [Web Search](features/native-tools/web-search.md)+ * [Web Scraper](features/native-tools/web-scraper.md)+ * [Coder](features/native-tools/coder.md)+ * [Documents](features/native-tools/documents.md)+ * [Image Tools](features/native-tools/image-tools.md)+ * [Image & Video Generation](features/native-tools/media-generation.md)+ * [Browser & Computer Control](features/native-tools/browser-and-computer.md)+ * [Cron & Scheduling](features/native-tools/cron.md)+ * [Voice](features/native-tools/voice.md)+ * [Memory Tools](features/native-tools/memory-tools.md)+ * [Third-party Integrations](features/native-tools/integrations.md)+ * [Agent Coordination](features/native-tools/agent-coordination.md)+ * [System & Utilities](features/native-tools/system-and-utilities.md)+* [Notifications & Activity](features/notifications-and-activity.md)+* [Wallet](features/wallet.md)+* [Hosting](features/hosting.md)+* [Billing, Cost & Usage](features/billing-and-usage.md)+* [iOS Companion](features/ios-companion.md)+* [Approval Gate](features/approval-gate.md)+* [Privacy & Security](features/privacy-and-security/README.md)+ * [Privacy Mode](features/privacy-and-security/privacy-mode.md)+ * [OS Keyring & Secret Storage](features/privacy-and-security/os-keyring-and-secret-storage.md)+* [Platform & Availability](features/platform.md)+* [Cloud Deploy](features/cloud-deploy.md)++## Developing++* [Overview](developing/developing.md)+* [Rust Quickstart](developing/quickstart.md)+* [Getting Set Up](developing/getting-set-up.md)+* [Architecture](developing/architecture/README.md)+ * [Deep Architecture Reference](developing/architecture/architecture.md)+ * [Agent Harness](developing/architecture/agent-harness.md)+ * [Flows on TinyAgents](developing/architecture/flows-on-tinyagents.md)+ * [Memory](developing/architecture/memory.md)+ * [MCP Registry](developing/architecture/mcp-registry.md)+ * [Security](developing/architecture/security.md)+ * [Frontend](developing/architecture/frontend.md)+ * [Tauri Shell](developing/architecture/tauri-shell.md)+* [Building the Rust Core](developing/building-rust-core.md)+* [Loadable modules](developing/loadable-modules.md)+* [Performance and footprint](developing/performance.md)+* [Pluggable engines](developing/engines.md)+* [Jev](developing/jev.md)+* [Embedding OpenHuman](developing/embedding.md)+* [One TinyHumans API key](developing/tinyhumans-api-key.md)+* [Hooks](developing/hooks.md)+* [MCP Server](developing/mcp-server.md)+* [Claude Code CLI provider](developing/claude-code.md)+* [Theming (Token System)](developing/theming.md)+* [Testing Strategy](developing/testing-strategy.md)+* [E2E Testing](developing/e2e-testing.md)+* [Agent Observability](developing/agent-observability.md)+* [Release Policy](developing/release-policy.md)+* [AgentBox marketplace deployment (historical)](developing/agentbox-deployment.md)+* [Chromium Embedded Framework (historical)](developing/cef.md)++## Legal++* [Terms & Conditions](legal/terms-of-use.md)+* [Privacy Policy](legal/privacy-policy.md)diff --git a/docs/gitbooks/docs/gitbooks/en/developing/agent-observability.md b/docs/gitbooks/docs/gitbooks/en/developing/agent-observability.mdnew file mode 100644index 0000000000..d90be4bcac--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/agent-observability.md@@ -0,0 +1,133 @@+---+description: Artifact-capture layer that makes E2E tests debuggable. Logs, traces, screenshots.+icon: eye+---++# Agent Observability++This doc describes the artifact-capture layer that makes the desktop app+inspectable by coding agents (Codex, Claude Code, Cursor) through the+existing WDIO / tauri-driver E2E harness (see [E2E Testing](e2e-testing.md)).++It is intentionally narrow: one canonical onboarding + privacy flow with+on-disk screenshots, page-source dumps, and mock backend request logs.++## TL;DR++```bash+bash app/scripts/e2e-agent-review.sh+```++Artifacts land under:++```text+app/test/e2e/artifacts/<ISO-timestamp>-agent-review/+ 01-welcome.png+ 01-welcome.source.xml+ 02-post-welcome.png+ 02-post-welcome.source.xml+ 03-post-onboarding.png+ 03-post-onboarding.source.xml+ 04-privacy-panel.png+ 04-privacy-panel.source.xml+ mock-requests-after-welcome.json+ mock-requests-after-onboarding.json+ mock-requests-after-privacy.json+ failure-<test>.png # only on failure+ failure-<test>.source.xml # only on failure+ meta.json # run metadata + checkpoint index+```++The script prints the resolved artifact directory at the end.++## Pieces++| Piece | Path | Role |+| ---------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| Helper | `app/test/e2e/helpers/artifacts.ts` | Run dir, `captureCheckpoint`, `captureFailureArtifacts`, `saveMockRequestLog` |+| WDIO hook | `app/test/wdio.conf.ts` (`afterTest`) | Always dumps screenshot + source on any failing test |+| Canonical spec | `app/test/e2e/specs/agent-review.spec.ts` | Welcome → onboarding → privacy panel with named checkpoints |+| Wrapper script | `app/scripts/e2e-agent-review.sh` | Build + run + print artifact dir |+| Stable selectors | `data-testid` on `OnboardingNextButton`, `Onboarding` overlay + skip button, `WelcomeStep`, `PrivacyPanel` | Agent-reliable navigation anchors |++## Environment overrides++| Variable | Effect |+| -------------------- | ------------------------------------------------------------------------------------------- |+| `E2E_ARTIFACT_DIR` | Force a specific run dir (skips auto-timestamped name) |+| `E2E_ARTIFACT_ROOT` | Parent dir for auto-generated run dirs (default: `app/test/e2e/artifacts`) |+| `E2E_ARTIFACT_LABEL` | Label used in the auto-generated run dir name (default: `run`; wrapper sets `agent-review`) |++## Using the helper from new specs++```ts+import { captureCheckpoint, saveMockRequestLog } from "../helpers/artifacts";+import { getRequestLog } from "../mock-server";++await captureCheckpoint("after-connect-click");+saveMockRequestLog("after-connect-click", getRequestLog());+```++`captureCheckpoint` numbers captures so the run dir reads chronologically.+`captureFailureArtifacts` is wired into `wdio.conf.ts` and fires+automatically on any failing test, specs should not call it directly.++## Inference on the wire: the capture proxy++Logs tell you a turn was slow; they do not tell you what the harness sent or+which endpoint answered. `scripts/debug/capture-first-inference.mjs`+(`pnpm debug capture`) is a loopback proxy between the core and its inference+backend that records both sides:++```bash+CAPTURE_ALL=1 pnpm debug capture # listens on 127.0.0.1:18765+# then, in another shell, point a core at it:+BACKEND_URL=http://127.0.0.1:18765 ./target/debug/openhuman-core run --port 7799+# or set api_url = "http://127.0.0.1:18765" in the user's config.toml+```++Every inference request body is written, numbered, under+`target/debug-logs/inference-sequence/` (the exact system prompt, tool+schemas and `prompt_cache_key` the harness assembled), and every response+yields one summary line and one JSONL record in+`target/debug-logs/inference-capture.jsonl`:++```text+[capture] #000 200 model=z-ai/glm-5.3-flash msgs=2 tools=19 served_by=StreamLake ttfb=7.38s total=8.43s prompt=12344 cached=12288 cache_key=tap-25675927a3f2160d+```++`CAPTURE_UPSTREAM=https://openrouter.ai` captures a direct BYOK OpenRouter+route instead of the hosted backend. Non-2xx response bodies are saved next to+the request dumps so an HTML 503 from an ingress is not lost behind a generic+"model error".++What to look for across the turns of one thread: `cache_key` must stay+identical (it is the harness's stable-prefix fingerprint and OpenRouter's+sticky-routing key), `served_by` should not change, and `cached` should+approach `prompt` from the second call on. Each of those drifting has been a+real bug (openhuman#6434). The proxy binds loopback only and refuses a+plaintext non-loopback upstream unless overridden, because it forwards the+bearer verbatim; `--help` lists every `CAPTURE_*` knob.++## Production agent traces are a separate mechanism++Everything above is about E2E artifacts on disk. For a real agent run, the+core can export trace spans to Langfuse instead: when+`observability.share_usage_data` is on (the default), a completed run's spans+go to the OpenHuman backend's Langfuse ingestion proxy over the same session+bearer every other backend call uses, and the backend forwards them to+Langfuse with the project keys injected server-side. Clients never hold+Langfuse credentials directly. Prompt and reply text ride along only while+`observability.agent_tracing.capture_content` is also on; turning it off keeps+metadata (names, timings, token and cost figures) but drops content. See+`crates/openhuman-core/src/agent/progress_tracing/langfuse.rs` and+`crates/openhuman-core/src/config/schema/observability.rs`.++## What is intentionally out of scope++- Visual baselines / image diffs across every component state.+- Screenshot capture on every click (too noisy).+- Live integrations (Gmail, Notion, Telegram); mock server only.+- New test framework / reporter.++Widen to more flows only after this loop proves out.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/agentbox-deployment.md b/docs/gitbooks/docs/gitbooks/en/developing/agentbox-deployment.mdnew file mode 100644index 0000000000..b88441f211--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/agentbox-deployment.md@@ -0,0 +1,118 @@+---+description: >-+ The removed AgentBox container deployment surface, kept as the record of+ what it was and which test pins its absence.+icon: box-archive+---++# AgentBox marketplace deployment (historical)++This page describes a container surface that no longer exists in+`openhuman-core`. A regression test,+`agentbox_run_and_jobs_paths_are_no_longer_public` in+`crates/openhuman-rpc/src/server/auth_tests.rs`, asserts that `/run` and+`/jobs/{job_id}` are gone and pins the reason in a comment: the AgentBox+marketplace surface moved out of this codebase. `OPENHUMAN_AGENTBOX_MODE`+has no remaining reader anywhere in `crates/openhuman-core/src` today, even+though the Dockerfile and `.env.example` still mention it; those references+are themselves stale and due for cleanup.++If you need to run OpenHuman on GMI Cloud's AgentBox marketplace today, this+is not the current integration path; check with the team that owns the+GMI Cloud deployment for where that surface lives now. The rest of this page+is kept as a historical record of how the integration worked before removal,+in case you are debugging an older build that still has it.++## Container contract (as it worked before removal)++When `OPENHUMAN_AGENTBOX_MODE=1`, the core HTTP server exposes:++- `POST /run`: accept work, return `202 { "job_id": "<uuid>" }`. Body shape:+ `{ "payload": { "message": "<string>", "thread_id": "<optional string>" } }`.+- `GET /jobs/{job_id}`: return `{ "status": "pending|running|completed|failed", "result": ..., "error": ... }`.+- `GET /health`: liveness.++Both `/run` and `/jobs/*` are unauthenticated at the container boundary;+AgentBox's edge handles auth before traffic reaches us.++## The 4-step register wizard++In the AgentBox console:++1. **Basic Info**: name `OpenHuman`, description, listing identity.+2. **Infrastructure**: Docker image source (push tagged builds to your+ chosen registry, see "Image push" below), compute tier, region. Enable the+ "GMI MaaS" toggle so the platform injects `GMI_MAAS_BASE_URL` and+ `GMI_MAAS_API_KEY` at runtime.+3. **Env Variables**: set:+ - `OPENHUMAN_AGENTBOX_MODE=1`+ - (optional) `OPENHUMAN_AGENTBOX_JOB_TIMEOUT_SECS` (default 600)+ - `GMI_MODELS` to the marketplace-approved model id (e.g.+ `deepseek-ai/DeepSeek-V4-Pro`).+ - `OPENHUMAN_WORKSPACE` to a writable container path (e.g. `/home/openhuman/.openhuman`).+ - `RUST_LOG=info` (or `debug` while shaking out the first deploy).+4. **Review & Register**: confirm and test from the console panel.++> ⚠️ The platform API key is shown ONCE on the registration confirmation+> screen. Save it to your secrets manager immediately. It is NOT recoverable+> from the console after that.++## Image push++Build and push from `main` using the existing `Dockerfile`:++```bash+docker build -t <registry>/openhuman-core:<tag> .+docker push <registry>/openhuman-core:<tag>+```++First deploy takes 10 to 25 minutes to reach `running`; later deploys are faster.++## Long-running requests++AgentBox treats requests >2 min as long-running. OpenHuman handles this with+**polling** per AgentBox's documented pattern: the agent runtime is invoked+inside the worker task, capped by `OPENHUMAN_AGENTBOX_JOB_TIMEOUT_SECS`+(default 10 minutes). No streaming.++Polling clients should:++1. `POST /run` and capture `job_id`.+2. `GET /jobs/{job_id}` every 1 to 3 seconds.+3. Stop when `status` is `completed` or `failed`.+4. Note: terminal jobs are retained for 1 hour after completion, then+ garbage-collected. Long pauses between poll and read may return `404`.++## Local smoke test++```bash+OPENHUMAN_AGENTBOX_MODE=1 \+GMI_MAAS_BASE_URL=https://api.gmi-serving.com \+GMI_MAAS_API_KEY=sk-... \+GMI_MODELS=deepseek-ai/DeepSeek-V4-Pro \+./target/debug/openhuman-core serve &++curl -X POST http://127.0.0.1:7788/run \+ -H 'content-type: application/json' \+ -d '{"payload":{"message":"hello"}}'++# Then poll the returned job_id:+curl http://127.0.0.1:7788/jobs/<job_id>+```++## Troubleshooting++- `404 job not found` after a successful submit: retention window (1h) has+ elapsed, or the container restarted (in-memory store is not durable in v1).+- `status: "failed"`, `error: "agentbox: agent runtime bridge not wired"`:+ the production invoker stub from before Task 9 landed; rebuild against a+ current `main`.+- `status: "failed"`, `error: "job timeout after Ns"`: the agent invocation+ exceeded `OPENHUMAN_AGENTBOX_JOB_TIMEOUT_SECS`. Bump the env var on the+ next deploy.+- `[agentbox::gmi] not registering GMI MaaS provider: missing/blank: GMI_MAAS_API_KEY`:+ the platform did not inject the key. Re-check the wizard's "MaaS+ integration toggle" in Step 2.+- `[agentbox::gmi] current-thread runtime detected, skipping provider registration`:+ the core was booted in a single-threaded tokio runtime. Use the standard+ `serve` subcommand, which spawns a multi-thread runtime.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/README.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/README.mdnew file mode 100644index 0000000000..2cb63aa2d5--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/README.md@@ -0,0 +1,101 @@+---+description: >-+ High-level shape of the OpenHuman system (desktop shell, Rust core, Memory+ Tree, agent loop). Pointer to the deep developer architecture in the repo.+icon: code-branch+---++# Architecture++OpenHuman is open-sourced under GNU GPL3. This page is the high-level shape of the system; the deep developer architecture lives in [deep architecture reference](architecture.md) in the repo.++## The shape++OpenHuman is a **React + Tauri v2 desktop app** with a **Rust core** doing the heavy lifting, in the same process rather than as a separate service.++```+┌──────────────────────────────────────────────────────────────────┐+│ Tauri shell (crates/openhuman-app/) │+│ • windowing, OS integration, embedded core lifecycle (tokio task)│+│ • global hotkeys, PTT/dictation overlays, deep links │+└──────────────────────────────────────────────────────────────────┘+ │ JSON-RPC (loopback HTTP) ↕+┌──────────────────────────────────────────────────────────────────┐+│ Rust core (crates/openhuman-core/, in-process, no binary) │+│ • Memory v2 (engine binding, recall/fetch/store, turn lifecycle) │+│ • Integration adapters + memory source sync │+│ • Provider router (model routing) │+│ • TokenJuice compression │+│ • Native tools (search, fetch, fs, git, …) │+│ • Voice (STT in, TTS out, live voice agent) │+└──────────────────────────────────────────────────────────────────┘+ │+┌──────────────────────────────────────────────────────────────────┐+│ React frontend (app/src/) │+│ • Screens, navigation │+│ • Talks to core over `coreRpcClient` │+│ • No business logic - presentation only │+└──────────────────────────────────────────────────────────────────┘+```++**Where logic lives:**++* **Rust core**. All business logic: Memory, integrations, model routing, tools, voice. Authoritative.+* **Tauri shell**. Windowing, process lifecycle, IPC. A delivery vehicle, not where features live.+* **React frontend**. UI and orchestration. Calls into core via JSON-RPC: `coreRpcClient` `fetch()`es `http://127.0.0.1:<port>/rpc` directly; only non-loopback plain-`http://` runtimes go through the shell's `relay_http_rpc` command (the `openhuman-rpc` HTTP client).++Running the core in-process instead of behind a socket is also why it's cheap to run many agents at once: no per-agent OS process, no per-agent socket. See [Performance](../performance.md) for the measurements and [Embedding OpenHuman](../embedding.md) for using the same core as a library outside the desktop app.++## Crates++* [`crates/openhuman-app/`](../../../../../../../crates/openhuman-app/) - Tauri v2 desktop host; excluded from the root workspace, built from its own manifest.+* [`crates/openhuman-core/`](../../../../../../../crates/openhuman-core/) - Cargo package `openhuman`: business domains, the controller contract and in-process dispatch, `CoreBuilder`/`CoreRuntime`. It is a library: no binary, no JSON-RPC server, and no dependency on `tinyhumans-sdk`.+* [`crates/openhuman-embed/`](../../../../../../../crates/openhuman-embed/) - typed library facade (`openhuman_embed::Runtime` / `Agent`, with `Harness` as a one-agent shorthand) for embedding the core in another product.+* [`crates/openhuman-rpc/`](../../../../../../../crates/openhuman-rpc/) - JSON-RPC 2.0 over the core: the envelopes, the browser-origin allowlist, the HTTP client used by the app and TUI, and the whole server (axum router, auth middleware, Socket.IO, `/dev/connect`, the listener bind). The contract types themselves (`Outcome`, `ControllerSchema`, `StructuredRpcError`) live in the core.+* [`crates/openhuman-tinyhumans/`](../../../../../../../crates/openhuman-tinyhumans/) - the TinyHumans layer: the SDK-backed backend transport, the hosted RPC proxy domains, a `RuntimeBuilder` that boots connected, and the host-side login and session owner. The only crate allowed to depend on `tinyhumans-sdk`, and the first thing every host installs.+* [`crates/openhuman-cli/`](../../../../../../../crates/openhuman-cli/) - the `openhuman-core` binary, the developer and benchmark bins, and every root `tests/` and `examples/` target.+* [`crates/openhuman-tui/`](../../../../../../../crates/openhuman-tui/) - standalone terminal frontend that boots the core in-process.++The full table is under "Repository layout" in the [deep architecture reference](architecture.md); per-crate notes are in [`crates/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/crates/README.md).++## Data flow++1. **Connect**. OAuth into an [integration](../../features/integrations/). Backend stores the token; core never sees it in plaintext.+2. **Sync**. A [memory source](../../features/memory.md) (folder, file, link, GitHub, RSS, or a connected Composio toolkit) syncs on demand and on its own schedule.+3. **Read**. `tinymemory-sources` turns the source into documents, with an SSRF guard on links.+4. **Scrub**. Every engine the host binds is wrapped in `memory::guard::ScrubbingEngine`, which uses the `safety` feature of `tinymemory-integrations` to strip secrets and personal identifiers before a write leaves the process. The wrap happens where the engine is resolved, so it covers the tool, the RPC surface, source sync, backfill and import; a caller holding a `BoundEngine` and reaching past it is not covered, which is why resolution is the only sanctioned way to get one.+5. **Store**. The item goes to the selected engine (hosted TinyHumans or your CortexDB). Conversation turns are logged as they happen, learnings when the agent or you add one.+6. **Recall / Fetch**. The agent's `memory` tool asks the engine a question (with citations) or runs a raw hybrid search.+7. **Pack**. Before every turn, a token-budgeted memory pack is recalled and added to that turn's model request only, never to the transcript.+8. **Forget**. Items are removed by id from the Memory page or the tool.+9. **Compress**. Tool output and large source data go through [TokenJuice](../../features/token-compression.md) before entering LLM context.+10. **Route**. The [router](../../features/model-routing/) picks the right provider and model for the task hint, one of several [pluggable engines](../engines.md) the core chooses at runtime.++## Privacy boundary++Stays on your machine:++* Workspace config and persona files.+* Audio capture buffers and any local model state.++Goes through the OpenHuman backend (under one subscription, and one TinyHumans API key for embedders):++* LLM calls (model providers).+* Web search proxy.+* Integration OAuth and tool proxying.+* TTS streaming.++See [Privacy & Security](../../features/privacy-and-security/) for the full picture, and [One TinyHumans API key](../tinyhumans-api-key.md) for what that single key covers.++## Open source++* **Repo:** [github.com/tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman). GNU GPL3.+* **Issues and PRs** are welcome. The project is in early beta.+* For contributors, the canonical developer guide is [deep architecture reference](architecture.md).++## Further reading++* [Agent harness](agent-harness.md), [Memory](memory.md) and [Security](security.md) for the deep dives.+* [Frontend](frontend.md) and [Tauri shell](tauri-shell.md) for the two outer layers.+* [Loadable modules](../loadable-modules.md) and [Pluggable engines](../engines.md) for what plugs into the core.+* [`AGENTS.md`](https://github.com/tinyhumansai/openhuman/blob/main/AGENTS.md) for the repo-wide rules, including which `vendor/` submodule owns what.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/agent-harness.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/agent-harness.mdnew file mode 100644index 0000000000..b3487fcf53--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/agent-harness.md@@ -0,0 +1,618 @@+---+description: >-+ How an agent turn actually runs - the tool-call loop, sub-agent dispatch,+ archetypes, triage, hooks, and the cost/budget machinery around them.+icon: layer-group+---++# Agent Harness++`crates/openhuman-core/src/agent/` is the host side of an agent turn: the tool-call loop and its dialects, sub-agent dispatch and archetypes, sessions and resume, triage, hooks, interrupts and cost accounting, all wrapped around the TinyAgents harness rather than reimplementing it.++## Embedding OpenHuman as a library++`openhuman_embed` exposes a two-step API. `Runtime::builder()` boots one in-process core per process, background services, registered domain families, backend URL and the TinyHumans API key, and `Runtime::agent(spec)` instantiates any number of agents on it. Each `AgentSpec` fully describes one agent: provider endpoint and model, access tier, `action_dir`, MCP servers, its own in-process tools, skill bundles, system prompt, tool scope, sandbox mode, allowlists, and a narrowed `DomainSet` / `ToolGroups`. A runtime identifies as `HostKind::Library`: inference does not depend on OpenHuman app login, including inference-readiness checks for workflow agent nodes.++### An embedder's own tools++`AgentSpec::tools` takes the host's own `Box<dyn Tool>` objects, which reach the model as real tools, their own schema on the wire, called by their own name. Before it existed the only road was `AgentSpec::mcp`, and the model paid for the indirection: a discovery call to learn what a server offers, and an `mcp_call_tool` envelope whose inner `arguments` object no provider can validate or constrain decoding against.++It takes a **factory**, not a belt. `Agent` is `Clone` and `Box<dyn Tool>` is not, and the session behind a spec is rebuilt from `Config` on every turn, so nothing holding a `dyn Tool` could survive in between. The closure therefore runs once per turn, which also means a host whose tools belong to something shorter-lived than the agent (one episode, one room, one assignment) can return a different belt each time instead of registering a second agent.++Implement `Tool` through `openhuman_embed::Tool`, not by depending on `tinytools` directly: a second path to that crate produces incompatible Rust types, and a tool built against it cannot be handed to a session at all.++One caveat on a varying belt. The prompt's tool catalogue is rendered from the same belt in the same build, so the two stay consistent on any turn that composes a prompt, but a **resumed** session reuses its persisted system messages, so a belt that moves under a long-lived thread is described by the prompt that thread opened with. Vary a belt only on turns that run on a session of their own.++Per-agent isolation is a context, not a second core. `Runtime::agent` clones the runtime's base `Config`, applies the spec, and derives a child `CoreContext` (`CoreContext::derive_with`) carrying that config, the agent's domain set, tool groups and skill-root policy. Every turn is dispatched under that context (`CoreRuntime::run_in` → `agent_chat_for` with an explicit `AgentDefinition`), so the config loader, the domain gate, the tool-group filter and skill discovery all read the agent's own settings. Transcripts are keyed by agent id and a turn resumes only its own thread.++Layout under a runtime-owned root: `<root>/config.toml` and the credential store; `<root>/workspace/` with the session database, `session_raw/` transcripts and each agent's `agents/<id>/skills/`; and `<root>/agents/<id>/action/` as each agent's default working root (a sibling of the workspace, never inside it).++`Harness` is the one-agent shorthand: a runtime plus one agent named `harness`. Build one runtime and issue concurrent `run` or `turn(...).send()` calls on its agents; do not build one core per agent. Each call owns a distinct session unless a prior session id is supplied.++Authentication in library mode is the TinyHumans API key (`RuntimeBuilder::api_key`), stored as an `api-key` auth profile beside the runtime's `config.toml`. Managed inference sends it as a bearer to the OpenAI-compatible endpoint; backend REST calls send `x-api-key`; there is no session JWT and nothing to expire. Agents that name their own `Provider` (BYOK) never touch it. The key covers every hosted feature, subject to its backend scopes: inference, embeddings, voice, search, media, Composio and the other integrations, channels and the socket. Only the session-bound `/auth/*` flows (OAuth connect, channel link tokens) still take `HarnessBuilder::session`.++`Workspace::Inherit` together with `Provider::inherit()` and no API key is deliberately not library-routed inference. It borrows the installed OpenHuman configuration and therefore keeps the installed application's session checks. Supply an explicit provider or an API key when embedding without app login.++Some settings remain runtime-wide for every agent (the live autonomy policy's `auto_approve*`, the approval gate switch, the sub-agent catalogue, the config sub-agents re-read); the crate README lists them under "Still runtime-wide".++> **Status (issue #4249, tinyagents migration):** the agent turn no longer runs on the in-tree `run_turn_engine` loop. **All three entry points (`Agent::turn`, the channel/CLI bus path, and `run_subagent`) now drive every turn through the published** [**`tinyagents`**](https://crates.io/crates/tinyagents) **2.1 agent-loop harness** via the adapter seam in [`crates/openhuman-core/src/agent/tinyagents/`](../../../../../../../crates/openhuman-core/src/agent/tinyagents/) (`run_turn_via_tinyagents_shared`). The legacy `run_turn_engine`, the three hand-rolled loops, `turn_engine_adapter`, and the custom `agent_graph/` engine described later in this page have been **removed**; the surviving shared seam, `TurnProgress`, lives in `agent/session_host/tool_progress.rs`. The dead `token_budget.rs` (context trimming is now `MessageTrimMiddleware`) and the vestigial `interrupt.rs` fence (cancellation is the tinyagents steering channel) are gone; policy **stop hooks** (budget / thread-goal / iteration caps) now fire through a `StopHookMiddleware` ([`tinyagents/stop_hooks.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/tinyagents/stop_hooks.rs)) that pauses the run on the first stop vote, and the channel route forwards live `AgentProgress` like the chat route.+>+> Multi-agent **orchestration** is expressed on tinyagents' **graph layer** via `graph::parallel::map_reduce`, the `spawn_parallel_graph` scaffold, and the shared `graph::orchestration` `TaskStore` lifecycle primitives re-exported from [`orchestration/mod.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/orchestration/mod.rs):+>+> * [`orchestration/delegation.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/orchestration/delegation.rs) is a `plan → execute ⇄ review → finalize` `CompiledGraph` (conditional routing, `RecursionPolicy`, durable `FileCheckpointer`, `CancellationToken`, `GraphTracingSink`);+> * the **workflow phase engine** fans each phase's agents out on the graph (`with_max_concurrency`), keeping the durable `WorkflowRun` ledger as the resume source of truth;+> * `spawn_parallel_agents` runs its fan-out through `spawn_parallel_graph` + `graph::parallel::map_reduce`;+> * the **agent-teams** member runtime is a conditional-routing graph (`execute → complete | fail → done`, [`agent_teams/runtime.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs));+> * the **detached-sub-agent** registry is backed by a typed `TaskStore` lifecycle ledger (Pending → Running → Completed/Failed/Cancelled).+>+> The sections below describing a bespoke `agent_graph/` module + per-agent `GraphBlueprint`s are **historical** (the pre-migration design) and are retained only for context.++## TinyAgents crate: features & compatibility++OpenHuman depends on the split TinyAgents 2.1 crate family by path into the vendored git submodule `vendor/tinyagents`, `tinyagents-harness` (features `sqlite`, `multimodal`, `builtin-tools`), `tinyagents-definition`, `tinyagents-graph` (`sqlite`), `tinyagents-registry`, `tinyagents-session`, `tinyagents-runtime`, `tinyagents-orchestration` and the optional `tinyagents-live`, plus `tinyinference` from `vendor/tinyagents/vendor/tinyinference`, so SDK changes can be tested in-tree before being PR'd upstream (see [`crates/openhuman-core/Cargo.toml`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/Cargo.toml)). The rationale, so future upgrades don't silently regress it:++* **Native TinyAgents model interface, OpenHuman-owned product policy.** Every live route is an `Arc<dyn ChatModel<()>>`: TinyAgents OpenAI-compatible clients cover wire-equivalent managed, local, and BYOK routes, while host `ChatModel` implementations cover Claude SDK/Code and Codex-specific transports. OpenHuman still owns credential resolution, OAuth, access gates, endpoint selection, egress disclosure, billing metadata, and error classification.+* **`sqlite` feature enabled with one native sqlite chain.** OpenHuman's root and Tauri Cargo worlds pin `rusqlite = "=0.40.2"` (`bundled`); the pinned Rust 1.96 toolchain provides the `cfg_select!` macro its build script needs, so no local patch of `rusqlite` / `libsqlite3-sys` remains. Both worlds resolve to a single `libsqlite3-sys` chain. Durable graph checkpoints run through TinyAgents' own `SqliteCheckpointer`; the earlier OpenHuman-owned `SqlRunLedgerCheckpointer` adapter has been retired (see [`orchestration/delegation.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/orchestration/delegation.rs)).+* **WhatsApp Web storage bridge.** `whatsapp-rust`'s Diesel-backed `sqlite-storage` feature links sqlite separately from rusqlite 0.40, so the optional `whatsapp-web` feature (now forwarded to `tinychannels/whatsapp-web`) currently builds against `wacore::store::InMemoryBackend` and logs that sessions are not durable. A rusqlite-backed durable WhatsApp store is required before treating Web sessions as persistent again.+* **`repl`/Rhai feature dropped.** TinyAgents no longer ships a `repl`/`rlm` scripting runtime, and OpenHuman no longer depends on it; there is no `rhai_workflows` tool. Rhai still appears as a direct dependency of `tinyflows` for its own JSON-query stack, unrelated to the agent harness (see "Language workflows" below, marked historical).+* **Ownership map:** model construction → `inference::provider::create_chat_model*`; durable graph checkpoints → TinyAgents' `SqliteCheckpointer`; generic detached executor state → `DetachedTaskRegistry`; controller-facing durability → OpenHuman SQL/JSON run ledgers (`running_subagents`, `workflow_runs`, `agent_teams`, `command_center`). The generic harness/graph/middleware/event primitives are used as-is.++The agent harness is the runtime that turns a user message (or a webhook fire, or a cron tick) into a complete, tool-using LLM interaction. It owns the tool-call loop, sub-agent dispatch, the trigger-triage pipeline, and the hook surface around them. It does **not** own provider HTTP transport, tool implementations, prompt-section assembly, or memory storage - those are separate domains the harness composes.++This page walks through what happens in one turn, then zooms in on each of the moving parts.++## The shape of a turn++Every turn - whether the user just typed a message, a Telegram webhook just fired, or a 9am cron just ticked - flows through the same lifecycle:++```+┌─ inbound ─────────────────────────────────────────────────────────┐+│ user message · channel inbound · webhook · cron · composio event │+└──────────────────────────┬────────────────────────────────────────┘+ │+ ▼ (external triggers only)+ ┌──────────────────────┐+ │ trigger triage │ classify → drop / notify /+ │ (small local LLM) │ spawn reactor / spawn orchestrator+ └──────────┬───────────┘+ │+ ▼+ ┌──────────────────────────────┐+ │ Agent::turn() │+ │ 1. resume transcript │+ │ 2. build system prompt* │+ │ 3. recall memory pack │+ │ 4. enter tool-call loop ────┼──► provider call+ │ 5. dispatch tool calls ────┼──► tool exec / sub-agent spawn+ │ 6. context guard / compact │+ │ 7. stop-hook check │+ │ 8. final assistant text │+ └──────────┬───────────────────┘+ │ async, after the user sees the reply+ ▼+ ┌─────────────────┐+ │ post-turn │ cost log · conversation+ │ hooks │ buffering for memory+ └─────────────────┘++* system prompt is built only on the first turn - subsequent+ turns reuse the rendered prompt verbatim so the inference+ backend's KV-cache prefix stays valid.+```++The rest of this page is the same diagram, expanded.++## Sessions and `Agent::turn`++A **session** is the live conversation an `Agent` instance is running. The `Agent` struct owns:++* The conversation history (system + user + assistant + tool messages).+* The provider client to call (model resolved by the [model router](../../features/model-routing/)).+* The tool registry visible to the model.+* The `memory` tool (when a memory engine is on), through which the model recalls, fetches, learns and forgets on demand.+* Per-turn budgets - max tool iterations, max payload size, max USD cost.+* Local action budget - a rolling hourly cap for side-effecting tool actions, read from `config.autonomy.max_actions_per_hour`.++`Agent::turn(user_message)` is the hot path. In one turn it:++1. **Resumes the session transcript** if this is a fresh process - re-loading the exact provider messages from disk so the inference backend's KV-cache prefix still hits.+2. **Builds the system prompt** (only on the first turn). This pulls in identity, soul, profile, memory, connected integrations, available tools, safety preamble - assembled by the prompt section builder.+3. **Recalls a memory pack.** TinyMemory's agent lifecycle logs the user turn and recalls a token-budgeted pack (learnings and beliefs, brain documents, this agent's history, other agents' turns), wrapped in `<memory-context>` and added to that turn's model requests ephemerally; it is never persisted in the transcript, so the prompt cache is unaffected. The model can still call the `memory` tool for a cited answer (see [Memory architecture](memory.md)).+4. **Enters the tool-call loop** (next section).+5. **Spawns post-turn hooks** in the background - the user gets their answer before cost logging and conversation logging finish.++The system prompt is **not** rebuilt on subsequent turns. Even cosmetic byte changes invalidate the KV-cache prefix and force a full re-prefill, so dynamic per-turn context (tool results, memory recall answers) is appended as user-visible message content rather than spliced into the system prompt.++#### The cacheable prefix is wider than the system prompt++Freezing the prompt is only one third of the contract, and the other two are easier to break because nothing about them looks like caching:++* **The tool block counts, and it comes **_**first**_**.** Every prefix cache in production renders the tool catalogue ahead of the conversation, a chat template has to put it somewhere the model reads before the first user turn. OpenAI's automatic cache, Anthropic's `cache_control` (tools → system → messages), DeepSeek's context cache and any vLLM/SGLang radix cache all work this way. So a `tools` array that changes between turns invalidates the frozen system prompt too, and the JSON key order of the request body (which puts `messages` before `tools`) says nothing about it. The mid-session Composio reconcile is still correct, a tool surface that lies about what the model can call is worse than a cold prefill, but it must fire only on a real capability change and be byte-stable otherwise. `connected_set_hash` sorts before hashing so a reordered backend response never reaches a rebuild, and `collect_orchestrator_tools` sorts the connected-toolkit enum for the same reason.+* **History must be append-only.** Turn N's serialization has to survive verbatim as the opening of turn N+1. `pair_tool_cycles` drops half-finished tool cycles at serialization time, so its verdict for an entry must depend only on that entry and its immediate neighbour, never on anything appended later, or an earlier message's presence flips retroactively and the prefix moves under the cache. Context compaction is the one deliberate exception; it rewrites the middle and pays for a re-prefill.++A resumed session's replayed prefix is folded into `Agent::history` rather than spliced into one request, so the request, the following turn and the persisted transcript all read the same sequence. Splicing it cost the conversation twice: the next turn went out without it, and the transcript written afterwards (serialized from `history`) held only the new turn, which the _next_ resume then read back, truncating the thread a little further on every restart.++#### A stable prefix only pays out when the wire says so++Keeping the bytes stable is necessary, not sufficient: the provider still has to be _told_ to cache, and two providers need telling explicitly.++* **Anthropic caches nothing without `cache_control` markers, and its OpenAI-compatible endpoint cannot carry them**, Anthropic documents prompt caching as unsupported on that path and reports `prompt_tokens_details` as always empty. A `cloud_providers` entry with `auth_style = "anthropic"` is therefore built as the crate's native Messages adapter (`tinyinference_llm::providers::anthropic`), which places markers on the last tool, the last system block, and the final message so a growing tool loop reuses the previous iteration's cache rather than only the system prompt. The one exception is text mode (`native_tools = false`, prompt-guided tools), which only the Chat Completions adapter implements and which keeps the compat client, and so keeps paying full price.+* **OpenRouter forwards markers to Anthropic and Gemini** but adds none itself; hosted OpenAI rejects unknown content-part fields. The OpenRouter slug (and any endpoint on `openrouter.ai`) enables `OpenAiModel::with_explicit_cache_control`, which marks the last system and last user message; every other Chat Completions endpoint stays unmarked.+* **The routing hint is separate from the markers.** The harness derives a `prompt_cache_key` from the declared stable prefix and puts it in `provider_options`, so every turn of a thread, and every sub-agent sharing its system prompt and tool set, routes to the same cache shard on providers that shard (OpenAI's `prompt_cache_key`). Adapters that have no such concept drop it. The managed backend receives it as a top-level body field alongside `thread_id`.++All three hang off `RunPolicy::cache.protect_prompt_prefix`, which the host sets unconditionally, and off the cacheable prefix the tinyagents loop declares on every request from the session's frozen system prefix (system prompt tiers, then the tool catalogue); the host has no middleware of its own for this. Until tinyagents began stamping that effective policy onto the outgoing request, both readers consulted `request.cache_policy` alone, always `None` here, so the flag was diagnostic only and no marker or key ever reached the wire. The `[cache]` debug line on every model call now reports whether a key was injected and how many cacheable segments were declared; `cache_read_tokens` on the usage that comes back is the number that proves it worked.++Measure this rather than reasoning about it. `CAPTURE_ALL=1 node scripts/debug/capture-first-inference.mjs` records a whole session's requests, `scripts/debug/run-multi-turn-capture.mjs` drives a multi-turn thread through the production RPC, and `scripts/debug/audit-inference-prefix.mjs` reports the first divergence and attributes it. A single-turn capture cannot see any of these, the question is never what turn 1 costs, it is whether turn 2 can reuse it.++### AGENTS.md project instructions++Alongside identity/soul/profile/memory, the system prompt pulls in **AGENTS.md** instruction files, OpenHuman's analog of Claude Code's `CLAUDE.md` / Codex's `AGENTS.md`. Two layers are loaded **once**, at system-prompt build time (never re-read per turn, so the frozen-prefix / KV-cache contract holds):++* **Global**, `<workspace_dir>/AGENTS.md`, the user's OpenHuman workspace (where `SOUL.md` / `USER.md` live). Applies to every run.+* **Project**, `<action_dir>/AGENTS.md`, the folder the agent is operating in. For sub-agent runs with a git-worktree override (`SubagentRunOptions.worktree_action_dir`), that override dir is the project layer instead.++The global layer renders first, the project layer second (project instructions layered after, taking precedence on conflict), under a `## Project instructions (AGENTS.md)` heading. When the two dirs resolve to the same path the file is loaded **once** (deduped). Missing / unreadable / empty files are silently skipped, and each layer is capped at `BOOTSTRAP_MAX_CHARS` (\~20 000 chars) with a `[... truncated]` marker so a large file can't crowd the prompt.++The loader is `agent::prompts::agents_md` (pure functions returning pre-loaded strings, bounded at read time so a pathological multi-MB file can't exhaust memory before the render-time cap); the strings are threaded onto `PromptContext` (`agents_md_global` / `agents_md_local`) and rendered by `AgentsInstructionsSection`, which sits after the user-files section and before the tool catalogue in the default and sub-agent builders. The **primary / orchestrator** agent and the other built-in dynamic agents (`PromptSource::Dynamic`) assemble their own body via `render_*` helpers, so the same `AgentsInstructionsSection` is injected centrally by `SystemPromptBuilder::from_dynamic`, appended after the agent's own body, before the central grounding contract, rather than by each `agents/<id>/prompt.rs` builder. The feature is gated by `agent.agents_md_enabled` (default **on**); when off, no AGENTS.md content is loaded or injected.++## The tool-call loop++Inside `Agent::turn`, the tool-call loop is the inner engine. Since issue #4249 it is the published **tinyagents** crate's `AgentHarness` loop, assembled per turn by `run_turn_via_tinyagents_shared` ([`crates/openhuman-core/src/agent/tinyagents/mod.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/tinyagents/mod.rs)). It runs up to the turn's iteration cap, resolved in `session_host/builder/iteration_cap.rs`: an explicit `[agent] max_tool_iterations_override` (or `OPENHUMAN_AGENT_MAX_TOOL_ITERATIONS`) wins, then the agent definition's cap (the orchestrator's is 200), then `max_tool_iterations` (default 10) for a turn with no definition. The model is told how many calls remain at 50% and 80% of the budget, and `inference_agent_chat` reports a capped turn with `hit_cap: true` and its `checkpoint` text:++```+loop {+ 1. context guard - if history is too big, microcompact / autocompact+ 2. stop-hook check - budget caps, max-iterations, custom kill switches+ 3. provider call - send messages + tool specs, stream the response+ 4. parse response - split assistant text from tool calls+ 5. if no tool calls - return final text+ 6. execute tool calls - dispatch each one (next section)+ 7. summarize oversize - route huge tool outputs through the summarizer agent+ 8. append results - push tool results into history, loop again+}+```++Every iteration emits a real-time `AgentProgress` event so the UI can render token-by-token streaming, "calling tool X" status, and per-iteration cost updates.++**One engine, three entry points.** The loop lives in TinyAgents. OpenHuman's chat host, channel/CLI route and sub-agent host each supply product policy at the adapter seam; spawned sub-agents enter through `agent/subagent_host`, which drives the neutral `tinyagents_orchestration::subagent::SubagentDriver` rather than an OpenHuman runner. The host owns provider/model choice, tool and security narrowing, workspace/artifact handling, progress and durable product projection. The neutral driver owns lifecycle ordering, task-key coalescing and the exclusive pause-or-terminal persistence decision. This direct cutover is in progress: the removed `harness/subagent_runner` path must not return as a facade or compatibility export.++### Tool dispatch and tool-call dialects++`agent.tool_dispatcher` (overridable for one launch with `OPENHUMAN_TOOL_DISPATCHER`) picks how tools are spoken to the model. `auto` (the default) uses **native tool calling**, structured tool specs through the `ChatModel` adapter and structured calls back, whenever the provider profile supports it, and falls back to JSON-in-tag for prompt-guided providers such as local Ollama. `python` and `typescript` are opt-in: they render the catalogue as code signatures and read code-style calls back, but mis-parse on some models. The session composes its prompt for the chosen dialect and pins the same dialect on the turn harness, so a text dialect keeps its schemas off the wire and the harness recovers calls with the matching grammar.++Canonical `tinytools_agent::dialect::ToolDialect` implementations provide transcript-compatible parsing and rendering directly; OpenHuman converts durable/provider records only at those I/O boundaries:++* **Native** (`native`), structured tool-call fields.+* **XML** (`xml`), `<tool_call>{...}</tool_call>` tags in assistant text, with full JSON schemas in the prompt.+* **P-Format** (`pformat`), compact positional `<tool_call>name[0|a|1|b]</tool_call>` with `name[0|<a>|1|<b>]` signatures in the prompt; opt-in.+* **Code** (`python` / `typescript`), the catalogue is a list of function signatures (`def read_file(path: str, limit: int = None) -> str` or `function read_file(path: string, limit?: number): string;`) and the model writes a function call inside the tag: `read_file(path="src/main.rs", limit=20)` or `read_file({path: "src/main.rs", limit: 20})`. Compact like P-Format but a syntax small code-trained models already write; `python` is the default.++Every text dialect shares one parser: a `<tool_call>` body is tried as P-Format, then as a code call, then as JSON, so a model that mixes forms is still understood. Persisted session histories can contain suffixes in any of these shapes, so the session shell keeps the dispatcher around to parse and replay them faithfully when a transcript is resumed.++### Context management mid-loop++Long tool-calling chains can blow past the context window. Two layers handle that:++* **Tool-result budget** - every tool result is checked against a per-call byte budget, enforced as tinyagents tool middleware. Anything over is hard-truncated with an explanatory marker so the model knows it didn't see the full output.+* **Microcompact / autocompact** - when total history is creeping toward the context window, tinyagents middleware (message trimming + the compression hooks installed in `tinyagents/middleware.rs` and `tinyagents/harness_context_ladder.rs`) compacts older turns into summaries before the next provider call. The compacted history keeps the system prompt and the most recent turns intact (KV-cache stability) and rewrites the middle.++### Oversized tool results - the summarizer detour++Some tool calls return enormous payloads - a Composio action dumping 200 KB of JSON, a web scrape returning 50 KB of markdown, a `file_read` over a multi-thousand-line log. Hard-truncating mid-payload drops whatever happens to land past the cut.++When a tool result exceeds the summarizer's threshold (`summarizer_payload_threshold_tokens`, default 4 000), TinyJuice's summary stage summarizes it before it enters the parent's history. The parent agent sees only the summary. There is one summarizer, and TinyJuice owns it: it decides when a summary is worth writing, writes the extraction prompt (identifiers and key facts first), caches identical summaries, trips a per-thread breaker after three failures, and offloads the original to CCR so the `juice_retrieve` footer can recover it exactly. The model call itself belongs to the host. `ToolOutputMiddleware` binds a unary child of the current turn through `PayloadSummarizer::prepare`, registers the capped model on a one-off harness (`tinyagents/payload_summarizer.rs`), and the module calls back through `MlHost.Generate`. Only the orchestrator carries a summary model, and it always sees `juice_retrieve`, even with the compaction router off, because a summary's footer names it. A result that qualified for a summary and did not get one is labelled as unsummarized, whether the module or the host failed, so the model does not re-run the tool for one. Summary reuse and the breaker are scoped to the thread, or to the run when there is no thread. Hard truncation remains the downstream backstop when summarization fails, or when the payload is so large that an LLM call on it makes no economic sense.++**Caller focus.** A tool can opt in to an optional `summary_focus` argument by adding `tokenjuice::focus::summary_focus_property()` to its schema; `web_fetch` and `web_search_tool` do. The model uses it to say what it needs from the result, for example "the rate limits". `before_tool` removes the argument from the call before validation, so the tool never sees it. Only a tool whose schema carries that exact property loses it; any other tool with a parameter of the same name keeps it. It reaches TinyJuice with the result, where it steers the summary, keys its cache, and ranks text for the deterministic compressors. A tool that caps its own output, such as `web_fetch`, is normally left to cap-and-spill. When the caller gives a focus, it is summarized as well, because paging the raw page cannot answer a question.++### Filesystem offload - `outputs/` and `workspace/`++Compression alone does not survive a long-horizon run. Summaries still accumulate step after step, and no amount of compressing restores the fidelity that was thrown away. So for minutes-to-hours tasks the harness moves large results **out of context and onto disk**, and hands the next step a **path**.++Two directories under the agent's existing `action_dir` at runtime (the implementation lives in `crates/openhuman-core/src/agent/harness/artifact_offload/`):++| Directory | Holds |+| ----------------------- | -------------------------------------------------------------------------- |+| `action_dir/outputs/` | Deliverables. Meant to outlive the step that made them, handed on by path. |+| `action_dir/workspace/` | Scratch. Intermediate files a worker needs but does not hand back. |++Note `action_dir/workspace/` is a scratch folder inside the agent's action root. It is **not** the core's internal `workspace_dir`, which agent writes may never reach.++Two halves enforce the convention:++* **Prompt.** A sub-agent that actually holds `file_write` gets a Long-horizon Artifact Offload contract in its system prompt: results past roughly 2 000 tokens go to a file under `outputs/`, and the reply is that relative path plus a short abstract. The gate is deliberate, a prompt may only name tools the agent can really call, or the model emits calls that fail. Skill-filtered specialists get no contract text, and a dedicated guard asserts their prompts never mention a filesystem tool. They stay covered by the harness half below, which needs no cooperation from the model. The `planner` prompt spells out what the convention means for its own work; the planner is told to reference artifact paths across DAG nodes rather than pasting payloads forward.+* **Harness.** `offload_oversized_result` runs on every sub-agent outcome, so an oversized result is offloaded even when the worker inlined it anyway. It fires **before** the definition's `max_result_chars` cap, so the full body lands on disk instead of being cut.++What the parent receives is a pointer, not a payload:++```+[artifact] kind=output path=outputs/presentation_agent/sub-1234-result.md bytes=52318+read_with: file_read {"path":"outputs/presentation_agent/sub-1234-result.md"}+note: The full result was written to the action workspace instead of being inlined. …++[abstract]+HEADLINE FINDING …+```++`SubagentRunOutcome.artifact_paths` carries the same paths structurally, parsed out of the `[artifact]` pointers in the output, so the handoff carries paths whether the harness offloaded the result or the worker wrote the file itself. Any path the parent takes delivery of is recoverable with an ordinary `file_read` long after the child's context is gone.++**The summarizer is now the fallback, not the first resort.** Offload catches the common case; the summarizer detour and the `tool_result_budget_bytes` truncation above still handle everything it does not, including every failure mode here. A refused or failed offload is deliberately soft: the caller keeps its inline payload and falls through to those backstops.++**Path hardening is fail-closed.** `resolve_artifact_path` rejects absolute paths, `..` traversal, and anything that escapes its convention root after lexical normalization. When a `SecurityPolicy` is available it also refuses anything under `workspace_dir`, both by blanket containment and via `is_workspace_internal_path`. Offload targets resolve under `action_dir`, never `workspace_dir` - including the case where someone configures `action_dir` inside the workspace root, where every offload is refused rather than quietly writing to internal state.++Writes log `[artifact] wrote worker artifact under action_dir`; each path a handoff carries logs `[artifact] handoff carried an artifact path to the parent`, on both the producing and the consuming side, so a run journal shows both ends of every pointer.++### TokenJuice - content-aware tool-output compaction (Stage 1a)++Before a fresh tool result enters history (and ahead of the byte-budget backstop), it passes through the **TokenJuice content router** in the vendored TinyJuice crate (`vendor/tinyjuice`), with OpenHuman adapters in `crates/openhuman-core/src/inference/tokenjuice/`. Inspired by Headroom, the router _detects the content kind_ (JSON, code, log, search, diff, HTML, plain text) from the bytes and/or a hint derived from the tool name and arguments, then dispatches to a specialised compressor:++* **JSON** → SmartCrusher: array-of-objects → table (each key once), preserving rows that carry errors or numeric outliers.+* **Code** → tree-sitter (Rust/TS/JS/Python) signature keeper that collapses function bodies; brace-depth heuristic fallback.+* **Log** → the 100-rule engine for _command_ output (git/cargo/npm/…), signal-based keep-failures otherwise.+* **Search** → relevance-ranked top-K matches per file with a `+N more` tally.+* **Diff** → keep changed hunks, collapse unchanged context, summarise lockfile hunks.+* **HTML** → strip markup to readable text.+* **Plain text** → the opt-in Python/ML "Kompress" compressor (ModernBERT), or pass-through.++Every lossy compression offloads the original to the **CCR (Compress-Cache-Retrieve)** store behind a `⟦tj:<hash>⟧` marker, so compaction is effectively lossless: the agent calls `juice_retrieve` (token + optional byte/line range) to fetch the full original on demand. The same engine is exposed as a universal `compress_content(content, hint, opts)` for any large payload (file reads, web fetches), and as read-only `tokenjuice.*` debug RPCs. Compaction is on by default (`context.compaction_enabled`; `OPENHUMAN_COMPACTION=0` opts out). A large result is stored and replaced by a stats line, a 500-character head and a handle that the read-only `juice_find` / `juice_extract` / `juice_summarize` tools query (`tokenjuice.repl_handle_enabled`), so the LLM summary stage is skipped for results that get a handle. Configured via the `[tokenjuice]` block / `OPENHUMAN_TOKENJUICE_*` env. Agent definitions can override tool-result compression with `tokenjuice_compression = "auto" | "full" | "light" | "off"`; `auto` resolves coding-model agents (`[model] hint = "coding"`) to `light`, which disables CCR-backed lossy compression so coding agents keep raw build/test/diff/search text unless a reduction is truly lossless. Other agents default to `full`. The ML (Kompress) path runs as a `kompress` backend of the shared [`runtime_python_server`](../../../../../../../crates/openhuman-core/src/runtime/python_server/) (torch + ModernBERT pip-installed at runtime), gated by the `ml_compression_enabled` flag and degrading gracefully to a native compressor when the Python runtime is unavailable.++### Missing capabilities++There is no self-healing archetype. The old automatic "command not found → spawn ToolMaker → retry" interceptor was removed with the in-house loop, and the `tool_maker` archetype that could be spawned explicitly was removed with the other single-belt specialists. A missing host command is reported back to the user rather than polyfilled.++## Sub-agents - the orchestrator pattern++OpenHuman is **multi-agent**. The agent the user is chatting with is the **Master Agent** (stable internal id: `orchestrator`) - a capable default agent that answers and completes ordinary work directly, including the inspect → edit → verify coding loop. It spawns specialist sub-agents when parallelism, deeper reasoning, or a specialised capability materially helps.++### Why multi-agent++A single agent that knows everything also has a system prompt the size of a small book. Splitting work across specialists means:++* Each sub-agent gets a **narrow system prompt** with only the sections it needs (identity / memory / safety preamble can be stripped).+* Each sub-agent gets a **filtered tool registry** - the image agent doesn't need filesystem tools, the task manager doesn't need the Composio catalog.+* Sub-agent histories never leak back to the parent - the parent sees one compact tool result, not the inner conversation.+* Cheaper models can do the leaf work. The orchestrator is on a strong reasoning model; a research sub-agent might be on a faster, cheaper one.++### The built-in archetypes++Each archetype lives under `agents/<name>/` with an `agent.toml` (metadata, tool scope, model hint) and a prompt. The orchestrator's chat delegates are the ones in its `[subagents]` allowlist:++| Archetype | When the orchestrator picks it |+| -------------------- | --------------------------------------------------------------------------------------------- |+| `orchestrator` | The Master Agent: top-level, direct-capable default. Never spawned by another orchestrator. |+| `task_manager_agent` | Adding, previewing, fetching, updating or removing task sources, workflow bundles, artifacts. |+| `vision_agent` | Anything that depends on the content of an image (describe, OCR, UI elements). |+| `image_agent` | Generating or editing an image. |+| `video_agent` | Generating a video or animating an image. |+| `presentation_agent` | Building a slide deck with grounding and citations (feature `documents`). |+| `skill_setup` | Finding, installing and managing skills from registries (`setup_skills`). |+| `workflow_builder` | Authoring or editing a saved workflow (`build_workflow`); returns a proposal, never saves. |+| `flow_discovery` | Suggesting workflows worth setting up (`discover_workflows`). |++Other built-ins are never chat delegates:++| Archetype | Who runs it |+| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |+| `planner`, `critic` | Only the `parallel_research_cross_check` workflow-run template (decompose and research = `planner`, cross\_check = `critic`). |+| `summarizer` | The harness, to compress oversized tool results; also the synthesize phase of that workflow-run template. |+| `trigger_triage` / `trigger_reactor` | Classifying an incoming external event, and the lightweight reaction to one. |+| `morning_briefing` | Cron: the daily digest, on a named read-only tool belt. |++Work that used to go to single-belt specialists (coding, crypto, settings, scheduling, product docs, MCP servers) is now done by the orchestrator itself through **inline skills**: `use_skill` loads a tool pack's guide and schemas (`coding`, `web3`, `system`, `scheduling`, `docs`, `mcp`), and the same tools are `Deferred` so `tool_search` finds any single one. Running an installed skill is the orchestrator's own `run_workflow`. See [`tools/toolpacks/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/tools/toolpacks/README.md).++Custom archetypes ship as TOML files under `$OPENHUMAN_WORKSPACE/agents/*.toml` (or `~/.openhuman/agents/*.toml` for user-global specialists). Custom definitions override built-ins on id collision.++### Running a reusable sub-agent++When the orchestrator calls `spawn_subagent`, the default contract is durable and asynchronous. The tool builds a deterministic compatibility selector from the parent session/thread, agent id, model override, sandbox mode, action root, and normalized task key/title. It then checks `orchestration::subagent_sessions` before spawning:++* If a compatible worker is already running, the instruction is injected through its `RunQueue` and the parent gets a quick `subagent_session_id` / `task_id` reference.+* If a compatible worker is idle or paused with reusable history, the harness starts a new transient run for the same durable `subagent_session_id` and passes the saved child history through `SubagentRunOptions.initial_history`, with the new instruction appended as a user-visible follow-up.+* If the shape is incompatible, the worker was closed, `fresh: true` was passed, or no session exists, the harness creates a new durable session and worker thread.++The child run is prepared and executed by the OpenHuman host through the neutral TinyAgents lifecycle:++1. Receives parent cancellation and workspace from its typed run context; remaining legacy provider, sandbox, and transcript inputs stay scoped until their explicit migration lands.+2. Resolves the sub-agent's model - inline `model` override first, then config-level pins (`[orchestrator].model`, `[teams.*].lead_model`, `[teams.*].agent_model`), then the archetype hint or inherited parent model.+3. Filters the parent's tool registry per the definition's `tools`, `disallowed_tools`, and `skill_filter`. In `fork` mode, the parent's full registry is inherited verbatim.+4. Builds a narrow system prompt, omitting the sections the definition asks to strip.+5. Passes the prepared child to `tinyagents-orchestration` for lifecycle ordering and exactly one pause-or-terminal persistence action.+6. Persists the child history and worker thread pointer under the durable `subagent_session_id` so later turns can resume or inspect it. Pause continuation also retains its complete TinyAgents task key.++`wait_subagent` and `steer_subagent` accept either the durable `subagent_session_id` or the transient `task_id`; durable ids are preferred across turns. `list_subagents` shows reusable children for the current parent thread, and `close_subagent` marks a worker non-reusable and cancels it if it is still running. Inline blocking is explicit via `blocking: true`; it is no longer the default.++The synthesized archetype delegations (`delegate_*`, `build_workflow`, and the other `delegate_name` tools) follow the same contract: they route through the durable async path by default, returning an `[async_subagent_ref]` (with `subagent_session_id` + `task_id`) immediately, and the finished result is inserted into the parent chat as a new system turn via `background_completions`/`background_delivery`. The delivery turn persists its own closing message, `sender: "agent"`, id `agent:<run_id>`, `extraMetadata.requestId = run_id`, **before** it emits `chat_done` as `client_id: "system"`; the frontend reuses that id, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent for these deterministic `agent:`-prefixed ids; every other id is UUID-fresh and keeps the constant-time append path) instead of persisting the delivered result a second time (#5933). **Interactive turns follow the same contract since #6034**: `web_chat::presentation::deliver_response` stores the reply under `agent:<request_id>` before publishing `chat_done`, so an answer the core produced exists on disk whether or not a client is there to receive the announcement, a dropped socket or a reloaded webview costs a repaint, not the reply. The exception is a segmented delivery, where the client owns one row per segment and the core stores none; the frontend keeps generated ids there for exactly that reason. They fall back to inline blocking automatically when there is no parent agent turn or no chat thread to deliver into (cron/CLI), or when `blocking: true` is passed. Cross-turn continuity comes from three pieces: the per-turn `[active_subagents]` roster merges the live in-memory registry with the durable `subagent_sessions` store (so a cold-booted orchestrator still sees earlier workers); `continue_subagent` falls back from pause checkpoints to the durable store, resuming an idle worker with its persisted history; and a `workflow_proposal` payload found in a finished child's history is persisted as a parent-thread message (`extraMetadata.scope = "workflow_proposal"`) that the frontend rehydrates into the proposal card on thread load.++### Spawn hierarchy and tiers++Not every agent is allowed to spawn every other agent. The harness models a three-tier hierarchy that mirrors the cost / latency / depth-of-thought split between models:++```+Primary (direct-capable, Master Agent on `coding` hint)+ │+ ├─► Worker ◄─── fast path: one delegation, leaf does the work+ │+ └─► Reasoning (slow, deep-thinking, e.g. planner on `reasoning` hint)+ │+ └─► Worker ◄─── deep path: reasoning decomposes, workers execute+```++Each `AgentDefinition` carries an `agent_tier` field (`chat` / `reasoning` / `worker`, default `worker`). The contract:++| Tier | May spawn | Must NOT spawn | Typical members |+| ----------- | --------------------- | ------------------------------- | --------------------------------------------- |+| `chat` | `reasoning`, `worker` | another `chat` | `orchestrator` |+| `reasoning` | `worker` | another `reasoning`, any `chat` | `planner` (today the canonical one) |+| `worker` | nothing[^1] | anything | critic, image\_agent, task\_manager\_agent, … |++**Why the rules.**++* _Chat → chat is meaningless._ The chat tier exists for snappy UX. A chat agent spawning another chat agent just doubles TTFT and burns tokens without buying any new capability.+* _Reasoning → reasoning blows up depth._ The reasoning tier is expensive. Chains of reasoning agents tend to re-decompose the same problem and create runaway hierarchies.+* _Worker → anything mixes execution and orchestration._ Workers are leaves so the parent always sees one compact result, not a transcript of nested delegations.++**Enforcement.** Two layers:++1. **Loader-time (static).** [`agents::loader::validate_tier_hierarchy`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/registry/agents/loader.rs) runs over the merged registry (built-ins + workspace TOMLs) and refuses to boot a registry that lists a same-tier or worker-with-subagents entry. Built-in archetypes are checked at compile-test time; user-shipped TOMLs are checked at workspace load.+2. **Runtime depth gate (dynamic).** Independent of tier, the sub-agent runner caps total spawn chain depth at `MAX_SPAWN_DEPTH = 3` via a task-local counter incremented across `run_subagent`, surfaced as a `SpawnDepthExceeded` agent error. This makes a user-shipped TOML that drops the tier annotation still unable to recurse past three hops.++> **Status:** the loader-time tier check, `agent_tier` field, and runtime depth-counter task-local are live. Depth is bounded by both the static loader contract and the runtime `MAX_SPAWN_DEPTH = 3` guard.++### Toolkit-specific specialists++For Composio toolkits with hundreds of actions (GitHub alone has 500+), loading every action into the sub-agent's tool set balloons prompt size. The harness ranks the toolkit's actions against the parent-refined task prompt with a cheap CPU-only filter (verb detection, token overlap, verb-alignment boost) and only loads the top-ranked subset into the sub-agent. No model call, pure heuristic - fast and explainable.++## Language workflows (Rhai): HISTORICAL (removed)++> **Status:** TinyAgents dropped its `repl`/`rlm` Rhai-backed REPL feature, and the `rhai_workflows` tool and `crates/openhuman-core/src/flows/rhai/` module described below no longer exist (`grep -rli rhai crates/` finds only an unrelated `tinyflows` JSON-query dependency). The section is retained as design history.++The fixed delegation primitives (`spawn_subagent`, `spawn_parallel_agents`, `run_workflow`) can't express _ad-hoc control flow_, "spawn N readers, dedupe their findings, verify each survivor with 3 refuters, loop until dry". The **`rhai_workflows` tool** closed that gap: it exposed TinyAgents' Rhai-backed `.ragsh` REPL (the `repl` cargo feature) so the orchestrator could author and run its own workflow scripts.++**One tool call = one `eval_cell`.** The orchestrator's normal tool-call loop _was_ the CodeAct driver loop: the model wrote a Rhai cell, the cell ran against a persistent per-session namespace (top-level `let` bindings survived into the next cell via an optional `session_id`), and the structured result flowed back as the tool result. Scripts reached the host only through capability functions, `tool_call`, `agent_query`, `model_query`, their `*_batched` fan-out variants, `emit`, and `answer`.++The domain lived in `crates/openhuman-core/src/flows/rhai/`:++* **`policy.rs`** mapped the autonomy tier + `tool_timeout` clamps onto a `tinyagents::ReplPolicy` (always bounded, never unbounded; `readonly` refused; `full` could raise call-count limits to a hard 2× ceiling).+* **`bridge.rs`** built the `CapabilityRegistry`: the parent's visible tools (each re-wrapped so the **approval gate ran in the bridge**, it was _not_ on the repl path, which bypassed the harness `wrap_tool` middleware), the turn's provider model, and a sub-agent capability per `allowed_subagent_ids`. Recursion/duplication hazards (`rhai`, legacy `rlm`, `spawn_*`, workflow tools, `CliRpcOnly`-scoped tools) were excluded. Because `eval_cell` ran on `spawn_blocking` + `block_on`, the `agent_query` adapter re-installed the `PARENT_CONTEXT` task-local that `run_subagent` resolves.+* **`sessions.rs`** was a bounded (LRU + idle-TTL) manager of persistent sessions, one cell at a time (a concurrent call on a busy session returned a typed "busy" error).+* **`ops.rs`** ran the cell on `spawn_blocking` under a layered time bound (rhai `on_progress` deadline → `bridge_block_on` timer race → outer `tokio::timeout` backstop → harness `ToolTimeout`), wired the run-cancellation token to a fresh per-cell `ReplCancelFlag`, and mapped every failure mode to a model-consumable result.++The tool was registered for the orchestrator on `supervised`/`full` tiers only, behind an `OPENHUMAN_RHAI_WORKFLOWS=0` kill switch.++## Triage - handling external triggers++When a webhook fires, a cron ticks, or a Composio event arrives, the system can't just hand it straight to the orchestrator. Most triggers are noise; some warrant a notification; only a few deserve a full agent turn. The **trigger-triage pipeline** is the gate.++```+TriggerEnvelope ──► run_triage ──► TriageDecision ──► apply_decision+ │ │+ │ ├─► drop (noise)+ │ ├─► notify only+ │ ├─► spawn trigger_reactor+ │ └─► spawn orchestrator+ │+ └── small local LLM (with cloud-LLM retry fallback)+```++The evaluator is intentionally cheap - a small local model where available, falling back to a remote model on retry. The decision is cached so identical triggers don't re-classify. Only triggers that escalate to "spawn orchestrator" go through the full `Agent::turn` machinery.++## Hooks - observability and policy levers++Two hook surfaces wrap the loop, on opposite ends:++### Stop hooks (mid-turn)++Stop hooks fire **between** iterations of the tool-call loop. They're the policy lever for budget caps, rate limits, and custom kill switches. Built-in hooks:++* **Budget stop hook** - caps cumulative turn cost in USD using the per-iteration cost accumulator.+* **Max-iterations stop hook** - caps iteration count from outside the agent's persistent config.+* **Action budget policy** - `SecurityPolicy` enforces `config.autonomy.max_actions_per_hour` for side-effecting tool operations. Users can tune it in Settings -> Advanced -> Agent autonomy, or operators can override it with `OPENHUMAN_MAX_ACTIONS_PER_HOUR`.++A hook returning `Stop` aborts the loop with a clear reason the caller can surface to the user. Stop hooks are distinct from interrupts (next section): they're policy-driven, not user-driven.++### Post-turn hooks++Post-turn hooks fire **after** the turn completes, in the background. They get a `TurnContext` snapshot - user message, assistant response, every tool call with arguments and outcome, total wall-clock, iteration count, session ID. Built-in consumers:++* **Cost log** - final per-turn cost line.+* **Conversation logging** - the `memory` lifecycle logs the reply after the turn, with one-line tool results (never arguments); there is no batching or idle flush. See [Memory architecture](memory.md).++Long-term facts are written explicitly: the agent calls the `memory` tool's `learn` action. There is no automatic archivist.++Hooks run via `tokio::spawn`, so the user gets their answer before any of them finish.++## Interrupts - graceful cancellation++Cancellation is the tinyagents **steering channel**. The old in-house `InterruptFence` (`harness/interrupt.rs`) is gone; when the user hits Ctrl+C or sends `/stop`, the runner forwards the request into the harness's steering/cancellation seam, which stops the loop at the same safe points the fence used to guard - before each tool execution, before each sub-agent spawn, before each provider call:++* Every running sub-agent shares the cancellation scope and bails at its next checkpoint.+* In-flight provider streams are dropped.+* Buffered conversation turns are still stored (idle flush, or the exit flush on quit).++Interrupts are user-driven; stop hooks are policy-driven. Both enter the same harness pause/stop plumbing, but from different sides.++## Cost accounting++Every provider response carries a `UsageInfo` block - input tokens, output tokens, cached input tokens, and an authoritative `charged_amount_usd` populated by the OpenHuman backend. `TurnCost` sums those across every provider call inside one turn so the harness can:++* Emit per-iteration cost telemetry over the progress channel.+* Feed the budget stop hook so a runaway turn cuts itself off mid-loop.+* Log accurate end-of-turn cost lines.++When the backend doesn't surface a charged amount (older builds, providers that don't bill through it), a small per-tier rate table provides a token-rate floor estimate. Direct cost from the backend always wins when available.++## Web channel events and RPCs (assistant-ui elements pass)++The assistant-ui-elements integration added a batch of additive `WebChannelEvent`s and RPCs so the frontend can render tool args/timing, plan/goal/queue state, and turn lifecycle without polling. `EVENTS_VERSION` (`core/bus.rs`) is `1.4.0`; every new field is optional/defaulted so an older subscriber keeps parsing what a newer publisher emits.++**New/extended socket events** (bridged from `DomainEvent` onto `WebChannelEvent` by `web_chat::event_bus` and `openhuman_rpc::server::socketio`):++* `ts` (epoch ms) is now stamped on every event by `publish_web_channel_event` when the producer left it unset, so the frontend can order/measure latency without guessing at receive time.+* `chat_done.timing` - `{ first_token_ms, first_tool_ms, total_ms, tokens_per_second }`, threaded from the progress bridge's per-turn `TurnTiming` through `ProgressBridgeHandle::timing_snapshot()`. `tokens_per_second` is derived from `output_tokens / (total_ms / 1000)` when both are known and `total_ms > 0`.+* `chat_cancelled` - `{ thread_id, client_id, request_id, cancel_reason: "user_stop" | "superseded", superseded_by }`. Emitted alongside (not instead of) the existing `chat_error{error_type:"cancelled"}` for one release, on both the unscoped/scoped stop path and the superseded-by-a-newer-request path, and on the parallel-turn cooperative-cancel path (which previously published no terminal event at all).+* `chat_error{error_type:"guardrail"}` - carries a `guardrail: { verdict, score, reasons: [{code,message}] }` payload when `start_chat` rejects a message via `StartChatError::Guardrail` (the prompt-injection/security guardrail). Every other rejection stays `error_type:"inference"`. The RPC surface (`channel.web_chat`'s `Result<_, String>`) encodes the same structured verdict as a `GUARDRAIL:<json>` sentinel string (`web_chat::ops::start_chat::{GUARDRAIL_ERROR_PREFIX, is_guardrail_error_message}`, mirroring the existing `BACKEND_UNAVAILABLE:` pattern).+* `turn_cost` - live per-turn cost readout from `AgentProgress::TurnCostUpdated`, throttled to at most one emission per 750ms per turn (the first update always emits immediately): `{ thread_id, client_id, request_id, round, usage: { input_tokens, output_tokens, cached_input_tokens, cost_usd, context_window, subagents } }`. `subagents` is always empty on this live event (it is the parent's cumulative rollup only); per-sub-agent attribution still only shows up on the terminal `chat_done.usage`.+* `approval_decided` / `plan_review_decided` - bridged from `DomainEvent::ApprovalDecided` / `PlanReviewDecided`, which gained `thread_id`, `client_id`, `tool_call_id`, and `resolution` (`"expired"` on TTL/sweep, `"cancelled"` on a dropped decision channel, `None` for an ordinary user decision - carried on the wire as the existing `cancel_reason` field). Only surfaced when the original park had both `thread_id` and `client_id` (chat-routed).+* `run_mode_changed` - `{ thread_id, client_id: "", message: "plan" | "build" }`, bridged from `DomainEvent::ThreadRunModeChanged`, published by `agent::tinyagents::run_mode::set_mode`.+* `thread_todos_changed`, `queue_item_queued` / `queue_item_delivered` / `queue_item_removed` - `queue_item` carries `{ id, lane, text_preview }`.+* Sub-agent correlation: `subagent_spawned`/`subagent_completed`/`subagent_failed`/`subagent_awaiting_user` carry `subagent.parent_call_id` (the spawning tool call's id - every worker of one `spawn_parallel_agents` call shares it); `subagent_completed` also carries `subagent.output` (capped final text). `tool_call.args`/`tool_result.args`+`elapsed_ms` now carry real arguments and timing instead of `null` (from tinyagents' `AgentEvent::ToolStarted.input`).+* Artifact events (`ArtifactPending`/`ArtifactReady`/`ArtifactFailed`) carry `tool_call_id` and `turn_request_id`, the latter filled from the originating turn's `ApprovalChatContext::request_id` so the frontend can bind an artifact card to the exact turn that produced it (`None` for CLI/cron/sub-agent producers with no chat context).++**New RPCs:**++* `agent.set_run_mode { thread_id, mode }` / `agent.get_run_mode { thread_id }` - read/flip a thread's Plan/Build `RunModeHandle`. `channel.web_chat` also accepts an optional `run_mode: "plan" | "build"` param (mirroring the socket `chat:start` payload) so a turn can start with the thread already in the requested mode instead of racing a separate RPC call; unrecognized values are logged and ignored.+* `threads.goal_get` / `threads.todos_get` - read a thread's current goal/todo state directly (previously only observable via the bridged events).+* `threads.edit_message { thread_id, message_id, content, client_id? }` / `threads.regenerate { thread_id, message_id?, client_id? }` - both return `{ request_id }`. They cancel the thread's in-flight turn, fork the session transcript at a cut point via `TranscriptLocator::truncate_into_next_generation` (the sealed generation the fork was cut from is never touched - same "compaction never erases" guarantee), truncate the conversation-store message log and the turn-state snapshots for every dropped turn, then restart the turn with the edited content (`edit_message`) or the original prompt (`regenerate`). See `threads::ops::edit`'s module doc for the full UI-message-id -> transcript-cut-point mapping.+* `channel.web_queue_remove { client_id, thread_id, item_id }` - remove one specific queued item from a thread's run queue.+* `agent.context_breakdown { agent_id?, thread_id? }` - a UI-friendly view over the agent's rendered prompt size (system/tools/history split) for the composer's context-usage indicator.+* `commands.list` - merges built-in commands with `skills.list` and `flows.list` into one slash-command catalog.++`plan_exit` (the tool that flips a thread from Plan back to Build) only flips the mode when there is no plan review still parked on that thread (`agent::plan_review::gate::PlanReviewGate::parked_review_for_thread`) - a review resolves before `request_plan_review` returns control to the agent, so this only matters for a mis-timed/concurrent `plan_exit` call racing a still-pending review, which must not unlock every tool before the user has actually approved anything.++## Explicit run context and host capabilities++`OpenHumanRunContext` is now the live carrier at the shared chat, channel, and sub-agent turn seam. Roots snapshot their currently scoped origin, progress, stop hooks, dispatch state, thread, route slot, and workspace grant, then own or explicitly receive one cancellation token before passing the context to the runner; a recursive sub-agent forks it with `child()`, preserving shared cancellation/policy handles while isolating route observation and usage accounting. The shared runner creates `RunContext<OpenHumanRunContext>` through `into_tinyagents`, and the OpenHuman assembly and middleware registry consume that typed context directly. Route, and thread scopes still surround the drive only for legacy tool/model APIs outside the typed harness boundary. Recursive fan-out receives cancellation and workspace from its typed parent `RunContext` through `ToolDispatch`; it never reads ambient cancellation state.++`OpenHumanHostBundleFactory` is the B1 host composition point. It constructs the context, definition, security, model, memory, budget, progress, tool-outcome and experience adapters from the same session/runtime inputs. OpenHuman retains all policy decisions; TinyAgents receives only the resulting canonical run context today. Wiring the complete host-capability bundle into every invocation remains a later cutover step.++## Self-healing recap++A few small adaptive systems sit on top of the main loop:++* **Tool-output summary circuit-breaker** - three consecutive summary failures in a thread make TinyJuice stop asking for summaries in that thread, so results fall back to compaction and truncation.+* **Triage local-vs-remote retry** - local LLM first; remote fallback on parse failure.+* **Unknown-tool and malformed-argument recovery** - middleware rewrites an invalid model tool call into a recoverable result instead of aborting the run.++None of these change the loop's shape - they just make the common failure modes recoverable without the user having to intervene.++## Where to look in the code++The harness shell lives under `crates/openhuman-core/src/agent/`, with the tinyagents adapter seam in `crates/openhuman-core/src/agent/tinyagents/` and archetype definitions in `crates/openhuman-core/src/agent/registry/`. The README in `crates/openhuman-core/src/agent/` enumerates the public surface; the most load-bearing files (paths relative to `crates/openhuman-core/src/agent/` unless prefixed) are:++| File / dir | What lives there |+| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `session_host/runtime_session.rs` | `Agent::turn` - the lifecycle described above; routes into the tinyagents runner via `tinyagents/turn_runner.rs`. |+| `tinyagents/mod.rs` | `run_turn_via_tinyagents_shared` - the shared tinyagents harness assembly (the live loop). |+| `tinyagents/middleware.rs` | The named OpenHuman middleware stack (approval/security, tool policy, recovery, budgets, circuit breaker). |+| `harness/graph.rs` | The channel/CLI bus turn route into the tinyagents runner. |+| `subagent_host/` | Direct OpenHuman planner/executor/persistence adapters for `tinyagents-orchestration::subagent`; product prompt/tool/model/security/artifact/progress behavior remains here. |+| `orchestration/subagent_sessions/` | Durable reusable sub-agent identity, compatibility matching, persisted status/history. |+| `harness/definition.rs` | `AgentDefinition` - what an archetype declares. |+| `subagent_host/ops/runner.rs` | Integration-tool ranking and the host execution leaf; generic lifecycle stays in `tinyagents-orchestration`. |+| `tinyagents/payload_summarizer.rs` | The model call behind TinyJuice's oversized-tool-result summary. |+| `session_host/tool_progress.rs` | Surviving OpenHuman seam: `TurnProgress`. |+| `message_convert.rs` | Concrete durable/provider conversion around canonical tool-call dialect APIs. |+| `triage/` | External-trigger classification + escalation. |+| `registry/agents/` | Built-in archetypes - one subdirectory per agent. |+| `hooks.rs` / `stop_hooks.rs` | Post-turn and mid-turn hook surfaces. |+| `cost.rs` | Per-turn USD/token accounting. |+| `progress.rs` | Real-time progress events to the UI. |++## Agent state graphs (`agent_graph`): HISTORICAL (removed)++> **⚠️ This section describes a design that was never shipped and has been removed.** The bespoke `agent_graph/` engine, `GraphBlueprint`, and the `SqliteCheckpointer` described below **do not exist** at those paths any more. The live system runs on the published **tinyagents** crate; see the status banner at the top of this page and "Agent engine + orchestration on tinyagents (live)" below. Graphs are built with `tinyagents::graph::GraphBuilder` (`orchestration/*/graph.rs`, `orchestration/delegation.rs`), durable checkpoints use TinyAgents' own `SqliteCheckpointer` (the earlier `SqlRunLedgerCheckpointer` adapter is retired), and per-agent graph selection is `AgentGraph` (`agent/harness/agent_graph.rs`) with each agent's `registry/agents/<id>/graph.rs`. The text below is retained only as pre-migration design history.++Alongside the linear tool-call loop, the harness ships a **LangGraph-style state-machine engine** under `crates/openhuman-core/src/agent_graph/` (issue #4249, referenced here only as design history, the path no longer exists). Where the loop is an implicit "prompt → tool → result → next prompt" cycle, a graph models agent execution as an explicit directed graph of **nodes** (states) and **edges** (transitions), with typed working state that survives across transitions, parallel branches, and checkpoints.++```rust+StateGraph::new(name)+ .add_node(id, node) // a unit of work: async fn(State) -> (State, Command)+ .add_edge(from, to) // static transition+ .add_conditional_edges(...) // route by inspecting state+ .add_fork(from, [a, b]) // fan out in parallel; merge via State::merge+ .set_entry_point(id) / .set_finish_point(id)+ .compile()? -> CompiledGraph // validated; .invoke(state) / .resume_with(...)+```++| Subfolder | Role |+| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `graph/` | The engine: `GraphState` (merge reducer), `Node` trait, builder + `compile()` validation, Pregel super-step `executor` with cycle / cancel / step-cap guards, `invoke`/`resume`. |+| `checkpoint/` | `Checkpointer` trait (type-erased JSON state) → `InMemoryCheckpointer` (tests) + `SqliteCheckpointer` at `{workspace}/.openhuman/agent_graph/checkpoints.db`. Durable pause/resume. |+| `hitl/` | Human-in-the-loop: `approval`/`clarification` interrupt builders + `ApplyResume` (folds the human's answer into state on resume). A node returns `Command::Interrupt` to pause. |+| `observability/` | `EventBusSink` (a `ProgressSink`) emits `tracing` spans + publishes the `GraphRun*`/`GraphNode*` `DomainEvent` family (new `agent_graph` event domain). |+| `summarization/` | Node-boundary wrapper over `context::summarize_chat_history`. |+| `memory/` | Pre-node wrapper for memory context. |+| `definitions/` | Built-in graphs over a shared `ProductState`: `canonical_turn` (the agent turn as a `dispatch → parse → stop_check → tools → compact → loop / finalize` graph) and `plan_execute_review` (composes the `planner` with a worker archetype around a HITL review gate), plus a deterministic `demo_review` twin for tests. A registry (`list_definitions`/`build_definition`) + `runner` (`run_graph`/`resume_graph`) persist runs to the checkpointer and emit bus events. |+| `blueprint/` | The per-agent chain type. Every built-in agent declares its LangGraph-compatible chain in a `graph.rs` next to `prompt.rs` (`pub fn graph() -> GraphBlueprint`), wired into `BuiltinAgent.graph_fn`. `GraphBlueprint` is serializable (typed `NodeKind`/`EdgeSpec`), structurally validated, and `compile()`s to a real `CompiledGraph`. Reusable shapes: `canonical_turn` (most agents), `single_shot`, `orchestrator`, `plan_execute_review`. Inspect via `openhuman.agent_graph_{agent_list,agent_graph}`. |++### Per-agent graphs (`graph.rs`)++Each agent folder under `crates/openhuman-core/src/agent/registry/agents/<name>/` (and the four agents that live in their own domains) now contains, alongside `agent.toml` + `prompt.rs`:++* **`graph.rs`**: `pub fn graph() -> GraphBlueprint`. `prompt.rs` defines what the agent _says_; `graph.rs` defines how it _runs_, meaning its node/edge chain. A loader test asserts **every** built-in agent's chain validates and compiles, so a malformed chain fails CI.++Most agents reuse `blueprint::canonical_turn(id)` (the standard tool-calling loop); one-pass agents use `single_shot`, the orchestrator uses the delegation chain, and the planner uses `plan_execute_review`.++**RPC surface** (`schemas.rs` + `ops.rs`, registered in `crates/openhuman-core/src/core/all.rs`): `openhuman.agent_graph_definition_list`, `_run`, `_run_list`, `_run_get`, `_checkpoint_list`, `_resume`.++> **Status (issue #4249, superseded by the published `tinyagents` crate):** the in-house `agent_graph` engine described in this section **no longer exists**. openhuman's agent engine + orchestration now run on the published [`tinyagents`](https://crates.io/crates/tinyagents) **2.1** crate (the same LangGraph-style harness + durable graph runtime), via the adapter seam in `crates/openhuman-core/src/agent/tinyagents/`. The sections above are retained as design history; the subsection below describes the live architecture.++## Agent engine + orchestration on tinyagents (live)++Every agent turn uses TinyAgents. Chat and channel/CLI callers invoke the session/turn host, while a sub-agent call enters `agent/subagent_host` and its direct `tinyagents-orchestration::subagent` lifecycle. There is no `harness/subagent_runner` compatibility path. The surrounding OpenHuman seam:++| File (`crates/openhuman-core/src/agent/tinyagents/`) | Role |+| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `mod.rs` | The runner (`run_turn_via_tinyagents_shared`): installs the native `ChatModel`, host tool adapters, and middleware on an `AgentHarness`; runs one turn; caps output through `MaxTokensModel` (`agent/tinyagents/model.rs`); mirrors progress; forwards steering; and pauses gracefully at the model-call cap. |+| `mod.rs` / `model.rs` / `tools.rs` / `convert.rs` | `RunPolicy` / `ChatModel` / `Tool` / message adapters (incl. unknown-tool policy and out-of-band reasoning forwarding). |+| `observability.rs` | Harness `AgentEvent` → `AgentProgress` + cost; `GraphTracingSink` for graph events. |+| `orchestration.rs` | Re-exported `graph::orchestration` task-store types; map-reduce fanout now uses the TinyAgents SDK surface directly. |+| `delegation.rs` | The durable `plan → execute ⇄ review → finalize` delegation graph (production worker wired in `orchestration::delegation`), checkpointed via TinyAgents 2.1's own `SqliteCheckpointer`. The earlier `SqlRunLedgerCheckpointer` adapter and its `checkpoint.rs` are retired. |++**Orchestration on graphs** (`crates/openhuman-core/src/agent/orchestration/`):++* **Workflow phase DAG** (`workflow_runs/engine.rs`) runs on a `dispatch ⇄ run_phase → done` conditional-routing graph; each phase fans its agents out via `graph::parallel::map_reduce`. The durable `workflow_runs` row stays the source of truth (controllers + resume read it).+* **Team member runtime** (`agent_teams/runtime.rs`, `run_member_graph`) is a conditional-routing graph (`execute → complete|fail → done`).+* **Multi-stage delegation** (`orchestration::delegation` + the `delegate` tool) runs `delegation.rs`, checkpointed to the session DB.+* **Detached sub-agents** (`running_subagents.rs`) use TinyAgents `DetachedTaskRegistry` for ownership-aware snapshots, wait/timeout, steering lookup, cooperative cancellation, hard abort, and terminal cleanup. OpenHuman retains durable task-store projection, product/session metadata, RPC and delivery semantics, and the `RunQueue` compatibility fallback.++**Deliberately kept off the crate's primitives** (documented engineering decisions, not gaps):++* **Sub-agent host policy** (`subagent_host/`) stays OpenHuman-owned: definition resolution, archetype tool filtering, provider resolution, narrow prompt building, memory context, worker-thread mirror, handoff configuration and product checkpoint/session projection. It implements the TinyAgents planner/executor/persistence traits directly. The neutral driver, not a host-local runner, owns lifecycle sequencing and task-key coalescing.+* **Durable run ledgers** (`workflow_runs`, `agent_teams`, `command_center`, `subagent_sessions`) stay on openhuman SQLite/JSON until their controller projections and restart semantics are mapped onto TinyAgents task/status/journal records. The `agent_teams` race-safe SQL compare-and-swap task claim remains OpenHuman-owned.++> **Note:** TinyAgents 2.1 ships harness store/cache/session primitives (`harness::store` with JSONL append stores, `harness::cache`, `harness::subagent`, lineage-aware status), graph task stores, the detached runtime registry, and conformance contracts. The session shell and product-specific sub-agent build/delivery pipeline remain OpenHuman-owned.++## Reliability: breakers, handback, and classified failures++Three cooperating mechanisms keep runs from wandering or dying silently:++**No-progress circuit breaker** (`RepeatedToolFailureMiddleware`, `crates/openhuman-core/src/agent/tinyagents/middleware.rs`) is a thin driver over the crate's `NoProgressTracker`. It fingerprints each tool call's arguments and feeds outcomes into an escalation ladder: `Continue` → `Nudge` (a structured "no progress since step X" corrective injected via `SteeringCommand::InjectMessage`, which is safe inside interactive turns) → `Halt` (record a root-cause summary into the `HaltSummarySlot`, pause via the steering handle). Identical arguments retried count toward the trip (threshold 3 consecutive identical failures); _recoverable_ failures (timeouts, connection resets, rate limits, 5xx) get an extended headroom ladder instead of the fixed crate thresholds.++**Sub-agent handback** (`subagent_host/`): a sub-agent run resolves to one of three statuses:++* `Completed`: clean final response.+* `AwaitingUser { question, options }`: the child called `ask_user_clarification`; the host projects its full checkpoint (history, question, options and overrides) under the complete TinyAgents task key `(root_run_id, parent_run_id, thread_id, task_id)`. Resume recovers that original key rather than deriving a new one from the fresh parent turn.+* `Incomplete { reason }`: the child was halted by the breaker or hit its model-call cap. The delegating parent **relays the blocker** instead of treating a halted child as a finished answer or re-spinning the identical delegation.++A breaker halt at the top level is likewise never a silent finish, and the breaker's root-cause summary is not shown to the user as is either: it is worded for a model ("Report this back instead of retrying"). `hit_cap` / `breaker_halt` are surfaced on the turn result, and the chat turn closes the halted run the same way it closes a tool turn that ended without final text (`session_host/driver/grounded_close.rs`, #4093 / #6278 / #6279):++1. A tools-disabled wrap-up call whose instruction restates the turn's tool records, each failure's own message included, with the breaker summary passed as a stop note to explain rather than repeat.+2. A separate check call that sees only the request, the records and the candidate reply. It rejects a reply that only narrates intent, contradicts a record, or leaves out the failure that explains an unfinished request.+3. A deterministic fallback for an empty, tool-calling, rejected or unverified reply (a check that failed or gave no verdict). It quotes each tool result and the stop note.++Accepted text is streamed only after the check, so a rejected reply never renders.++**Classified tool failures** (`crates/openhuman-core/src/tools/status/`): every failed tool call is classified into a transport-agnostic `ClassifiedFailure { class, category, cause_plain, next_action, recoverable }`. Classes cover `MissingPermission`, `MissingApp`, `ServiceUnavailable`, `BadCredentials`, `BlockedByPolicy`, `ModelConnection`, `Timeout`, `Denied`, `ApprovalExpired`; categories map 1:1 to UI states: _recoverable_ (safe auto-retry), _blocked by policy_ (change settings), _needs user confirmation_ (sign in / install / grant), _user declined_ (never auto-retried). The classification rides `AgentProgress::ToolCallCompleted.failure` (including for sub-agent calls) into the chat timeline.++## Journals, replay, and migration shadows++Every run appends to a durable **event journal** (`tinyagents/journal.rs`): a `StoreEventJournal` over a JSONL append store at `{workspace}/tinyagents_store/journal`, composed as `FanOutSink` (live bridge + journal) → `RedactingSink` (credential masking before persistence), with restart-stable event ids (`{run_id}-evt-{offset}`). Even an unobserved background turn is reconstructable after the fact. Three read-only RPCs expose it: `agent_run_events` (paged, late-attach replay by `run_id`/`offset`/`limit`), `agent_run_status` (latest harness status), and `agent_runs_active` (active runs, filterable by thread or root run).++The remaining store cutover runs on **shadow scaffolding** (product behavior unchanged; divergences logged):++* **Session dual-write / shadow read** (`session_host/runtime_session.rs`): session messages dual-write into the TinyAgents store (default-ON flag `config.session_dual_write`); loads shadow-read for parity while the legacy file store stays authoritative.++Goals and todos are crate-backed outright, with no shadow: thread goals live in the crate `graph.goals` KV store (`agent/goals/store.rs`), and the session todo list lives in the in-process crate `graph.todos` store (`agent/todos/ops.rs`); see [Goals & Todos](../../features/goals-and-todos.md).++## Workload routes and the burst tier++`tinyagents/routes.rs` is the declarative TinyAgents `ModelRouter` for the OpenHuman workload roles `chat`, `reasoning`, `agentic`, `coding`, `burst`, `summarization`, and `vision`, keyed by their `hint:*` aliases. It owns fallback chains and capability gates; `inference::provider::factory` resolves each selected role to its configured native `ChatModel`, on the managed backend, the pinned default model (`openrouter/deepseek/deepseek-v4-flash` unless changed under Settings → Routing → Default model); there are no per-role tier endpoints any more. The **`burst`** role serves low-context, high-fanout workers.++## See also++* [Architecture overview](./) - where the harness sits in the bigger picture.+* [Memory](../../features/memory.md) and [Memory architecture](memory.md) - the `memory` tool, the per-turn memory lifecycle and conversation logging.+* [Automatic Model Routing](../../features/model-routing/) - how `model: "hint:reasoning"` resolves to a concrete provider+model.+* [Native Tools - Agent Coordination](../../features/native-tools/agent-coordination.md) - the user-facing surface for `spawn_subagent`, `delegate_*`, `todo`.++[^1]: Skill-wildcard entries (`{ skills = "*" }`) are exempt because they name no agent: they expand to the connected Composio actions as `Deferred` tools the agent reaches through `tool_search`, not to a spawn.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/architecture.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/architecture.mdnew file mode 100644index 0000000000..44f52c4a12--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/architecture.md@@ -0,0 +1,333 @@+---+description: >-+ Deep architecture reference for the OpenHuman codebase - repo layout, runtime+ scope, dual-socket sync, RPC flow.+icon: code-branch+---++# Deep Architecture Reference++**A personal AI assistant built on Rust, with a persistent memory (stored in CortexDB, hosted by TinyHumans or your own) and an agent harness that can act across your connected services.**++OpenHuman is a cross-platform communication and automation platform: a Rust core that runs agent turns, keeps a pluggable memory engine, and executes tools against memory, channels, integrations, and (for users who opt in) a wallet, all wrapped in a single React + Rust (Tauri) codebase that can target multiple platforms. **What we document and ship for users today is desktop only: Windows, macOS, and Linux.** Web is **not** a supported target. Android and iOS exist as experimental clients with their own build and publish workflows (`android-compile.yml`, `ios-appstore.yml`) and are not part of the shipped desktop host; do not treat them as product-ready. The stack includes a managed Node.js runtime for tool-capable skills, persistent Rust-native WebSocket infrastructure to the backend, and a native Rust tool-dispatch path plus a standards-based Model Context Protocol (MCP) server for external clients.++***++## Repository layout (monorepo)++| Path | Contents |+| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **`app/`** | pnpm workspace **`openhuman-app`**: Vite/React UI (`app/src/`), Vitest and WDIO tests. The Tauri shell itself is the Rust crate `crates/openhuman-app/` (below). |+| **`crates/openhuman-app/`** | Thin Tauri v2 desktop host (Cargo package `openhuman-app`). Built from its own manifest and lockfile, excluded from the root workspace; hosts the core as an in-process tokio task (`src/core_process.rs`). |+| **`crates/openhuman-core/`** | Cargo package **`openhuman`**: library **`openhuman_core`**, with no `tinyhumans-sdk` dependency — the hosted backend is reached through the `backend::transport::BackendTransport` port, except hosted memory, which `vendor/tinymemory`'s own HTTP client calls (see `memory/engine.rs`). Flat domain modules directly under `src/` (`agent`, `backend`, `channels`, `config`, `cron`, `desktop`, `flows`, `hooks`, `hosting`, `inference`, `integrations`, `mcp`, `media`, `memory`, `modules`, `platform`, `runtime`, `sandbox`, `search`, `security`, `skills`, `threads`, `tools`, `util`, `voice`, `web3`, `web_chat`, …). `src/core/` holds the CLI (`cli.rs`), dispatch, controller registry (`all.rs`), event bus (`bus.rs`), `runtime/` (`CoreBuilder`/`CoreRuntime`) and `subsystem/`. There is no `src/rpc/` or `src/embed/` inside this crate any more. |+| **`crates/openhuman-rpc/`** | Shared JSON-RPC contracts: `RpcOutcome`, `unwrap_rpc`, `apply_log_envelope`, `StructuredRpcError`. The `http-client` feature (default on; off for root-workspace consumers) adds `post_json_rpc`, `bearer_header`, `redact_url_for_log`, `HttpRpcResponse`. Used by the Tauri shell (`core_rpc.rs` → `relay_http_rpc`) and the TUI (envelope decoding). The core does **not** depend on this crate and does not re-export it: the controller contract (`Outcome`, `ControllerSchema`, `StructuredRpcError`, params rules, in-process dispatch) lives in `crates/openhuman-core/src/core/`, and this crate sits above it. Behind `server` it also owns the `http_host` static-directory file server and registers its controllers as a core extension. |+| **`crates/openhuman-embed/`** | Typed library facade (`openhuman_embed::{Harness, Core, CoreBuilder, DomainSet, ServiceSet, HostKind}`) for embedding the core in another product; forwards the core's feature gates. Installs no backend transport itself. |+| **`crates/openhuman-tinyhumans/`** | The TinyHumans layer above embed: `SdkBackendTransport` (the only crate that depends on the vendored `tinyhumans-sdk`), `install()` for hosts that boot the core themselves, a `RuntimeBuilder` that boots an embed runtime connected, the hosted RPC proxies (`hosted/`, all on the SDK's typed clients through one `hosted::client::HostedClient`: billing, team and usage, referral, announcements, webhook tunnels, managed Telegram/Discord linking, and backend-brokered OAuth — registered into the core's controller registry as an extension, some sharing the core's `auth` / `channels` / `webhooks` namespaces), and the host-side login/session owner (`session/`). A user without a TinyHumans account gets the core's `BACKEND_UNAVAILABLE:` sentinel from these without a request. |+| **`crates/openhuman-cli/`** | The `openhuman-core` binary (installs the tinyhumans transport, then `run_core_from_args`), the developer/benchmark bins, and every root `tests/*.rs` / `examples/*.rs` target. |+| **`crates/openhuman-tui/`** | Standalone ratatui terminal frontend. Boots the core in-process via `CoreBuilder` (`DomainSet::full()`, `ServiceSet::none()`), no HTTP. |+| **`Cargo.toml`** (root) | Virtual workspace for `openhuman-core`, `openhuman-embed`, `openhuman-rpc`, `openhuman-tinyhumans`, `openhuman-cli`, and `openhuman-tui` (`cargo build -p openhuman-cli --bin openhuman-core` builds the standalone CLI/server); `vendor/`, `worktrees/`, `crates/openhuman-app`, `app/src-tauri-mobile`, and `packages/tauri-plugin-ptt` are excluded. Holds the `[patch]` tables for vendored crates. There is no sidecar: the desktop bundle links the core in-process (`app/package.json` `core:stage` is a documented no-op). |+| **`crates/openhuman-core/src/skills/`** | Skill metadata and run orchestration (`ops_create`, `ops_discover`, `ops_install`, `ops_parse`, `catalog/`, `registry`, `runtime/`, `schemas/`, `types`, `bundled/`, `webhooks/`). The legacy QuickJS / `rquickjs` skill execution runtime was removed; skills contribute metadata + tool descriptors that get injected into agent prompts, while tool execution flows through native Rust handlers and Node-backed helpers via `runtime::node` (Cargo feature `runtime-node`). |+| **`gitbooks/`** | This book (public product and contributor documentation). |+| **`docs/`** | Internal maintainer documentation (test-coverage matrix, release smoke checklist, library benchmarking notes). |+| **`vendor/`** | Recursive git submodules for the `tiny*` crate family (`tinyagents`, `tinyflows`, `tinychannels`, `tinyjuice`, `tinymemory`, `tinymcp`, `tinybus`, `tinybox`, `tinycomputer`, `tinyruntime`, `tinydocs`, `tinysearch`, `tinyskills`, `tinyvoice`, `tinywallet`, `tinyhosts`, `tinyconnectors`, `tinyhumans-sdk`) plus `motosan-ai-oauth`. |++The desktop app **WebView** loads the UI from `app/`; RPC, agents and skills run in the **`openhuman_core`** core, hosted in-process as a tokio task by the Tauri shell (`crates/openhuman-app/src/core_process.rs`, `run_server_embedded_with_ready`) and reachable over loopback HTTP. The renderer's `coreRpcClient` `fetch()`es `http://127.0.0.1:<port>/rpc` directly; the `relay_http_rpc` Tauri command (backed by `openhuman_rpc::post_json_rpc`) is only the fallback for non-loopback plain-`http://` runtimes that the webview would block as mixed content. The standalone `openhuman-core serve` binary is the CLI/debug path.++***++## Platform reach++**Supported today (end users):** desktop. Windows, macOS, Linux (native installers).++**Not supported yet:** Android, iOS, standalone web client (may exist as experimental targets in the repo; do not treat as product-ready).++```+ OpenHuman (shipping)+ |+ Desktop+ / | \+ Windows macOS Linux+ x64 x64 x64+ ARM64 ARM64 ARM64+```++Tauri v2 compiles the Rust core into native binaries per platform, embedding the React frontend as a lightweight WebView. Desktop builds produce `.dmg`, `.msi`, `.AppImage`, and `.deb` installers. Additional targets (mobile, web) are out of scope until explicitly documented as supported.++***++## High-level architecture++```++------------------------------------------------------------------++| React Frontend |+| Redux Toolkit | coreRpcClient (fetch) | Socket.IO client | UI |++------------------------------------------------------------------++ | HTTP JSON-RPC (loopback) | Socket.IO (loopback)+ | Tauri IPC (windows, hotkeys, relay_http_rpc fallback)++------------------------------------------------------------------++| Rust Core (openhuman_core) |+| |+| +------------------+ +------------------+ +-----------------+ |+| | Agent harness | | Socket Manager | | Memory (v2) | |+| | (tinyagents) | | (client to | | + encryption | |+| | + tool dispatch | | backend, WS) | | at rest | |+| +------------------+ +------------------+ +-----------------+ |+| |+| +------------------+ +------------------+ +-----------------+ |+| | Skill metadata | | Cron Scheduler | | Session & Auth | |+| | & tool registry | | (`cron` domain) | | Management | |+| +------------------+ +------------------+ +-----------------+ |+| |+| +------------------+ +------------------+ +-----------------+ |+| | Channel | | SQLite Storage | | OS Keychain | |+| | integrations | | (rusqlite) | | Integration | |+| +------------------+ +------------------+ +-----------------+ |++------------------------------------------------------------------++ |+ +-----------+-----------++ | |+ TinyHumans backend External APIs+ (Socket.IO + REST) (Telegram, etc.)+```++The frontend communicates with the **openhuman** Rust core in two ways: **Tauri IPC** for shell commands (windows, hotkeys, and the **`relay_http_rpc`** HTTP relay used only for non-loopback plain-`http://` runtimes) and **HTTP JSON-RPC over loopback** for business logic and tools, plus a **Socket.IO bridge served by the core itself** for live events (chat streaming, notifications). The core owns the outbound persistent connection to the TinyHumans backend, the memory engine binding (memory items themselves are stored in CortexDB, not on the device), and tool execution: agent turns run through the `tinyagents` harness, and tools dispatch as native Rust handlers, plus Node-backed helpers via `runtime::node`, gated by the `security/` sandbox policy. Skills no longer execute in-process; the `crates/openhuman-core/src/skills/` domain contributes metadata and tool descriptors that get injected into agent prompts. External MCP clients (Claude Desktop, Cursor, Zed) reach the same tool surface over a separate stdio MCP server; see [MCP Server](../mcp-server.md).++***++## Rust-powered performance++OpenHuman chose Tauri + Rust over Electron for performance and security reasons. See [Performance](../performance.md) for measured numbers (agents-per-process density, cold start, binary size); the table below is qualitative:++| Metric | OpenHuman (Tauri + Rust) | Typical Electron App |+| ------------------------- | -------------------------------------------------------------------------- | ----------------------------------------- |+| Binary size | Feature-dependent (native Wry webview; no bundled Chromium) | \~150 MB+ |+| Memory per tool execution | Native Rust (no per-tool VM); shared managed Node runtime for helper calls | \~150 MB+ (Chromium renderer per process) |+| Cold startup | Sub-500ms | 2-5 seconds |+| Garbage collection pauses | None (Rust ownership model) | V8 GC pauses |+| Memory safety | Compile-time guaranteed | Runtime exceptions |+| TLS implementation | rustls (no OpenSSL dependency) | Chromium's BoringSSL |++Why this matters in practice: people run OpenHuman alongside other resource-heavy apps, browser tabs, IDEs, chat clients, dashboards. A native binary with sub-500ms startup means the app feels native and stays out of the way instead of competing for the same CPU and memory budget. No GC pauses means background work such as memory writes and socket events does not stall while a collector runs.++The **Tokio async runtime** drives all I/O. WebSocket connections, HTTP requests, file operations, and inter-skill communication, as non-blocking tasks on a thread pool. Thousands of concurrent operations (skill executions, cron jobs, socket events) share a small fixed set of OS threads.++***++## Real-time socket infrastructure++OpenHuman implements a **dual-socket architecture**: a Rust-native WebSocket client on desktop and a JavaScript Socket.io client on web. The Rust implementation survives app backgrounding, operates independently of the WebView, and handles TLS via rustls.++```+Desktop Mode: Web Mode:+++-------------+ +-------------++| React UI | | React UI |++------+------+ +------+------++ | Tauri IPC | Direct++------+------+ +------+------++| Rust Socket | | JS Socket |+| Manager | | .io Client |++------+------+ +------+------++ | tokio-tungstenite | Socket.io+ | + rustls TLS | (websocket/polling)++------+------+ +------+------++| Backend | | Backend |++-------------+ +-------------++```++The Rust socket manager implements Engine.IO v4 and Socket.IO v4 framing over a raw WebSocket. On handshake it connects, waits for the Engine.IO OPEN frame (which carries `sid`, `pingInterval`, `pingTimeout`), then sends the Socket.IO CONNECT with JWT auth and waits for the ACK. For keep-alive it answers each Engine.IO PING with a PONG; the connection is considered dead after `pingInterval + pingTimeout + 5s` (50 seconds with the defaults). Reconnection backs off exponentially from 1 second up to a 30-second cap, resetting to 1s once a connection that had been established is lost, but continuing to grow if a connection was never established in the first place. Because it is plain Rust `reqwest` rather than a browser fetch, it also sidesteps CORS: outbound API calls go out directly, with no browser restrictions to work around.++The socket connection is shared across the process rather than opened per skill or per tool, so events are routed to the right handler over async message channels instead of paying a new connection each time.++***++## Skills++Skills are `SKILL.md` packages (metadata, instructions, optional bundled scripts/resources) that extend the agent with reusable workflows. The legacy model, one sandboxed QuickJS VM per skill with per-skill bridge APIs and an embedded 5-second cron tick, is gone.++Responsibilities are split across three domains:++| Domain | Role |+| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `crates/openhuman-core/src/skills/` | Skill metadata: create/discover/install/parse `SKILL.md` and inject descriptors into agent prompts (`ops_create`, `ops_discover`, `ops_install`, `ops_parse`, `registry`, `tools`). |+| `crates/openhuman-core/src/skills/catalog/` | Registry of installed skills. |+| `crates/openhuman-core/src/skills/runtime/` | Execution of installed `SKILL.md` workflows: starts/cancels runs, reads run metadata/logs, resolves language runtimes. The orchestrator runs an installed skill itself through `run_workflow`. |++**Skill discovery** uses `SKILL.md` plus optional bundled resources:++| Field | Purpose |+| ----------------- | ------------------------------ |+| `name` | Human-readable display name |+| `description` | Trigger/selection summary |+| `metadata.id` | Stable skill slug when present |+| `allowed-tools` | Tool allowlist guidance |+| bundled resources | scripts, references, assets |++**Language runtimes**: script-backed skills run through shared runtime domains rather than embedded VMs. `runtime::node` (Cargo feature `runtime-node`) resolves a compatible system `node` or installs a managed distribution (SHA-256-verified) into the OpenHuman cache, and `runtime::python` does the same for Python. Execution is gated by the `security/` sandbox policy like any other tool.++**Scheduling**: recurring work is owned by the `cron` domain (with `scheduler_gate`), not by skills; there is no per-skill `onCronTrigger()` handler.++***++## AI and tool protocol (MCP)++OpenHuman implements the **Model Context Protocol** on both sides of the connection. As a client, the core browses Smithery and the official MCP registry, connects servers a user declares in `mcp.json`, and surfaces their tools to agents through the same tool registry native tools use; see [MCP registry](mcp-registry.md). As a server, `openhuman-core mcp` exposes OpenHuman's own tools over stdio or HTTP so external MCP hosts such as Claude Desktop, Cursor, and Zed can call them; see [MCP server](../mcp-server.md).++Every remote tool definition, whether coming in through a connected server or served out to a host, passes a prompt-injection scan before it reaches a model. Tool execution itself runs through the same Tool Registry as native tools: native Rust handlers or Node helpers via `runtime::node`, gated by `SecurityPolicy` and the active sandbox backend.++## Memory++Memory v2 is three operations (Recall, Fetch, Store) over a pluggable engine: `tinyhumans` (hosted CortexDB behind the backend's `/memory/*` routes, needs a session or TinyHumans API key) or `cortexdb` (your own endpoint and key); with neither, memory is off. Items live in CortexDB; only bookkeeping (job queue, sync/import state) is written under `<workspace>/memory/`. The contract and engines live in `vendor/tinymemory`, which is three crates: `tinymemory-api` (the contract, no I/O), `tinymemory-tools` (the agent surface and lifecycle over any engine) and `tinymemory-integrations` (everything that touches the outside world, one Cargo feature per module). OpenHuman's `crates/openhuman-core/src/memory/` keeps the host side: engine binding, ops, the single `memory` agent tool, conversation buffering, document sources, the consent-gated v1 import and the exit flush. The compiled `context.md` brief it used to own is gone, replaced by the per-turn memory pack. See [Memory architecture](memory.md), [Pluggable engines](../engines.md) and the spec `docs/specs/memory-v2.md`.++Conversation state is separate from memory: each thread's transcript is a JSONL file keyed by thread and agent id (the thread store is `tinyagents_session::threads` in `vendor/tinyagents`, wrapped by `threads::store`), and compaction seals a generation rather than deleting it, so the full history stays recoverable even though a resumed session only reads the latest generation.++***++## Security architecture++```++-------------------------------------------------------------------++| Security Layers |+| |+| +------------------+ +------------------+ +------------------+ |+| | OS Keychain | | Secrets at rest | | Tool sandbox | |+| | (macOS/Win/Lin) | | ChaCha20-Poly | | (platform jail | |+| | for credentials | | 1305 (`enc2:`) | | or Docker) | |+| +------------------+ +------------------+ +------------------+ |+| |+| +------------------+ +------------------+ +------------------+ |+| | Single-Use | | rustls TLS | | No localStorage | |+| | Login Tokens | | for all network | | for sensitive | |+| | (5-min TTL) | | connections | | data | |+| +------------------+ +------------------+ +------------------+ |++-------------------------------------------------------------------++```++Credentials go through the OS keychain via the `keyring` crate (macOS Keychain, Windows Credential Manager, Linux Secret Service), on desktop only. Executable tools run through `SecurityPolicy` (`crates/openhuman-core/src/security/policy/`: `types.rs`, `path_checks.rs`, `command_checks.rs`, `enforcement.rs`) and a host-appropriate sandbox backend selected at runtime. One consequence is worth stating plainly: when the `Local` backend is selected on a host with no usable OS jail, `sandbox/ops.rs` logs `[sandbox:local] OS backend unavailable, using noop` and spawns through the no-op backend, so the command runs **unconfined**. Landlock covers Linux and Seatbelt covers macOS; the Windows AppContainer backend exists upstream but is not compiled, so Windows is the case that hits this path. Use the Docker backend where confinement has to hold. The backends no longer live in `security/`: `crates/openhuman-core/src/sandbox/` picks between none, the OS jail (Landlock on Linux, Seatbelt on macOS) and Docker, over the `tinybox` crates. The legacy per-skill QuickJS memory and stack limit model is gone. Web-to-desktop auth handoff uses single-use login tokens with a 5-minute TTL, exchanged via the Rust HTTP client so it bypasses browser CORS. All WebSocket and HTTP connections use rustls, with no dependency on the platform's OpenSSL. Sensitive state lives in Redux (in memory) and the OS keychain (persistent); nothing sensitive goes into localStorage. User prompts are normalized, scored, and enforced server-side (`allow | review | block`) before model or tool execution; see `crates/openhuman-core/src/security/prompt_injection/`.++***++## End-to-end data flow++A complete flow from user action to external service and back:++```+User types a command in the chat UI+ |+ v+Frontend sends the turn to the core over HTTP JSON-RPC+ |+ v+Agent harness (tinyagents) runs the turn, sees the tool catalog+ |+ v+Model decides to call a tool (e.g., send a Telegram message)+ |+ v+Tool Registry routes to the registered handler+ |+ v+Handler executes: native Rust, or a Node helper via `runtime::node`+ |+ v+Handler runs through `SecurityPolicy` and the active sandbox backend+ |+ v+External call: reqwest over rustls, a channel driver, SQLite, OS keychain, etc.+ |+ v+External service responds+ |+ v+Result flows back through the harness to the frontend over Socket.IO or the RPC response+ |+ v+User sees the result in the chat interface+```++Every layer is async and non-blocking. The Rust core runs concurrent tool executions, cron triggers, and socket events on a fixed Tokio thread pool.++***++## Vendored crate family & recent shifts++Core subsystems run on published `tiny*` crates, vendored as git submodules under `vendor/` (`tinyagents`, `tinyflows`, `tinychannels`, `tinyjuice`, `tinymemory`, …) so crate changes can be tested in-tree before publishing. `tinymemory` no longer vendors a local engine; it holds the Memory v2 contract and the CortexDB engine. The major ownership boundaries are:++* **Agent engine on tinyagents.** Every agent turn runs through the `tinyagents` crate harness via the seam in `crates/openhuman-core/src/agent/tinyagents/`; see [Agent harness](agent-harness.md).+* **Memory on tinymemory (v2).** The contract, CortexDB engine, sources, safety scrubbing, context compiler and v1 importer are crate-owned (`vendor/tinymemory`). OpenHuman keeps the host side under `crates/openhuman-core/src/memory/` (see [Memory architecture](memory.md)). The chat thread store moved to `tinyagents_session::threads`.+* **Inference on the crate ModelRouter.** Host workload-tier model routing and cloud provider slugs now use the crate-native `ModelRouter`/`OpenAiModel` (#4782, #4783).++***++## Technology stack++| Layer | Technology | Why |+| -------------- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Frontend** | React 19, TypeScript 5.8 | Modern component model, type safety |+| **State** | Redux Toolkit + Persist | Predictable state with offline persistence |+| **Build** | Vite 7 | Sub-second HMR, optimized production builds |+| **Styling** | Tailwind CSS | Utility-first, consistent design system |+| **Framework** | Tauri v2 | Native cross-platform with minimal overhead |+| **Language** | Rust (2021 edition) | Memory safety, zero-cost abstractions |+| **Async** | Tokio | High-performance async I/O runtime |+| **JS Runtime** | Node.js | Managed V8 runtime for tool helpers and skill-adjacent JS |+| **Database** | SQLite (rusqlite) | Embedded, zero-config, per-domain stores |+| **WebSocket** | tokio-tungstenite + rustls | Persistent connections with native TLS |+| **HTTP** | reqwest | Async HTTP with rustls + native-tLS dual support |+| **Encryption** | chacha20poly1305 (secret store), aes-gcm + argon2 (`security/encryption/`) | Config-field secrets use ChaCha20-Poly1305 under a keychain-backed master key (`enc2:` prefix); the separate user-facing encryption facility uses AES-256-GCM with Argon2id |+| **Scheduling** | cron crate + `cron` domain | Standard cron expressions, `scheduler_gate`-gated |+| **Telegram** | `tinychannels` Bot API driver | Transport in vendored `tinychannels`; host keeps bus/approval glue |+| **Realtime** | Socket.io (client) | Bidirectional event-based communication |+| **AI** | MCP (JSON-RPC 2.0) | Standardized tool protocol for LLM integration |+| **Search** | OpenAI embeddings + SQLite FTS5 | Hybrid semantic + keyword search |++***++## iOS client (experimental)++The iOS client is a Tauri v2 app that shares the React/TypeScript UI codebase but ships **no Rust core binary on-device**. All AI, RPC, and domain logic remain on the desktop core; the iOS app is a thin transport client.++### Transport architecture++```+iOS App (React + Tauri iOS shell)+ |+ TransportManager (app/src/services/transport/TransportManager.ts)+ |-- LanHttpTransport direct HTTP to desktop core (same LAN)+ |-- TunnelTransport socket.io relay; E2E encrypted+ |-- CloudHttpTransport fallback via cloud backend API+```++Transport is selected by `ConnectionProfile` stored in secure storage. On pairing, the iOS app stores `{channelId, sessionToken, corePubkey, devicePrivkey}` after the client-side `tunnel:connect` succeeds.++### Pairing flow++1. Desktop: `devices_create_pairing` RPC -> backend ACKs `tunnel:register` with `{channelId, pairingToken, pairingExpiresAt}`.+2. Desktop shows QR: `openhuman://pair?cid=<>&pt=<>&cpk=<>&rpc=<>&exp=<>`.+3. iOS scans QR, generates X25519 keypair, connects to backend (`tunnel:connect`, `role:client`, `pairingToken`).+4. Backend consumes `pairingToken` (single-use) and returns iOS `sessionToken`.+5. X25519 key agreement over `tunnel:frame` -> XChaCha20-Poly1305 symmetric key.+6. Desktop emits `DomainEvent::DevicePaired`; device appears in the Devices panel.++### Key paths++| Path | Purpose |+| --------------------------------------------- | ------------------------------------------------------- |+| `crates/openhuman-core/src/security/devices/` | Rust devices domain (pairing, store, crypto, event bus) |+| `app/src/services/transport/` | TS transport strategies + manager |+| `app/src/lib/tunnel/` | TS tunnel crypto (X25519 + XChaCha20-Poly1305) |+| `app/src/pages/ios/` | iOS-specific screens (PairScreen, MascotScreen) |+| `packages/tauri-plugin-ptt/` | Swift PTT plugin (AVAudioEngine + SFSpeechRecognizer) |+| `app/src-tauri-mobile/Info.plist` | Privacy strings for the iOS Info.plist |++### Security++* Tunnel backend is a blind forwarder; it never sees plaintext payloads.+* `pairingToken` is single-use, TTL'd, hashed at rest on backend.+* `sessionToken` is per-client peer and revocable from the desktop Devices panel; the desktop core does not receive a session token during register.+* Speech recognition runs on-device (Apple Speech framework); audio never leaves the device.+* The iOS symmetric session key is held in memory, so a restart re-pairs rather than resuming.++### Backend dependency++The `tunnel:register` / `tunnel:connect` / `tunnel:frame` Socket.IO protocol is served by the TinyHumans backend. Pairing depends on it being deployed, which it is; see [iOS Companion](../../features/ios-companion.md) for the user-facing state of this client.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/flows-on-tinyagents.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/flows-on-tinyagents.mdnew file mode 100644index 0000000000..bdc3d15813--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/flows-on-tinyagents.md@@ -0,0 +1,219 @@+---+description: >-+ How a saved flow runs - lowering a WorkflowGraph onto tinyagents, the+ {run,nodes} run-state, the capability seam, agent-nodes-as-nested-graphs, the+ two-layer security model, and the one-trigger model.+icon: diagram-project+---++# Flows on TinyAgents++The **flows** domain ([`crates/openhuman-core/src/flows/`](../../../../../../../crates/openhuman-core/src/flows/)) drives saved automations - the workflows a user builds in the canvas or the copilot builds for them. It does **not** contain a workflow engine. Every flow is run by the vendored, host-agnostic [`tinyflows`](https://github.com/tinyhumansai/tinyflows) crate, which **lowers each workflow onto the same** [**`tinyagents`**](https://crates.io/crates/tinyagents) **state-graph engine that the** [**agent harness**](agent-harness.md) **runs on.** So a saved flow is a tinyagents graph, and (after harness unification) each of its `agent` nodes is _itself_ a tinyagents graph - a graph within a graph.++This page is the flows counterpart to [Agent Harness](agent-harness.md): where that page explains how one agent _turn_ runs, this one explains how one _flow_ runs, and how the two runtimes compose.++## Two crates, one engine++| Crate | Role | Where |+| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |+| `tinyflows` | Host-agnostic workflow model + validate + compile + run. Never hard-codes a vendor; every outside-world effect goes through a capability trait. | [`vendor/tinyflows/`](https://github.com/tinyhumansai/tinyflows) |+| `tinyagents` | The published state-graph + agent-loop harness both runtimes lower onto. | crate; OpenHuman seam in [`crates/openhuman-core/src/agent/tinyagents/`](../../../../../../../crates/openhuman-core/src/agent/tinyagents/) |+| `openhuman::flows` | The host: CRUD/run/resume RPCs, SQLite store, triggers, the builder/scout agents. | [`crates/openhuman-core/src/flows/`](../../../../../../../crates/openhuman-core/src/flows/) |+| `openhuman::flows::tinyflows` | The **capability seam** - adapters implementing the `tinyflows` traits over real OpenHuman services. | [`crates/openhuman-core/src/flows/tinyflows/`](../../../../../../../crates/openhuman-core/src/flows/tinyflows/) |++`tinyflows` is published to crates.io and is deliberately persistence-free and vendor-free (see its [`CLAUDE.md`](https://github.com/tinyhumansai/tinyflows/blob/main/CLAUDE.md)); OpenHuman is the first downstream host and injects everything real through the seam.++## The run pipeline++A flow is a [`WorkflowGraph`](https://github.com/tinyhumansai/tinyflows/tree/main/crates/tinyflows/src/model) - a directed graph of typed \[`Node`]s joined by \[`Edge`]s, JSON on the wire. Running it is a fixed four-stage pipeline ([`vendor/tinyflows/crates/tinyflows/src/lib.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/lib.rs), [`compiler.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/compiler.rs), [`engine.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/engine.rs)):++```mermaid+flowchart LR+ subgraph host["openhuman::flows (host)"]+ store[(SQLite<br/>flow store)] --> graph[WorkflowGraph<br/>JSON]+ end+ graph --> validate["validate<br/>(structural)"]+ validate --> compile["compiler::compile<br/>(lower onto tinyagents)"]+ compile --> gb["tinyagents<br/>GraphBuilder"]+ gb --> run["engine::run_with_checkpointer<br/>(drive to completion)"]+ run --> outcome["RunOutcome<br/>{ output, pending_approvals, cancelled }"]+ seam["openhuman::flows::tinyflows<br/>capability seam"] -. host-injected .-> run+```++1. **validate** ([`validate.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/validate.rs)) - structural checks over the raw graph: unique node ids, that every referenced node exists, and **exactly one trigger node** (0 → `MissingTrigger`, >1 → `MultipleTriggers`). This is the single-trigger invariant the whole model rests on (see [Trigger model](flows-on-tinyagents.md#the-trigger-model)).+2. **compile** ([`compiler.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/compiler.rs)) - runs validation, then lowers the validated graph onto a fresh `tinyagents` state graph. **Every tinyflows node becomes a tinyagents graph node**; every tinyflows edge becomes a graph edge, with conditional/parallel routing and a merge barrier expressed on the tinyagents graph layer. The graph is rebuilt per run so compilation stays independent of any host state.+3. **run** ([`engine.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/engine.rs)) - the host calls `engine::run_with_checkpointer_journaled_observed` ([`flows/ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/ops.rs), `flows_run`), which drives the compiled graph to completion, folding each node's output into the run state and pausing at approval gates.+4. **outcome** - a `RunOutcome { output, pending_approvals, cancelled }`; the host persists live steps through the `FlowRunObserver` and exports the durable graph observations to Langfuse ([`tinyflows/langfuse_export.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs)).++Because the engine keys persisted state by a caller-supplied `thread_id`, durable **HITL resume** is `engine::resume_with_checkpointer` over the same `tinyagents::graph::SqliteCheckpointer` the agent harness uses - opened once per host at `<workspace_dir>/flows/checkpoints.db` ([`caps/ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs), `open_flow_checkpointer`).++## Run state: one JSON map, a merge reducer, and the `{json,text,raw}` envelope++The entire run's working memory is a single `serde_json::Value` laid out as ([`vendor/tinyflows/crates/tinyflows/src/engine.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/engine.rs)):++```json+{+ "run": {+ "trigger": {/* the trigger payload seeded at start */}+ },+ "nodes": {+ "planner": {+ "items": [/* … */]+ },+ "drafter": {+ "items": [/* … */]+ }+ }+}+```++As the graph executes, a **merge reducer** folds each node's item output into `nodes.<id>`. Because merging is additive rather than last-writer-wins, a **fan-in** node can see every predecessor's output at once, and a **fan-out** (`split_out`) node's parallel branches merge back at the barrier without clobbering one another - the same reducer pattern the tinyagents graph layer uses for its own `map_reduce` fan-out (see [Agent Harness](agent-harness.md)).++Every **capability node** (agent / tool\_call / http\_request / code) emits its output wrapped in a stable **`{ json, text, raw }` envelope**. Downstream nodes never see the raw completion shape - they bind against the envelope:++* `=item.json.<field>` - the structured object (when the producer emitted JSON);+* `=item.text` - the prose form;+* `=item.raw` - the untouched producer output.++### The `=`-expression scope++Node config is resolved through jq/jaq `=`-expressions ([`vendor/tinyflows/crates/tinyflows/src/expr.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/expr.rs)) against a per-node **scope** with four bindings:++| Binding | What it holds |+| ------- | ------------------------------------------------------------------------------------------- |+| `item` | the first input item's `json` (the direct predecessor's output) |+| `items` | every input item's `json`, in edge order |+| `run` | run metadata and the **trigger payload** (`run.trigger`) |+| `nodes` | **every completed node's output, keyed by id**: `{ "<id>": { "item": …, "items": [ … ] } }` |++So a node three hops downstream can reach back to a specific ancestor by id - `"=nodes.planner.item.json.plan"` - which is exactly how the demo workflow passes the planner's structured plan into the drafter's prompt. A `"=item.text"` form is the short-hand for the immediate predecessor. Missing segments resolve to `null` rather than erroring, and a malformed jq program yields `null` rather than panicking - node wiring never crashes the run.++## The capability seam++`tinyflows` touches nothing real on its own. Everything - LLM calls, tools, HTTP, code, persistence, sub-workflow lookup - is a **capability trait** the host implements ([`vendor/tinyflows/crates/tinyflows/src/caps/mod.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/caps/mod.rs)). `openhuman::flows::tinyflows::caps` supplies one adapter per trait, assembled into a `Capabilities` bundle per run by `build_capabilities` ([`caps/`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/caps/mod.rs)):++| tinyflows trait | Node(s) it backs | OpenHuman adapter | Wraps |+| ------------------ | ------------------------------- | ------------------------------------------- | ------------------------------------------------ |+| `LlmProvider` | `agent` (bare), `output_parser` | `OpenHumanLlm` | `inference/provider` (`create_chat_provider`) |+| `AgentRunner` | `agent` (with `agent_ref`) | `OpenHumanAgentRunner` | the agent registry + harness `Agent` |+| `ToolInvoker` | `tool_call` | `OpenHumanTools` | Composio + native `oh:` tools |+| `HttpClient` | `http_request` | `OpenHumanHttp` | `HttpRequestTool` (allowlist + DNS-rebind guard) |+| `CodeRunner` | `code` | `OpenHumanCode` | the sandbox (`execute_in_sandbox`) |+| `StateStore` | resumable/stateful runs | `tinyflows_sqlite::flows::SqliteStateStore` | a namespaced KV table in `flows.db` |+| `WorkflowResolver` | `sub_workflow` by id | `OpenHumanWorkflowResolver` | the saved-flow store (`load_flow_graph`) |+| `MemoryProvider` | `memory` | `OpenHumanMemory` | the memory store (`tinyflows/memory_adapter.rs`) |++`AgentRunner` is **optional** in the crate (`Capabilities::agent` is `Option`): a host without an agent registry leaves it `None` and `agent` nodes fall back to a bare `LlmProvider` completion. OpenHuman always wires it, so `agent` nodes get the real agent runtime described next. Of the remaining optional slots, `tasks` takes the crate's own `TokioTaskRunner`, while `shell` and `approvals` are left `None`: there is no host shell adapter yet, and approvals reuse the engine's pause-and-`flows_resume` fallback.++## Agent nodes: a graph within the graph++A flow `agent` node names a **registered agent kind** through a trusted `agent_ref` in its config (a custom specialist, …). `OpenHumanAgentRunner::run_agent` resolves that ref and routes on what it finds:++* **A harness `AgentDefinition` exists** → build a full harness `Agent` (`Agent::from_config_for_agent`) and run the node's request through `run_single`. That is the _same_ entry the builder/scout and cron jobs use, and internally it drives `run_turn_via_tinyagents_shared` ([`crates/openhuman-core/src/agent/tinyagents/mod.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/agent/tinyagents/mod.rs)) - the tinyagents `AgentHarness` tool-call loop. The definition's ToolScope, `sandbox_mode`, and `max_iterations` govern the inner turn.+* **Only a custom `AgentRegistryEntry` exists** (no full definition) → the persona-shaping fallback: the entry's `system_prompt` (and model, when the node didn't pin one) is prepended and the request runs through `OpenHumanLlm::complete` - a single completion, no private tool loop. This keeps custom registry agents working without a regression.++The consequence is the nesting the plan set out to achieve: **the flow is a tinyagents graph whose `agent` nodes each run a nested tinyagents graph (one agent turn).**++```mermaid+flowchart TB+ subgraph flow["Flow = tinyagents graph (compiled WorkflowGraph)"]+ t[trigger] --> a["agent node<br/>agent_ref = planner"]+ a --> tc[tool_call node]+ tc --> tr[transform node]+ end+ a -.->|"run_agent → Agent::from_config_for_agent → run_single"| inner+ subgraph inner["Agent turn = nested tinyagents graph (AgentHarness)"]+ p[provider call] --> parse[parse tool calls]+ parse --> tools[dispatch tools]+ tools --> compact[context guard]+ compact --> p+ parse --> done[final text]+ end+ done -.->|"{ json, text, raw } envelope"| tc+```++Either path returns a JSON value; the `agent` node folds it into the `{ json, text, raw }` envelope (with an `output_parser` sub-port applying the node's declared schema), so a downstream node's binding is identical whether the node ran a full agent turn or a bare completion.++`agent_ref` is resolved **from trusted node config only, never from model output**, so a prompt-injected upstream completion cannot pick an arbitrary agent kind. The **builder's dry-run** exercises this path too: `dry_run_workflow` compiles a draft and runs it against `tinyflows`' _mock_ capabilities wired with a `MockAgentRunner` ([`vendor/tinyflows/crates/tinyflows/src/caps/mock.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/caps/mock.rs)), so a draft whose `agent` nodes carry an `agent_ref` is self-tested end-to-end before it is ever saved.++## The security model: two gates++A flow run is guarded on **two independent layers**, an outer one owned by the flows runtime and an inner one owned by the agent harness.++**Outer gate - the flow's origin + autonomy tier.** `flows_run`/`flows_resume` scope a `TrustedAutomation { source: Workflow { require_approval } }` origin around the whole engine future ([`flows/ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/ops.rs), via `with_origin`). Before an _acting_ node dispatches, the seam consults the user's `[autonomy]` tier through `SecurityPolicy::gate_decision` for that node's `CommandClass` (`http_request` → Network, `code` → Write, native `oh:` tools → their classified class) in `enforce_node_tier_gate` ([`caps/`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/caps/mod.rs)):++* a `readonly` run **`Block`s** at the network/code boundary and never dispatches;+* a `supervised` run's `Prompt` decision is escalated by `gate_call_for_tier` into a **forced `ApprovalGate` round-trip** - even when the flow's own `require_approval` is `false`, so the tier's "ask me" can't be silently defeated by a saved flow's default trust;+* a `full` run passes through.++Composio `tool_call` nodes get an extra deny-by-default **curation gate** (`is_curated_flow_tool`): a slug is allowed only if it resolves to a known, curated, in-scope, connected toolkit action - stricter than the general agent tool-call path, because a flow's slug is a free-form string the author typed rather than one the backend returned from live discovery.++**Inner gate - the agent definition's ToolScope + sandbox.** When an `agent` node runs a full harness `Agent`, that turn runs under the _same_ `Workflow` origin (the engine future is already inside `with_origin`), so the autonomy tier and approval gate apply to the inner turn automatically - **no new origin wrapper**. On top of that, the agent definition's own `ToolScope`, `sandbox_mode`, and iteration cap bound what the turn can do, exactly as they do for a chat sub-agent. So an `agent` node is gated twice: the flow's outer autonomy/origin gate and the agent's inner tool/sandbox gate.++`agent_ref` being trusted-config-only is the third leg: untrusted trigger or upstream data can influence _arguments_ (bounded by the curation + scope + approval checks) but never _which agent kind or tool identity_ runs.++## The trigger model++`tinyflows` enforces **exactly one trigger node per graph** at validate time ([`validate.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/validate.rs)). A workflow therefore has a single entry point, and the trigger's payload is what seeds `run.trigger` in the run state.++That is a _model-level_ constraint, not a product limitation. **Multi-trigger is a host-side concern today**, handled by the flows domain rather than the engine. `FlowTriggerSubscriber` ([`flows/bus.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/bus.rs)) is the trigger → run bridge: it subscribes to the normalized domain events a saved flow's single trigger node can bind to and calls `flows::ops::flows_run` for each match:++* **`DomainEvent::FlowScheduleTick`** - a `flow`-type cron job fired; the one named flow is loaded, re-checked for a still-live `schedule` trigger, and dispatched with an empty trigger payload.+* **`DomainEvent::ComposioTriggerReceived`** - every enabled flow with an `app_event` trigger bound to that `toolkit`/`trigger_slug` is dispatched with the event payload seeded into `run.trigger`.++Dispatch is deduped per `flow_id` (a trigger burst can't spawn overlapping runs for the same flow), while the interactive `flows_run` RPC is deliberately _not_ deduped - a user asking to run a flow again is always honored.++So "run this flow on a schedule **and** when a Gmail message arrives" is expressed as two host subscriptions fanning into the same one-trigger graph. **Model-level multiple triggers on one graph are future work**, tracked as such; nothing in the seam or the store depends on it today.++## Builder, scout, and executor: one harness++The three agents that touch flows all run on the shared agent harness - `Agent::from_config_for_agent` → `run_single` under a scoped origin - the same pattern the flow's own `agent` nodes use:++| Agent | Registry id | Entry point | Tool belt |+| --------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Builder** (copilot) | `workflow_builder` | `flows_build` ([`ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/ops.rs)) | `propose_workflow` / `revise_workflow` (validate-only), `dry_run_workflow` (compile + run vs. mocks), `save_workflow`, `run_workflow`, catalog/connection reads ([`builder_tools.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/builder_tools.rs)) |+| **Scout** (discovery) | `flow_discovery` | `flows_discover` ([`ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/ops.rs)) | `suggest_workflows` ([`discovery_tools.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/discovery_tools.rs)) |+| **Executor** | _(n/a - the engine)_ | `flows_run` / `flows_resume` | the capability seam above |++Both agents live under [`crates/openhuman-core/src/flows/agents/`](../../../../../../../crates/openhuman-core/src/flows/agents/) as first-class registry agents (`agent.toml` + `prompt.md`), on the reasoning tier with narrow, safety-reviewed tool belts. The builder is tool-assisted end-to-end: it _proposes_ graphs (validate-only), _dry-runs_ them against mock capabilities as a self-test loop, and only then _saves_ and confirm-first _test-runs_ a real flow. The full discover → build → save → run lifecycle:++```mermaid+sequenceDiagram+ participant U as User+ participant S as flow_discovery<br/>(scout)+ participant B as workflow_builder<br/>(builder)+ participant St as flow store<br/>(SQLite)+ participant E as tinyflows engine++ U->>S: flows_discover+ S->>S: suggest_workflows (validate ideas)+ S-->>U: FlowSuggestion[]+ U->>B: flows_build (pick a suggestion / prompt)+ B->>B: propose_workflow (validate draft)+ B->>E: dry_run_workflow (compile + run vs. mocks)+ E-->>B: mock RunOutcome (self-test)+ B->>St: save_workflow (existing flow)+ B-->>U: WorkflowProposal+ U->>E: flows_run (confirm-first)+ E->>E: validate → compile → run (real caps)+ E-->>U: RunOutcome (live steps + Langfuse trace)+```++## Where to look in the code++| Path | What lives there |+| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| [`vendor/tinyflows/crates/tinyflows/src/`](https://github.com/tinyhumansai/tinyflows/tree/main/crates/tinyflows/src) | The engine: `model/`, `validate.rs`, `compiler.rs`, `engine.rs`, `expr.rs`, `caps/`, `nodes/`. |+| [`vendor/tinyflows/crates/tinyflows/src/caps/mod.rs`](https://github.com/tinyhumansai/tinyflows/blob/main/crates/tinyflows/src/caps/mod.rs) | The capability traits + `Capabilities` bundle. |+| [`crates/openhuman-core/src/flows/tinyflows/caps/`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/caps/mod.rs) | The host adapters, `build_capabilities`, `open_flow_checkpointer`, the two-layer gate helpers. |+| [`crates/openhuman-core/src/flows/ops.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/ops.rs) | `flows_run` / `flows_resume` / `flows_build` / `flows_discover` and CRUD. |+| [`crates/openhuman-core/src/flows/bus.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/bus.rs) | `FlowTriggerSubscriber` - the host-side multi-trigger bridge. |+| [`crates/openhuman-core/src/flows/builder_tools.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/builder_tools.rs) | The builder's `propose` / `revise` / `dry_run` / `save` / `run` tools. |+| [`crates/openhuman-core/src/flows/agents/`](../../../../../../../crates/openhuman-core/src/flows/agents/) | `workflow_builder` + `flow_discovery` agent definitions. |+| [`crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/flows/tinyflows/langfuse_export.rs) | Post-run export of the durable graph observations. |++## See also++* [Agent Harness](agent-harness.md) - the tinyagents turn every `agent` node (and the builder/scout) runs on.+* [Security (`crates/openhuman-core/src/security/`)](security.md) - the `SecurityPolicy` / autonomy tier the outer node gate consults.+* [Architecture overview](./) - where flows sit in the bigger picture.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/frontend.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/frontend.mdnew file mode 100644index 0000000000..386b69b7d0--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/frontend.md@@ -0,0 +1,646 @@+---+description: >-+ The React + Vite frontend (`app/src/`) - architecture, state, services,+ providers, routing, components, hooks.+icon: browsers+---++# Frontend++`app/src/` is the OpenHuman desktop UI: a Vite and React 19 tree in the pnpm workspace `openhuman-app`. It uses Redux Toolkit with persistence for session state, talks to the in-process Rust core over JSON-RPC (`coreRpcClient` → local HTTP, with the Tauri `relay_http_rpc` command as a fallback relay) and socket.io (`socketService`), and reaches the cloud backend via REST (`apiClient`). Heavy logic lives in the core, not here.++This is one consolidated reference. Use the table of contents above (or your reader's outline) to jump between sections.++The tree also carries a **mobile shell**: `AppRoutesIOS.tsx`, `pages/ios/`, the `services/transport/` connection profiles and the `app/src-tauri-mobile/` host. That client is **experimental and not part of the shipped desktop host**, which targets Windows, macOS and Linux only. It appears on this page because those files sit in the same tree and share the `App.tsx` provider chain, not because the client ships. See [iOS Companion](../../features/ios-companion.md) for what it is and what still has no desktop surface.++## Quick reference++| Section | Covers |+| ------------------------------------------------- | --------------------------------------------------------------- |+| [Architecture](frontend.md#architecture-overview) | Provider chain, build, layout, conventions |+| [State Management](frontend.md#state-management) | Redux Toolkit slices, selectors, persistence |+| [Services Layer](frontend.md#services-layer) | `apiClient`, `socketService`, `coreRpcClient` |+| [Providers](frontend.md#providers) | `ThemeProvider`, `CoreState`, `Socket`, `ChatRuntime` providers |+| [Pages & Routing](frontend.md#pages--routing) | `HashRouter`, route guards, main routes |+| [Components](frontend.md#components) | UI / settings component patterns |+| [Hooks & Utilities](frontend.md#hooks--utilities) | Shared hooks, helpers, config |++## Scale++| Metric | How to read it |+| --------------------------------------- | ----------------------------------------------------- |+| TypeScript / TSX files under `app/src/` | `find app/src -name '*.ts' -o -name '*.tsx' \| wc -l` |+| App-level hooks | `ls app/src/hooks/*.ts app/src/hooks/*.tsx \| wc -l` |+| Test runner | Vitest (`app/test/vitest.config.ts`) |++## Directory layout++```+app/src/+├── App.tsx # Provider chain + HashRouter shell (desktop + mobile shells)+├── AppRoutes.tsx # Desktop route table (AppRoutesIOS.tsx for mobile)+├── main.tsx # Entry (polyfills, Sentry, store, styles)+├── store/ # Redux slices, selectors, userScopedStorage persistence+├── providers/ # ThemeProvider, CoreStateProvider, SocketProvider, ChatRuntimeProvider+├── services/ # apiClient, socketService, coreRpcClient, transport/, api/*+├── lib/ # AI prompt loaders, i18n, MCP helpers, platform, tunnel crypto+├── pages/ # Route-level screens (incl. onboarding/, ios/, dev/)+├── features/ # Feature verticals (human/, conversations/, voice/, wallet/, skills/)+├── components/ # Shared UI (incl. settings/, layout/shell/, accounts/)+├── hooks/ # App hooks+├── utils/ # Config, Tauri command wrappers, routing utilities+└── assets/ # Icons and static assets+```++## Architecture overview++### System architecture++OpenHuman's desktop UI is a **React 19** app (`app/src/`) that:++* Uses **Redux Toolkit** with persistence for session-related state+* Connects to the backend with **REST** (`apiClient`) and to the local core with **Socket.io** (`socketService` → core socket endpoint)+* Calls the **Rust core** (embedded in the Tauri host as a tokio task) over HTTP via **`coreRpcClient`** (JSON-RPC methods implemented in `crates/openhuman-core/src/`); non-loopback plain-http runtimes are relayed through the Tauri **`relay_http_rpc`** command+* Leaves **AI prompts** to the core: bundled `crates/openhuman-core/src/agent/prompts` ship as Tauri resources (see `crates/openhuman-app/tauri.conf.json` resources) and are read core-side, not by the frontend+* Uses a **minimal MCP-style** helper layer under `lib/mcp/` (transport, validation)++### Entry points++| File | Purpose |+| ----------------------- | -------------------------------------------------------------------------------- |+| `app/src/main.tsx` | React root, polyfills, Sentry boundary, store, global styles |+| `app/src/App.tsx` | Provider chain (see below) + desktop/mobile shells, Settings modal overlay |+| `app/src/AppRoutes.tsx` | `HashRouter` routes, `ProtectedRoute` / `PublicRoute` / `DefaultRedirect` guards |++### Provider chain++_Generated from `app/src/App.tsx` by `scripts/generate-architecture-docs.mjs`. Do not edit by hand — run `pnpm docs:generate` to refresh._++| # | Component | Role |+| -- | ---------------------- | --------------------------------------------------------------------------- |+| 1 | `Sentry.ErrorBoundary` | Crash boundary; renders ErrorFallbackScreen |+| 2 | `Provider` | Redux store; enables useAppSelector / dispatch app-wide |+| 3 | `PersistGate` | Holds UI until persisted Redux slices rehydrate |+| 4 | `ThemeProvider` | Theme tokens and dark-mode handling |+| 5 | `I18nProvider` | Localization context consumed via useT |+| 6 | `BootCheckGate` | Blocks render until the core boot snapshot resolves |+| 7 | `CoreStateProvider` | Core app snapshot: auth, session, onboarding state |+| 8 | `SocketProvider` | Core socket.io events; desktop only (mobile uses the TunnelTransport relay) |+| 9 | `ChatRuntimeProvider` | Chat runtime events, tool timeline, and approvals |+| 10 | `Router` | HashRouter navigation for all routes |+| 11 | `CommandProvider` | Command palette context |+| 12 | `ServiceBlockingGate` | Blocks the shell until required services are configured |++**Why this order**++1. Redux `Provider` is outermost so `useAppSelector` / dispatch work everywhere.+2. `PersistGate` rehydrates persisted slices before children assume stable auth/session.+3. `BootCheckGate` / `CoreStateProvider` resolve the core boot snapshot (auth, onboarding) before feature providers mount.+4. `SocketProvider` (desktop only) and `ChatRuntimeProvider` depend on that core state for realtime events and approvals.+5. `Router` supplies navigation to all routes.++### Module relationships (simplified)++```+App.tsx+ ├─ Redux store + persistor+ ├─ ThemeProvider / I18nProvider - theme tokens, useT() localization+ ├─ BootCheckGate - waits for the core boot snapshot+ ├─ CoreStateProvider - auth/session/onboarding snapshot (fetchCoreAppSnapshot RPC)+ ├─ SocketProvider - socket.io connection to the local core (desktop only)+ ├─ ChatRuntimeProvider - chat streaming, tool timeline, approvals → Redux+ └─ AppShell (desktop or mobile)+ ├─ AppRoutes - PublicRoute / ProtectedRoute / DefaultRedirect+ └─ SettingsModal - overlay mounted when the URL is /settings/*+```++### Services layer (conceptual)++```+services/+ ├─ apiClient → REST to a URL resolved at runtime via `services/backendUrl#getBackendUrl`+ ├─ backendUrl → Calls `openhuman.config_resolve_api_url`; falls back to VITE_BACKEND_URL only outside Tauri+ ├─ socketService → Socket.io to the local core (base URL derived from the RPC URL); MCP-style envelopes+ ├─ coreRpcClient → JSON-RPC over HTTP to the local openhuman core; `relay_http_rpc` fallback for non-loopback http+ └─ transport/ → ConnectionProfile transports for iOS/remote (LanHttp, Tunnel, CloudHttp)+```++#### Runtime config precedence++The desktop app does not bake the core RPC URL or the API host into the bundle as a hard requirement. At runtime the app resolves them in this order (highest first):++1. **Welcome-screen RPC URL field**, saved via `utils/configPersistence` and restored on next launch. End users configure a self-hosted core address here, not by hand-editing `config.toml` or `.env` files.+2. **Tauri `core_rpc_url` command**, the port the embedded core is listening on for this process.+3. **`VITE_OPENHUMAN_CORE_RPC_URL`**, build-time fallback for development.+4. The hardcoded `http://127.0.0.1:7788/rpc` default.++Once the RPC handshake succeeds, `services/backendUrl` calls `openhuman.config_resolve_api_url` to pull `api_url` (and other safe client fields) from the loaded core `Config`. `VITE_BACKEND_URL` is only used as a web fallback when the app runs outside Tauri.++Components that need the backend URL should call `useBackendUrl()` (or `getBackendUrl()` from non-React code), they must not import the static `BACKEND_URL` constant from `utils/config`, which represents the build-time value only.++### Related docs++* Rust architecture: [Architecture](architecture.md)+* Tauri shell: [Tauri Shell](tauri-shell.md)++## State Management++The application uses Redux Toolkit with Redux-Persist. There is no single root persist config: each slice that persists wraps its own reducer with `persistReducer` in **`store/index.ts`**, whitelisting exactly the fields that should survive a restart.++### Storage backends++* `userScopedStorage` (`store/userScopedStorage.ts`) is the default storage for persisted slices. Blobs are keyed `${userId}:persist:<key>` so state never leaks across users on logout/login (#900).+* Plain `localStorage` is used only for pre-login, device-wide slices (`coreMode`, `locale`, `theme`) that must survive user switches.++### Slices++Authoritative list = the `reducer` map in `store/index.ts`. One-line purposes:++| Slice | Purpose | Persisted? |+| --------------------- | ------------------------------------------------------------------------------ | -------------------------------------------------------------- |+| `accounts` | Connected web-app accounts + rail ordering | `accounts`, `order`, `lastActiveAccountId` (not the active id) |+| `announcement` | Harness-init announcement banner, seen ids | `shownIds` |+| `channelConnections` | Messaging channel connections (WhatsApp, Slack, …) | connections + migration/default-channel fields |+| `chatRuntime` | Streaming buffers, tool timelines, inference status, artifacts | only `artifactsByThread` (ready snapshots) |+| `connectivity` | navigator.onLine, core health, renderer to core socket, core to hosted link | no |+| `coreMode` | Pre-login core mode selection (embedded / self-hosted / cloud) | `mode` (plain localStorage) |+| `followupSuggestions` | Follow-up chips for each thread's latest settled turn | no (in-memory only) |+| `githubStar` | Whether the user dismissed the in-app "Star us on GitHub" CTA | `dismissed` |+| `layout` | Two-pane layout geometry (sidebar visibility, dragged widths) | `panels` |+| `locale` | UI language | `current` (plain localStorage) |+| `mascot` | Mascot appearance / voice selection | `color`, `voiceId`, `customMascotGifUrl`, `selectedMascotId` |+| `notifications` | Notification items + preferences | `items`, `preferences` |+| `persona` | Cosmetic persona display name + description (SOUL.md lives in the core) | `displayName`, `description` |+| `ptt` | Push-to-talk hotkey + session prefs (`isHeld` deliberately excluded) | `shortcut`, `speakReplies`, `showOverlay` |+| `queue` | The core's per-thread run queue plus the composer's pending follow-up messages | no (in-memory only) |+| `runMode` | Per-thread plan/build run mode | no (in-memory only) |+| `socket` | Per-user socket connection status / socket ids | no (reconnects on boot) |+| `theme` | Theme mode, font size, message view mode, custom themes | plain localStorage |+| `thread` | Chat thread list + per-thread message caches | only `selectedThreadId` |+| `threadGoal` | Durable per-thread goal state | no (in-memory only) |+| `threadTodos` | Live per-thread todo list | no (in-memory only) |+| `userErrors` | User-actionable runtime errors (#3931) | no (in-memory only) |+| `walletPreferences` | Hidden-token preferences for the wallet view | `hiddenTokenKeys` |++Ephemeral chat state (streaming buffers, tool timelines) must **not** survive a restart: the UI would try to resume a turn whose live driver is gone. The one exception, agent-generated artifacts, goes through the `artifactsReadyOnlyTransform` in `store/index.ts` (pure logic in `store/artifactsPersistFilter.ts`).++### Typed hooks++File: `store/hooks.ts`++```typescript+// Use these instead of plain useDispatch/useSelector+export const useAppDispatch: () => AppDispatch = useDispatch;+export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;+```++### Best practices++1. Always use the typed hooks, `useAppDispatch` and `useAppSelector`.+2. Use selectors for derived state: see `store/socketSelectors.ts`, `store/connectivitySelectors.ts`, `store/userErrorsSelectors.ts`.+3. Whitelist persistence per slice. Never persist transient or loading state; add a per-slice `persistReducer` in `store/index.ts`.+4. Prefer Redux over ad hoc `localStorage`. Plain localStorage is reserved for the pre-login slices noted above.+5. In dev and E2E builds the store is exposed as `window.__OPENHUMAN_STORE__` so WDIO specs can assert backing state; production bundles do not expose it.++***++## Services Layer++The application uses singleton services for external communication. This prevents connection leaks and provides consistent API access.++### Service architecture++```+app/src/services/+ ├─ apiClient (HTTP REST)+ │ └─ backend URL resolved at runtime (services/backendUrl)+ ├─ socketService (Socket.io)+ │ └─ connects to the local core's socket endpoint (base derived from the RPC URL)+ ├─ coreRpcClient.ts+ │ ├─ direct webview fetch → local openhuman core (JSON-RPC over HTTP)+ │ └─ invoke('relay_http_rpc', …) fallback for non-loopback plain-http runtimes+ ├─ coreCommandClient.ts - typed wrappers over core RPC methods+ ├─ transport/ - ConnectionProfile transports (LanHttp, Tunnel, CloudHttp) for iOS/remote+ └─ services/api/* - domain API modules (~50 files, see below)+```++### API Client (`services/apiClient.ts`)++Fetch-based HTTP REST client for backend communication with typed request/response handling and error handling. The backend URL is resolved at runtime (`services/backendUrl`), not baked in.++```typescript+import apiClient from "../services/apiClient";++const user = await apiClient.get<User>("/users/me");+const result = await apiClient.post<LoginResponse>("/auth/login", {+ email,+ password,+});+```++### Domain API modules (`services/api/`)++\~55 domain-scoped modules, one per feature surface, each wrapping either backend REST endpoints or core RPC methods. Representative examples:++* `authApi` / `userApi`: auth + user profile+* `threadApi`, `threadUsageApi`: chat threads+* `agentTeamApi`, `agentWorkApi`, `subagentApi`: agents+* `skillsApi`, `skillRegistryApi`, `flowsApi`, `workflowRunsApi`: skills & automation+* `channelConnectionsApi`, `mcpClientsApi`, `mcpSetupApi`, `tunnelsApi`: connections+* `memoryApi`: Memory v2 RPC wrappers (`openhuman.memory_*`)+* `billingApi`, `creditsApi`, `referralApi`, `inviteApi`: commerce+* `voiceSettingsApi`, `aiSettingsApi`, `modelCouncilApi`: AI/voice config++For the full list, `ls app/src/services/api/`. New feature surfaces get their own module here rather than growing `apiClient`.++### Socket Service (`services/socketService.ts`)++Socket.io client singleton connected to the **local core's** socket endpoint (base URL derived from the resolved RPC URL via `coreSocket.ts`; authenticated with the core RPC token). It ingests realtime core events (connection status, channel updates) and dispatches them into Redux (`socketSlice`, `connectivitySlice`, `channelConnectionsSlice`). It also hosts the MCP-style transport (`SocketIOMCPTransportImpl` from `lib/mcp`).++Keep `socketService` and the core socket behavior aligned (the "dual socket sync" rule in AGENTS.md). Connection lifecycle is owned by `providers/SocketProvider.tsx`; on mobile the provider is not mounted at all: events arrive through the `TunnelTransport` relay instead.++### Core RPC (`services/coreRpcClient.ts`)++The Rust core runs **in-process** inside the Tauri host (no sidecar). The UI calls JSON-RPC methods on it over local HTTP:++```typescript+import { callCoreRpc } from "../services/coreRpcClient";++const result = await callCoreRpc<MyType>({+ method: "openhuman.some_method",+ params: {+ /* … */+ },+ timeoutMs: 60_000, // optional per-call override (default 30s)+ suppressAuthExpiredEvent: false, // narrow reads can opt out of global sign-out on 401+});+```++How a call flows:++1. **URL + token resolution**: the RPC URL follows the precedence in [Runtime config precedence](frontend.md#runtime-config-precedence); the per-launch bearer token comes from the Tauri `core_rpc_token` command (or the stored token for self-hosted cores).+2. **Direct fetch**: the webview `fetch()`es the JSON-RPC envelope straight to the core (loopback http or any https URL).+3. **Shell relay fallback**: plain `http://` to a **non-loopback** host is active mixed content and Chromium blocks it (#3865). `rpcUrlNeedsShellRelay()` detects this and routes the call through `invoke('relay_http_rpc', { url, token, body })`, implemented in **`crates/openhuman-app/src/core_rpc.rs`** (a thin wrapper over `openhuman_rpc::post_json_rpc` from `crates/openhuman-rpc/`), which returns `{ status, body }` re-wrapped as a `Response`.+4. **Transport override**: iOS/remote connection profiles install a `CoreTransport` (`setActiveCoreTransport`) so the same `callCoreRpc` surface rides LAN/tunnel/cloud transports.++Errors are classified into a stable `CoreRpcError.kind` (`auth_expired`, `transport`, `timeout`, `rate_limited`, …): callers branch on `kind`, never on message regexes. An `auth_expired` classification broadcasts `core-rpc-auth-expired`, which `CoreStateProvider` turns into a session clear.++### Best Practices++1. Use singletons. Never create multiple service instances.+2. Keep Tauri IPC and RPC calls in services. Do not scatter `invoke()` or raw fetches through components.+3. Clean up on unmount by disconnecting in the `useEffect` cleanup.+4. Handle errors through `CoreRpcError.kind` and retry only transient failures.++***++## Providers++React context providers (`app/src/providers/`) manage service lifecycle and expose core-owned state. The full nesting (including gates that live in `components/`) is the generated [provider chain](frontend.md#provider-chain) above. There is **no** `UserProvider`, `AIProvider`, or `SkillProvider`: auth/user state lives in `CoreStateProvider`, AI configuration lives in the Rust core, and skills execute in the core (the frontend QuickJS skills engine was removed).++### ThemeProvider (`providers/ThemeProvider.tsx`)++Applies theme tokens and dark-mode handling from the persisted `theme` slice (mode, font size, custom themes).++### CoreStateProvider (`providers/CoreStateProvider.tsx`)++The authoritative auth/session/onboarding context. Fetches the core app snapshot (`fetchCoreAppSnapshot()` RPC), exposes it via `useCoreState()` (`{ snapshot, isBootstrapping, refresh }`), and clears the session on the global `core-rpc-auth-expired` event. It follows a **turn-boundary refetch contract**: after every agent reply completes (`chat_done` in `ChatRuntimeProvider`) it refetches the user state (debounced 750ms) and merges it into the snapshot via `patchSnapshot`: see `providers/README.md`.++### SocketProvider (`providers/SocketProvider.tsx`)++Owns the socket.io connection to the local core: connects once core state is ready, updates the `socket` slice, and tears down on unmount. Desktop only: `App.tsx` skips it on mobile, where events arrive through the `TunnelTransport` relay.++### ChatRuntimeProvider (`providers/ChatRuntimeProvider.tsx`)++Subscribes to chat runtime socket events (message streaming, tool calls, subagent lifecycle, approval requests) and reduces them into the `chatRuntime` slice: per-thread tool timelines, streaming buffers, artifacts, and approval state consumed by the chat surface and the mascot.++### Gates and shell-level contexts (in `components/`)++* `BootCheckGate` (`components/BootCheckGate/`) blocks render until the core boot snapshot resolves.+* `CommandProvider` (`components/commands/`) holds the command palette context.+* `ServiceBlockingGate` (`components/daemon/`) blocks the shell until required services are configured.++### Context vs Redux++| Use Context For | Use Redux For |+| ---------------------------------- | ---------------------------------- |+| Service instances (socket, client) | Serializable state (status, data) |+| Methods (emit, on, off) | Persisted state (sessions, tokens) |+| Derived values | Complex state logic |++Example: `SocketProvider` owns the socket instance; Redux stores connection status in `socketSlice`.++***++## Human Mascot Surface++The mascot appears on **two** surfaces, deliberately. `/human` (`app/src/features/human/HumanPage.tsx`) is the dedicated full-bleed stage with a right-rail chat. `/chat` carries the same mascot docked on its composer, where it expands into a voice stage in place. Both read one set of mascot preferences from `mascotSlice` (colour, voice, speak-replies, dismissal) so the two can never disagree about the same setting.++`app/src/features/human/chatMascot/` owns the chat-side surface:++| Module | Role |+| ----------------------- | --------------------------------------------------------------------------------------------------------- |+| `ChatMascotContext.tsx` | Shared dock/stage refs and the send binding. Every value is stable: see the re-render note below. |+| `ChatMascotDock.tsx` | The small mascot standing on the composer's input box. An anchor + hit area; it draws nothing. |+| `ChatMascotStage.tsx` | The scaled-up voice surface: `MicComposer`, input-device selector, speak-replies switch, collapse button. |+| `ChatMascotOverlay.tsx` | The single Rive instance, moved between dock and stage with a `transform`. |+| `geometry.ts` | Pure dock ⇄ stage transform maths (`inscribedSquare`, `lerpBox`, `boxTransform`). |++Clicking the dock expands the mascot into a right-hand stage column while the transcript and the text composer stay live in the left column, so voice and text are the same conversation. `pages/Accounts.tsx` animates the column width; `ChatMascotOverlay` re-measures both anchors per frame so the mascot stays glued to a destination that is still moving. Expanded/collapsed and the speak-replies preference are persisted in `mascotSlice`.++**Two invariants worth keeping.** The mascot re-renders at \~60fps during TTS lipsync, so (a) it is rendered as a leaf with nothing beneath it, and (b) the mascot context value is deliberately non-reactive: reactive state lives in Redux or in the send-binding external store instead. A reactive context value would reconcile the whole chat tree every frame, which is the stall #5357 had to fix. And the overlay only mounts while the agent account is selected, so a fixed overlay is never left alive as an invisible canvas still burning frames under another account.++The mascot face comes from `useHumanMascot`, which subscribes to chat lifecycle events for thinking, speaking, acknowledgement, and error states, plus a `listening` pose driven by `MicComposer`'s `onRecordingChange`.++Sub-agent delegation is visualized by `SubMascotLayer`. It does not introduce a new socket protocol. Instead, it reads the selected or active thread's `chatRuntime.toolTimelineByThread` entries that `ChatRuntimeProvider` already builds from `subagent_spawned`, `subagent_completed`, `subagent_failed`, `subagent_iteration_start`, `subagent_tool_call`, and `subagent_tool_result`.++Lifecycle mapping:++| Runtime timeline state | Sub-mascot state |+| ---------------------- | -------------------------------------------------------------------- |+| `running` | Small colored mascot in a thinking face with a short activity bubble |+| `success` | Same mascot resolves to a happy face and completion bubble |+| `error` | Same mascot resolves to a concerned face and failure bubble |++Activity bubble text is intentionally compact: current child tool call, child iteration, the delegation prompt excerpt, or final status. The thread timeline remains the authoritative detailed view; sub-mascots are only the glanceable orchestration layer around the main mascot.++### Tool-call presentation++Every surface that names a tool call (chat cards, the processing panel, the status line, the mascot) resolves it through one registry, `app/src/features/conversations/tools/toolPresentation.ts` (`describeToolCall`). It returns the icon, a translated phrase in two tenses ("Reading file" while running, "Read file" once settled), the target chip, and which rich body the call expands into. The data lives in `toolSpecs.ts` (exact names, collapsed tools that switch on an argument, prefix families, named agents) and `toolPhrases.ts` (phrases, served as `conversations.tools.<id>.active|done`). Composio action slugs (`GMAIL_SEND_EMAIL`) resolve through the toolkit catalog in `components/composio/toolkitMeta.tsx` to "Used Gmail · Send email" with the app's logo. The server's `tool_display_label` is used only for tools the registry cannot describe.++Rendering uses assistant-ui's elements, vendored under `app/src/components/assistant-ui/elements/` (tool-call, tool-timeline, web-search, terminal-block, code-diff, web-preview) with the `tw-shimmer` utility. `ToolGroupRoot` / `ToolGroupTrigger` / `ToolGroupContent` wrap a run of calls in the tool timeline; `AssistantUiToolCallCard` renders each call. The adapters in `tools/ToolBodies.tsx` only map tool data onto those elements.++The core's `tool_result` socket event carries `args`, `elapsed_ms`, the recomputed `tool_display_label` / `tool_display_detail`, and `structured` (the tool's `ToolResult.metadata`; web searches send `{ kind: "web_search", query, provider, results: [...] }`). `parseWebSearchResult.ts` prefers that payload and falls back to parsing the text rendering for older turns.++`tools/__fixtures__/coreToolNames.json` lists every tool the core registers. The Rust test `tools/ops_tests_catalog_fixture_tests.rs` keeps it in sync (`UPDATE_TOOL_CATALOG=1` regenerates it) and `toolPresentation.catalog.test.ts` fails if any listed tool falls through to the generic fallback, so a new core tool cannot reach the chat unlabelled. `/dev/tools` (dev builds only) renders every state and the whole catalog.++***++## Pages & Routing++The application uses HashRouter with protected and public route guards. Desktop routes live in **`app/src/AppRoutes.tsx`**; on mobile (iOS/Android) `AppRoutesIOS.tsx` renders a reduced Human/Chat/Settings set instead.++### Route map++`app/src/AppRoutes.tsx` is the authoritative table and is heavily commented with the rationale for each entry. The desktop routes it declares:++| Route | Renders | Guard |+| -------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------- |+| `/` | `Welcome` | `PublicRoute` (signed in: forwards to `/home`) |+| `/auth` | `WebCallbackPage`, the auth callback | none |+| `/callback/:kind`, `/callback/:kind/:status` | `WebCallbackPage`, generic OAuth and provider callbacks | none |+| `/onboarding/*` | `Onboarding` stepper | `ProtectedRoute` |+| `/human` | `HumanPage`, the dedicated mascot stage | `ProtectedRoute` |+| `/chat/:threadId?` | `Accounts`, the unified chat (agent plus connected web apps) | `ProtectedRoute` |+| `/flows` | `FlowsPage` | `ProtectedRoute` |+| `/flows/draft` | `FlowCanvasDraftPage`, an unsaved proposed graph passed in `location.state` | `ProtectedRoute` |+| `/flows/:id` | `FlowCanvasPage` | `ProtectedRoute` |+| `/workflows` | `Activity`, the legacy `SKILL.md` workflow hub | `ProtectedRoute` |+| `/workflows/run` | `WorkflowsRun`, the single-purpose Skill runner | `ProtectedRoute` |+| `/connections` | `Skills`, the connections hub | `ProtectedRoute` |+| `/invites` | `Invites` | `ProtectedRoute` |+| `/notifications` | `Notifications` | `ProtectedRoute` |+| `/settings/*` | `Settings` | `ProtectedRoute` |+| `/ptt-overlay` | `PttOverlayPage`, the push-to-talk overlay window | none |+| `/dev/agent-insights` | `AgentInsightsPreview` | dev only |+| `/dev/ui` | `UiGallery`, every shared UI primitive in the active theme | dev only |+| `/dev/tools` | `ToolCallGallery`, every tool-call state and the whole core catalog | dev only |+| `/dev/assistant-ui` | The upstream assistant-ui demo on a mock runtime | dev only |+| `*` | `DefaultRedirect` | none |++The four `/dev/*` routes are registered inside an `IS_DEV` branch (`utils/config`), so `import.meta.env.DEV` is substituted at build time, the branch folds away, and their component trees leave a production bundle entirely. They are previews, never part of the shipped product.++Memory is a surface of `/connections`, not a route of its own: `?tab=brain&brain=<chip>` selects one of its eight chips, `engine`, `ask`, `explorer`, `learnings`, `conversations`, `brain`, `background` and `settings`. The list is `app/src/components/memory/memoryChips.ts` and the page is `app/src/pages/Memory.tsx`. `memoryChips.ts` also remaps the retired names (`graph`, `goals` and `context` to `ask`; `documents`, `sources`, `sync` and `history` to `brain`), and `/settings/memory-engine` redirects to the `engine` chip.++Back-compat redirects, all `Navigate replace`. The `ForwardSearch` ones copy the query string to the destination so old deep links still land on the right sub-tab:++| From | To |+| --------------- | ------------------------------------------------------------------------------ |+| `/home` | `/chat` |+| `/accounts` | `/chat` |+| `/brain` | `/connections?tab=brain` (`BrainRedirect` remaps the old `?tab=` to `?brain=`) |+| `/skills` | `/connections` (`ForwardSearch`) |+| `/channels` | `/connections?tab=messaging` |+| `/activity` | `/settings/account` |+| `/intelligence` | `/settings/account` |+| `/feedback` | `/settings/feedback` |+| `/routines` | `/flows` |+| `/webhooks` | `/settings/integrations` (`ForwardSearch`) |++There is **no** `/login` route: authentication flows through the Welcome page, the `/auth` callback, and deep links. `/agents` does not exist either, and Settings is an ordinary route rather than an overlay (see [Settings](frontend.md#settings)).++### Route guards++All three guards read `useCoreState()` (not Redux auth state) and render `RouteLoadingScreen` while bootstrapping:++* **`ProtectedRoute`** (`components/ProtectedRoute.tsx`, `({ children, requireAuth = true, redirectTo })`): without a session token, navigates to `redirectTo || '/'`. Onboarding gating is _not_ done here; an effect in `AppShellDesktop` (App.tsx) forces non-onboarding routes back to `/onboarding` while `onboarding_completed` is false, and bounces off it once complete.+* **`PublicRoute`** (`components/PublicRoute.tsx`): redirects signed-in users to `/home` (which forwards to `/chat`).+* **`DefaultRedirect`** (`components/DefaultRedirect.tsx`): signed out → `/`; signed in but onboarding incomplete → `/onboarding`; otherwise → `/chat`. Waits for `snapshot.currentUser` to avoid the post-login race.++### Onboarding Flow (`pages/onboarding/`)++A routed stepper (`Onboarding.tsx` mounts nested routes inside `OnboardingLayout`):++```+/onboarding/welcome → WelcomePage+/onboarding/runtime-choice → RuntimeChoicePage+ ├── cloud → /chat+ └── custom → /onboarding/custom/inference → voice → oauth → search+ → embeddings → (activity) → vault → /chat+```++Each custom step offers **Default** (let OpenHuman manage it) vs **Configure** (inline controls, or a deep-link callout to Settings for domains not yet embedded). Pages live in `pages/onboarding/pages/`; the legacy Composio/skills/context-gathering steps (`pages/onboarding/steps/`) are retired from the default flow but remain on disk. Completion is tracked by the core's `onboarding_completed` flag, enforced by the AppShell onboarding gate. After onboarding, `AppWalkthrough` (Joyride) runs the post-onboarding tour.++### Settings++Settings is a routed `/settings/*` page like every other surface, on desktop and on iOS alike. It was a desktop modal overlay that kept the page behind it rendered; that system is gone, and so are the older `SettingsPanelLayout` / `useSettingsAnimation` / `ProfilePanel` modals and the registry-derived settings search field (see [Removed](frontend.md#removed) below).++* **`components/settings/settingsRouteRegistry.ts`**: single declarative source of truth for every settings destination (id and route slug, i18n keys, section, sidebar `navGroup`, `devOnly`, `searchKeywords`). Navigation menus and breadcrumbs derive from it.+* **`components/settings/settingsRouteElements.tsx`**: maps registry entries to panel `<Route>` elements, including the redirects (`/settings/memory-engine` to the Memory `engine` chip).+* **`components/settings/layout/`**: the two-pane chrome. `SettingsLayout` projects the settings nav into the app sidebar's dynamic region; `SettingsSidebar` groups entries by `SettingsNavGroup` (`general`, `appearance`, `agentsAutonomy`, `security`, `data`, `knowledgeMemory`, `automationIntegrations`, `diagnosticsLogs`, in `NAV_GROUP_ORDER`); `SettingsSubNav`, `SettingsIndexRedirect`, `SettingsTabbedPage` and `SettingsPanel`, the one panel template, sit beside them.+* **`components/settings/panels/`**: leaf panels such as `AccountPanel`, `AppearancePanel`, `ThemeStudioPanel`, `AgentAccessPanel`, `AutonomyPanel`, `McpServerPanel`, `PrivacyPanel` and `DeveloperOptionsPanel`. Adding a panel means adding the component and a registry entry; navigation and breadcrumbs pick it up automatically.+* **`components/settings/controls/`**: the shared form primitives every panel composes (`SettingsSwitch`, `SettingsRow`, `SettingsSection`, `SettingsSelect`, and the rest), so a boolean is a switch everywhere.++### HashRouter vs BrowserRouter++The app uses HashRouter for desktop compatibility:++```typescript+// App.tsx+import { HashRouter } from "react-router-dom";++// URLs look like: app://localhost/#/home+// Instead of: app://localhost/home+```++**Why HashRouter:**++1. Tauri deep links work with hash-based URLs+2. No server configuration needed+3. Works with file:// protocol+4. Prevents 404 on direct URL access++### Deep Link Handling++Deep links are handled before routing:++```typescript+// main.tsx+import("./utils/desktopDeepLinkListener").then((m) => {+ m.setupDesktopDeepLinkListener().catch(console.error);+});+```++The listener intercepts `openhuman://` URLs (e.g. auth handoff), exchanges tokens through the Rust side (bypassing CORS), stores the session, and navigates to the right route. See `utils/desktopDeepLinkListener.ts`.++***++## Components++Shared UI lives in `app/src/components/`; feature-specific UI lives in `app/src/features/<vertical>/`. Highlights:++```+components/+├── ProtectedRoute / PublicRoute / DefaultRedirect # Route guards+├── layout/shell/ # RootShellLayout, AppSidebar, SidebarSlot (two-pane app chrome)+├── settings/ # Settings registry, layout, panels, controls (see above)+├── accounts/ # Connected-app provider icons (the live WebviewHost overlay was removed with the CEF provider webviews)+├── BootCheckGate/, daemon/ # Boot + service gates in the provider chain+├── commands/ # CommandProvider (command palette)+├── Announcement/, upsell/, notices/, walkthrough/ # Shell-level overlays+├── keyring/, InitProgressScreen/ # Consent + init overlays+├── memory/ # Memory v2 tabs (Engine, Ask, Explorer, Learnings, Conversations, Brain, Background, Settings) and import banner+└── intelligence/ # Shared intelligence UI (WorkflowsTab, Toast, ConfirmationModal)+```++Conventions:++* Modals render through a portal, above routed content. Settings is not one of them any more: it is a route.+* Modals are controlled: parents own `isOpen` state and pass `onClose`.+* All user-facing text goes through `useT()` (`lib/i18n/I18nContext`); CI enforces locale parity.+* Production `app/src` code uses only static `import` / `import type`, never dynamic imports.++***++## Hooks & Utilities++### Custom Hooks (`hooks/`)++`app/src/hooks/` holds the app-level hooks (the [Scale](frontend.md#scale) table names the command that counts them). Representative examples:++* `useUser` is a thin wrapper over `useCoreState()`; it returns `{ user: snapshot.currentUser, isLoading, error, refetch }`. There is no standalone user store.+* `useBackendUrl` resolves the backend URL at runtime (see [Runtime config precedence](frontend.md#runtime-config-precedence)).+* `useThreadQueries` fetches chat threads.+* `useDaemonHealth` / `useDaemonLifecycle` track core service health.+* `useDictationHotkey` / `usePttHotkey` manage global hotkeys.+* `useDeveloperMode`, `useMediaQuery`, `useEscapeKey` are general UI utilities.+* Feature hooks: `useFlowRunProgress`, `useWorkflowBuilderChat`, `useConsciousItems`, `useIntelligenceStats`, `useCostDashboard`, ….++Feature-local hooks live next to their feature under `features/*/`.++### Utilities++#### Configuration (`utils/config.ts`)++Centralized build-time environment variable access: **never read `import.meta.env` directly elsewhere**. These constants only carry the value baked into the bundle; for the **runtime** URL the app actually talks to, see `services/backendUrl` and `hooks/useBackendUrl`.++```typescript+// Build-time fallback only (used outside Tauri).+export const BACKEND_URL = /* VITE_BACKEND_URL || default */;+// Core RPC build-time fallback.+export const CORE_RPC_URL = /* VITE_OPENHUMAN_CORE_RPC_URL || 'http://127.0.0.1:7788/rpc' */;+// Dev flags, e.g.+export const DEV_FORCE_ONBOARDING = /* dev-only VITE_DEV_FORCE_ONBOARDING */;+```++> **Do not** import `BACKEND_URL` directly to make API calls. Resolve the URL at runtime so the core's `api_url` (via `openhuman.config_resolve_api_url`) takes effect:+>+> ```typescript+> // React components+> import { useBackendUrl } from "../hooks/useBackendUrl";+> const backendUrl = useBackendUrl();+>+> // Non-React code+> import { getBackendUrl } from "../services/backendUrl";+> const backendUrl = await getBackendUrl();+> ```++#### Desktop Deep Link Listener (`utils/desktopDeepLinkListener.ts`)++Handles incoming `openhuman://` deep links via the Tauri deep-link plugin: parses the URL, performs the Rust-side token exchange (bypasses CORS), stores the session, and navigates. Set up lazily from `main.tsx` so the Tauri IPC bridge is ready first.++#### URL Opener (`utils/openUrl.ts`)++Cross-platform URL opening: tries the Tauri opener plugin, falls back to `window.open`. Always use this instead of raw `window.open` so links open in the system browser.++#### Tauri command wrappers (`utils/tauriCommands/`)++Typed wrappers around `invoke(...)`, including the bridge-gap-aware `isTauri()` guard (checks `__TAURI_INTERNALS__.invoke` is actually wired, not merely that the app runs under Tauri). Use it; never check `window.__TAURI__` directly.++### Polyfills (`polyfills.ts`)++Node.js globals (`Buffer`, `process`, `util`) are polyfilled for the browser. Several browser-side modules use Node APIs, including voice/PTT audio encoding (`features/voice/pttAudio.ts`, `wavEncoder.ts`), mascot Rive asset caching (`features/human/Mascot/`), and tool-timeline formatting.++Two layers provide them:++1. **`vite-plugin-node-polyfills`** in `app/vite.config.ts` (`buffer`, `process`, `util`, `os`, `crypto`, `stream`, plus `Buffer`/`process`/`global` globals).+2. **`polyfills.ts`**, imported **first** in `main.tsx`, which synchronously assigns `Buffer`/`process`/`util` onto `globalThis`/`window`/`global`/`self` before any dependent module executes.++### Best Practices++#### Hook dependencies & cleanup++```typescript+useEffect(() => {+ on("event", handler);+ return () => off("event", handler);+}, [on, off, handler]);+```++Always include dependencies and always clean up subscriptions.++#### Error handling++Wrap Tauri/utility calls in try-catch with a fallback:++```typescript+try {+ await openUrl(url);+} catch (error) {+ console.error("Failed to open URL:", error);+}+```++#### Type safety++Use TypeScript generics for API and RPC calls:++```typescript+const user = await apiClient.get<User>("/users/me");+const result = await callCoreRpc<Snapshot>({+ method: "openhuman.app_state_snapshot",+});+```++## Removed++Stated rather than deleted, because each of these still turns up in older code and in older notes:++| Removed | Replaced by |+| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |+| `SettingsModal`, `SettingsModalFrame`, `SettingsModalLayout`, `settingsOverlay.ts` | `/settings/*` as an ordinary route rendered by `Settings` |+| `SettingsPanelLayout`, `useSettingsAnimation`, `ProfilePanel` | The `settingsRouteRegistry` plus `components/settings/layout/` |+| `components/settings/search/` and `settingsSearchRegistry` | Nothing: the sidebar search field was removed. `searchKeywords` stays on the registry entries. |+| `WebviewHost` overlay in `components/accounts/` | Nothing: it went with the CEF provider webviews |+| The frontend QuickJS skills engine | Skill execution in the Rust core |+| `UserProvider`, `AIProvider`, `SkillProvider` | `CoreStateProvider` for auth and user state; AI configuration and skills in the core |+| `/conversations`, `/accounts` as standalone pages | `/chat/:threadId?` (`Accounts`), the unified chat surface |++## See also++* [Architecture overview](architecture.md): the Rust side this UI presents.+* [Tauri Shell](tauri-shell.md): the host that serves this bundle and owns the IPC surface.+* [Agent Harness](agent-harness.md): what the chat surface's tool timeline is rendering.+* [Memory](../../features/memory.md): the user-facing shape of the `/connections?tab=brain` chips.+* [Theming](../theming.md): the token layer behind `ThemeProvider` and Theme Studio.+* [iOS Companion](../../features/ios-companion.md): the experimental mobile client the `AppRoutesIOS` shell and the `transport/` profiles belong to.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/mcp-registry.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/mcp-registry.mdnew file mode 100644index 0000000000..3234638098--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/mcp-registry.md@@ -0,0 +1,112 @@+---+description: >-+ The host half of the dynamic, user-facing side of MCP-client support: browse+ servers on Smithery and the official MCP registry, declare the user's servers+ in one mcp.json document, connect them (persi+icon: plug+---++# MCP Registry++`crates/openhuman-core/src/mcp/registry/` is the **host half** of the dynamic, user-facing side of OpenHuman's Model Context Protocol client support: browsing the supported upstream registries (Smithery and the official modelcontextprotocol registry), reconciling the install store against the user's `mcp.json` document, persisting that, and (for servers launched as local subprocesses or HTTP-remote endpoints) supervising the connection lifecycle. Installed servers' tools are surfaced to agents via the unified tool registry (`crate::tools::registry`).++The registries are **browse-only**. There is no install-from-catalog path and no setup agent: a user who finds a server in the Registry tab opens its own page, reads the install instructions there, and declares the server in the mcp.json tab (`{ "mcpServers": { name: { command, args, env } | { url, headers } } }`). The document's contract and its reconciliation live in `tinymcp::registry::config_doc`; `config_ops.rs` here is the RPC envelope over them (`mcp_clients_config_get` / `mcp_clients_config_set`).++The **client half**, meaning both transports, the Smithery/official catalogs, the SQLite store, the live connection map, the subprocess supervisor, browser sign-in, and the write-audit log, moved to the vendored `tinymcp` crate (`vendor/tinymcp`). What lives in this directory is only what belongs to this application:++* `host.rs` (one level up, `crates/openhuman-core/src/mcp/host.rs`): the one `tinymcp` service this process holds per workspace, and config-to-`tinymcp` conversion.+* `registry/`: the `mcp_clients` RPC surface, the agent-facing tools, and the prompt-injection scan applied to remote tool definitions.+* `audit/` (sibling of `registry/`): the RPC surface over `tinymcp`'s write-audit log.+* `server/` (sibling of `registry/`): the `openhuman-core mcp` stdio/HTTP server that exposes this application's own tools to external MCP hosts (see [MCP Server](../mcp-server.md)). This is the _server_ side and did not move.++> **Naming note**: the Rust module path is `crate::mcp::registry` (`crates/openhuman-core/src/mcp/registry/`), but the RPC namespace and on-disk SQLite filename stay `mcp_clients` for backward compatibility with existing frontend code and stored user state. Grep both names when chasing call sites.++All payload types (`InstalledServer`, `McpTool`, `ConnStatus`, the Smithery/official-registry DTOs) come from `tinymcp_bus` and are re-exported under `registry::types`, not redefined here. Types for the _static, config-declared_ server set (`[[mcp_client.servers]]` in `config.toml`) and the shared HTTP/stdio transport primitives are re-exported from `crate::mcp::config_servers` and `crate::mcp::http_client` (thin `pub use tinymcp::...` modules in `mcp/mod.rs`, not directories).++```+ ┌────────────────────────────────────────────────┐+ Registries ───► tinymcp (catalogs, store, supervisor) │+ └────────────────────┬───────────────────────────┘+ │ browse / declare+ ▼+ ┌──────────────────────┐+ Frontend (Skills UI) ─►│ ops.rs / schemas.rs │ RPC controllers (mcp_clients_*)+ └──────────┬───────────┘+ │ delegates to+ ▼+ ┌──────────────────────┐+ │ host::for_config │ the tinymcp service this+ │ / host::try_service │ workspace's host holds+ └──────────┬───────────┘+ │ tools_safe_for_agent (prompt-injection scan)+ ▼+ tool_registry (agents)++ supervisor_events.rs ── reconnect-supervisor ticks → DomainEvent+```++## Server transport model++An `InstalledServer` (from `tinymcp_bus`, re-exported as `registry::types::InstalledServer`) carries a `Transport` discriminator with stdio and HTTP-remote variants: a local subprocess (`npx`, `uvx`, or a direct binary) speaking stdio JSON-RPC, or a hosted server (the majority of what Smithery lists) dialled over streamable HTTP. A declaration in `mcp.json` becomes such a row directly (`tinymcp::registry::config_doc`): `command`/`args` → stdio, `url` → HTTP-remote, `env`/`headers` → the credential table. `tinymcp` dials whatever the row says; this domain only decides what the row says.++## Boot-time spawn and the reconnect supervisor++Installed servers are connected as the core comes up, and `mcp::registry::supervisor` (see `crates/openhuman-core/src/mcp/registry/mod.rs`) runs `tinymcp::Supervisor::tick` on an interval against every open workspace host, turning each tick's report into `supervisor_events::publish` calls. Errors never block boot; a broken MCP install should not gate the desktop app starting. Non-nominal ticks (stays-down, restored, parked) become `DomainEvent`s that reach the Event Log and the desktop notification bridge (#5931).++## Layout++| Path | Role |+| ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `mod.rs` | Module docs, `types`/`connections` re-export shims over `tinymcp_bus`/`super::host`, the reconnect-supervisor loop, the OAuth-callback completion helper, and `tools_safe_for_agent` (the prompt-injection scan applied to every remote tool definition). |+| `host.rs` (parent `mcp/`) | One `tinymcp` service per workspace, opened on first use; proxy resolution for MCP traffic (`proxy_for_mcp`). |+| `helpers.rs` | Shared RPC-handler plumbing: `Outcome` encoding, identifier guards, workspace-service resolution, credential-name injection. |+| `ops.rs` | `mcp_clients_*` RPC handler implementations (uninstall, list, browse, connect/disconnect, tool call, `update_env`, registry settings). One-to-one with `schemas.rs` handlers; publishes `DomainEvent`s `tinymcp` does not. |+| `config_ops.rs` | `mcp_clients_config_get` / `config_set`: the `Outcome` envelope, domain events and background connects over `tinymcp`'s `McpRegistry::render_config_doc` / `apply_config_doc`. The `mcp.json` shape, its refusals and the reconciliation (add, rewrite in place under the same `server_id`, or uninstall, merging write-only credentials) live in `tinymcp::registry::config_doc`. |+| `action_tool.rs` | One deferred agent tool per action on a connected server, built from `tinymcp_bus::agent_tools::action_tool_specs` with `tools_safe_for_agent` as the admission filter; execution goes through `InstalledServerInvoker::invoke`, which re-checks the live safe-tool list and then calls `service.dynamic().invoke(...)` on the `tinymcp` service, rather than back through `ops.rs`. |+| `schemas/` (`mod.rs`, `registry.rs`, `handlers.rs`, `params.rs`) | Controller schemas + handler dispatch. Re-exported from `mod.rs` as `all_mcp_registry_controller_schemas` / `all_mcp_registry_registered_controllers`. |+| `bus.rs` | `DomainEvent` subscriber (`McpClientEventSubscriber`) that logs `McpServer*` / `McpClientToolExecuted` lifecycle events. |+| `supervisor_events.rs` | Turns a `tinymcp::Supervisor` tick report into this domain's `DomainEvent`s, stamped with the workspace whose host was ticked. |+| `tools.rs` | Agent-facing `mcp_registry_*` tools (search catalog, inspect/list/connect/disconnect/call), thin shims over `ops.rs`. The one mutator (`mcp_registry_uninstall`) ships default-OFF behind the `mcp_manage` toggle; there is no install tool. Distinct from the generic `mcp_list_servers`/`mcp_call_tool` bridge tools. |+| `stub.rs` | The disabled facade compiled when the `mcp` feature is off. |++## Public surface++The exports from `mod.rs` are intentionally narrow:++```rust+pub use schemas::{+ all_controller_schemas as all_mcp_registry_controller_schemas,+ all_registered_controllers as all_mcp_registry_registered_controllers,+ schemas as mcp_registry_schemas,+};++pub use types::{ConnStatus, InstalledServer, McpTool};+```++`types` and `connections` are thin `pub mod`s re-exporting the `tinymcp_bus` wire vocabulary and `super::host`-backed lookups, respectively. This domain does not define its own copies. Everything else (`bus`, `ops`, `action_tool`, `supervisor_events`, `tools`) is `pub mod` for in-crate callers but not re-exported from `mod.rs`.++## Calls into++* `crate::mcp::host`: resolves the `tinymcp` service for a workspace (`host::for_config`, `host::try_service`, `host::all_hosts`).+* `tinymcp` / `tinymcp_bus`: the catalogs, store, connection map, supervisor, OAuth flow, and wire types.+* `crate::security::prompt_injection::scan_tool_definition`: the scan `tools_safe_for_agent` applies before a remote tool reaches the model.+* `crate::tools::registry`: installed servers' tools land here so agents see them alongside native tools.+* `crate::core::bus::BUS`: publishes `DomainEvent`s (`McpToolRejected`, lifecycle events, supervisor observations).++## Called by++* Core startup, via `mcp::host::init` and the reconnect-supervisor loop.+* Frontend Connections UI: the **MCP Servers** page (`McpServersTab`) is three tabs over the `openhuman.mcp_clients_*` RPC namespace: **Servers** (rows, status, the credential form: connect/disconnect, `update_env`, sign-in), **mcp.json** (`config_get` / `config_set`, the only way a server is added or removed) and **Registry** (`registry_search`, browse-only; a row opens the server's own page in the browser). `registry_settings_get` / `registry_settings_set` hold the Smithery / official-registry credentials (secret values are write-only). Agents use connected servers directly: the orchestrator finds a connected server's tool through `tool_search`, or loads the `mcp` skill (`use_skill`, guide in `crates/openhuman-core/src/tools/toolpacks/guides/mcp.md`) for the `mcp_registry_*` status / list-tools / tool-call fallback; they do not install them.++## Tests++Focused `*_tests.rs` siblings cover each file: `bus_tests.rs`, `ops_tests.rs`, `schemas_tests.rs`, `action_tool_tests.rs`, `supervisor_events_tests.rs`, `tools_tests.rs`.++## Related++* [`mcp/registry/mod.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/mcp/registry/mod.rs) and [`mcp/mod.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/mcp/mod.rs): the authoritative rustdoc this page mirrors.+* `crate::mcp::config_servers` / `crate::mcp::http_client` (`mcp/mod.rs`): re-export modules for the static config-declared server set and the shared transport primitives, both implemented in `tinymcp`.+* `crates/openhuman-core/src/mcp/audit/`: the RPC surface over `tinymcp`'s write-audit log.+* [MCP Server](../mcp-server.md): the `openhuman-core mcp` stdio/HTTP server side, which did not move to `tinymcp`.+* [Agent Harness](agent-harness.md): how the agent ends up calling MCP tools through `tool_registry`.+* [Architecture overview](architecture.md): where this fits in the wider system.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/memory.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/memory.mdnew file mode 100644index 0000000000..b54a733f20--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/memory.md@@ -0,0 +1,79 @@+---+description: >-+ The memory host layer in crates/openhuman-core/src/memory/: TinyMemory's+ agent lifecycle bound to OpenHuman's turns, RPC and UI.+icon: diagram-project+---++# Memory++`crates/openhuman-core/src/memory/` is the host layer over TinyMemory: it drives+the agent memory lifecycle around every turn, with a memory pack recalled before+the model runs, the turn logged on both sides, memory recalled into compaction+checkpoints, and belief builds run in the background.++The behaviour is specified in `docs/specs/memory-v2.md`; the user-facing feature+is [Memory](../../features/memory.md).++## TinyMemory crates (`vendor/tinymemory/crates/`)++| Crate | Owns |+| --- | --- |+| `tinymemory-api` | The engine contract: `MemoryEngine` (recall, fetch, store, forget, list, consolidate, beliefs), `StoreItem`, `MemoryMeta`, `MetaFilter`, `Namespace`/`Reach`, `EngineDescriptor`, `Error`. No I/O. Its `conformance` feature adds the suite every engine passes and the in-memory `ReferenceEngine` the unit tests use. |+| `tinymemory-tools` | The agent surface over any engine: `AgentMemory` (`start_session`, `pre_turn`, `post_turn`, `recall_for_compaction`, `recall`), `MemoryLayout`, `Brain`, holistic recall (`ContextPack`), `BackgroundJob`/`BackgroundRunner`. |+| `tinymemory-integrations` | Everything that touches the outside world: the CortexDB engine on both wires (`cortexdb` direct, `tinyhumans` behind the backend), the registry, document conversion and the brain filer, source readers (SSRF-guarded), secret/PII scrubbing, the v1 importer. |++## Host modules++| Module | Role |+| --- | --- |+| `engine` | Binds `[memory] engine`: `tinyhumans` over the host's backend credential (resolved per request) with the transport's attribution headers, or `cortexdb` with the key stored as `memory-cortexdb`. Off when neither is usable. |+| `guard` | `ScrubbingEngine`: every write is scrubbed under the host policy, whichever path makes it. |+| `scope` | `MemoryIdentity` scoped around every turn, resolved to a layout root and a memory agent id (host binding, definition pin, team, default). |+| `lifecycle::hooks` | `pre_turn`, `post_turn`, `compaction`: bounded, never fail a turn. |+| `lifecycle::jobs` | The persisted background queue and the `memory_background` cron job. |+| `lifecycle::views` | Policy, pack preview, agents list, job views for the RPCs. |+| `brain` | Brain source mapping for synced items and the `memory_brain_*` ops. |+| `sources` | The `[[memory.sources]]` registry and sync into the brain. |+| `channels` | Which channel each logged thread arrived on, for forgetting a channel. |+| `backfill` | Consent-gated storing of past chats in the lifecycle's shape. |+| `import` | Consent-gated, resumable v1 import. |+| `tools` | The single `memory` agent tool (`recall`, `fetch`, `learn`, `forget`), confined to the identity's layout. |+| `ops`, `explore` | Engine selection, recall, fetch, learn, forget, listing, the explorer. |+| `bus` | The cron subscriber (`memory_sources_sync`, `memory_background`). |+| `schemas` | The `openhuman.memory_*` controllers. |+| `status`, `error`, `types` | Subsystem status, error codes, shared types. |++## Where the agent loop calls memory++| Hook | File |+| --- | --- |+| Pre-turn (log + recall), first turn after a compaction also `start_session` | `agent/session_host/runtime_session/memory_ingest.rs`, from `before_turn` in `runtime_session.rs` |+| Pack injection, ephemeral, every model request of the turn | `agent/tinyagents/middleware/memory_pack.rs` |+| Post-turn (log the reply, queue builds), after the durable commit | `memory_ingest.rs`, from `finalize_after_durable_commit` |+| Compaction recall into the checkpoint | `agent/tinyagents/memory_summarizer.rs`, wrapped around the summarizer in `harness_context_ladder.rs` |++The turn's `MemoryTurn` (config, identity, thread, pack) rides+`OpenHumanRunContext::memory_turn`; a child run has its own.++Chat thread persistence is not memory: it is `tinyagents_session::threads`,+wrapped by `crates/openhuman-core/src/threads/store`.++The MCP server exposes `memory.recall`, `memory.fetch`, `memory.list`,+`memory.learn` and `memory.forget` (`mcp/server/tools/specs.rs`).++## Tests++- Unit tests beside each module (`*_tests.rs`), against `ReferenceEngine`.+- `tests/memory_v2_e2e.rs`: every `memory_*` RPC against the mock backend, and+ a web-chat turn whose inference request carries the pack, whose turns are+ logged with `x-sdk-name`, and whose transcript holds no pack.+- `crates/openhuman-embed/tests/runtime_agents.rs`: `AgentSpec::memory`.+- `app/test/playwright/specs/memory-v2.spec.ts` (UI).++Against a real CortexDB server, `scripts/test-memory-cortexdb-live.sh` boots+the pinned harness in Docker (`vendor/tinymemory/integration/cortexdb/`) and+runs `tests/memory_cortexdb_live.rs`: learnings, a synced folder source,+web-chat turn logging, recall, the pack preview, the pack injected into a+turn's inference request, and belief builds. It skips unless+`OPENHUMAN_LIVE_CORTEXDB_URL` is set.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/security.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/security.mdnew file mode 100644index 0000000000..b3220fd07a--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/security.md@@ -0,0 +1,99 @@+---+description: >-+ Trust boundary for the autonomous core - autonomy / risk policy, the policy+ that decides when to sandbox (mechanism lives in tinybox), audit log,+ encrypted secret store, public-bind / pairing guard, a+icon: shield-halved+---++# Security++`crates/openhuman-core/src/security/` is the **trust boundary for the autonomous core**. It owns the autonomy / risk policy that decides whether a given tool call is allowed, the pluggable sandbox backends that confine those calls when the host supports it, the append-only audit log of every agent action, the encrypted secret store, the pairing guard that gates public binding of the RPC server, and the `redact()` helper every other domain uses to keep logs free of plaintext credentials.++It does **not** own:++* The cross-domain `EncryptionEngine`, which lives in `crates/openhuman-core/src/security/encryption/`.+* Per-channel credential storage, which lives in `crates/openhuman-core/src/security/credentials/`.++This module is the place to look first when asking "is this agent action allowed, and if so, how is it confined?"++## Public surface++| Item | File | Purpose |+| ----------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |+| `SecurityPolicy` | `policy/types.rs` (path checks in `policy/path_checks.rs`, command classification in `policy/command_checks.rs`, gating in `policy/enforcement.rs`) | Assembles runtime policy from `AutonomyConfig` + workspace dir. |+| `AutonomyLevel` (`ReadOnly` / `Supervised` / `Full`) | `policy/types.rs` | Three-step autonomy ladder. |+| `CommandRiskLevel`, `ToolOperation`, `ActionTracker` | `policy/types.rs` | Risk classification + per-session counting. |+| `SecretStore` | `keyring/encrypted_store.rs` (`secrets.rs` re-exports it) | OS-keychain / encrypted-file secret persistence with round-trip helpers. |+| `AuditLogger`, `AuditEventType`, `AuditEvent`, `Actor`, `Action`, `ExecutionResult`, `SecurityContext`, `CommandExecutionLog` | `audit.rs` | Append-only audit trail. |+| `PairingGuard`, `constant_time_eq`, `is_public_bind` | `pairing.rs` (`PairingGuard` and `constant_time_eq` are re-exported from `tinychannels_bus::security`) | Pairing-token check before binding the RPC server publicly. |+| `redact(value: &str) -> String` | `core.rs` | Uniform 4-char-prefix redaction for logs. |+| `security_policy_info_for_config(&Config) -> Outcome<serde_json::Value>` | `ops.rs` | RPC handler for the doctor / settings UI. |++## Sandboxing++This module no longer carries sandbox backends. The old `Sandbox` trait, `NoopSandbox`, `create_sandbox` and the Docker / Bubblewrap / Firejail / Landlock `Command` wrappers had no callers and were removed. Per-session sandbox selection lives in `crates/openhuman-core/src/sandbox/`, which delegates local OS confinement to `tinybox-jail` (vendored tinybox) and keeps its own `docker run` executor. Shell-string scanning used by command classification is `tinybox_core::shell::scan`; the classification rules stay here.++## Autonomy ladder++`AutonomyLevel` is a three-step ladder that controls how aggressively the policy gates tool calls, and it only takes effect while `[autonomy] enabled = true`. `ReadOnly` blocks every writing class outright: no in-tier approval can authorize one. `Supervised`, the default, allows reads and parks everything else for an approval round trip. `Full` allows reads and writes and still parks the network, install and destructive classes. The wire spellings are lowercase (`readonly`, `supervised`, `full`); the user-facing table is in [Approval Gate](../../features/approval-gate.md).++`CommandRiskLevel` and `ToolOperation` classify a given tool call; `ActionTracker` keeps the per-session counts that the policy compares against those caps. The agent harness asks `SecurityPolicy` for a decision before every executable tool dispatch.++All of this only applies when the autonomy policy is turned on. Per `AGENTS.md`, `[autonomy] enabled = false` is the default, and `SecurityPolicy::from_config` carries that flag through every enforcement entry point: with the policy disabled, command classification, the approval gate, the command allowlist, and the hourly action budget are all inert, and `workspace_only`, `forbidden_paths`, and the workspace-internal boundary are not enforced. One thing never turns off: `is_always_forbidden` blocks credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and system roots, and rejects `..` traversal and null bytes in a path, whether the autonomy policy is enabled or not. That is the floor this module keeps regardless of configuration.++## Audit log++`audit.rs` writes an append-only stream of `AuditEvent`s under the workspace dir. Every executable tool call lands here with its `Actor` (agent / user), `Action`, `ExecutionResult`, and the `SecurityContext` (autonomy level, sandbox backend, etc.) it ran under. The log is the post-hoc story of what the agent did and why it was allowed.++## Pairing guard++`PairingGuard` (in `pairing.rs`) stands between the RPC server and any attempt to bind to a non-loopback address. `is_public_bind` detects the dangerous case; `PairingGuard` requires a constant-time-compared pairing token (`constant_time_eq`) before such a bind is permitted. This is the iOS / LAN-companion pairing flow's defence against an unpaired peer attaching to the desktop core.++## Secret store++`SecretStore` (implemented in `keyring/encrypted_store.rs`, re-exported through `secrets.rs`) encrypts config-field secrets with ChaCha20-Poly1305 (`enc2:` prefix) under a keychain-backed master key, migrating the legacy XOR `enc:` format on decrypt. Backend selection and the encrypted-file fallback are described in `crates/openhuman-core/src/security/keyring/README.md`.++## `redact()`++`redact(value)` returns a uniform 4-char-prefix string (e.g. `"sk-a"` -> `"sk-a…"`) for use in logs and error messages. Use it whenever a secret, credential, token, or PII string is about to be formatted into a `log::` / `tracing::` call. Other domains call it directly: `credentials/`, `webhooks/`, `composio/`, the integration adapters.++## Layout++| Path | Role |+| ----------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |+| `policy/` (`mod.rs`, `types.rs`, `path_checks.rs`, `command_checks.rs`, `enforcement.rs`, `policy_*_tests.rs`, `proptest_tests.rs`) | `SecurityPolicy`, `AutonomyLevel`, risk classification, path and command checks, action tracking. |+| `core.rs`, `core_tests.rs` | `redact()` + small shared helpers. |+| `audit.rs` | Append-only audit log types. |+| `secrets.rs`, `keyring/` | `SecretStore` (implemented in `keyring/encrypted_store.rs`) + round-trip tests. |+| `pairing.rs`, `pairing_tests.rs` | `PairingGuard` + constant-time helpers. |+| `ops.rs` | RPC handler (`security_policy_info_for_config`). |+| `schemas.rs` | Controller schemas + handler dispatch. |+| `mod.rs` | Re-exports of the public surface above. |+| `live_policy.rs`, `scrub.rs`, `tools.rs` | Live-policy lookup, the host scrubbing policy (`scrub::host_policy`), and the domain's own agent tools. |+| `approval/`, `credentials/`, `devices/`, `egress/`, `encryption/`, `keyring_consent/`, `pii/`, `prompt_injection/` | Sibling kernel-security domains under the same module. Each owns its own surface; this page covers the policy core only. |++## Calls into++* `crates/openhuman-core/src/config/`: `SecurityConfig`, `AutonomyConfig` for policy + sandbox selection.+* Workspace filesystem, for the audit log and secret store.++## Called by++* `crates/openhuman-core/src/cron/ops.rs`: wraps shell jobs in `SecurityPolicy::from_config`.+* `crates/openhuman-core/src/tools/ops.rs` and `tools/impl/{browser,document,filesystem,network,presentation,system}/`: every executable tool consults `SecurityPolicy`.+* `crates/openhuman-core/src/tools/impl/network/{gate,mcp,mcp_server_tools}.rs`: risk-classify outbound calls.+* `crates/openhuman-core/src/memory/guard.rs`: wraps every memory write in `security::scrub::host_policy()`.+* `crates/openhuman-core/src/agent/tools/delegate.rs`: sub-agent dispatch goes through the autonomy gate.+* `crates/openhuman-core/src/security/credentials/`: uses `SecretStore` and `redact`.++## Tests++* Unit: `pairing_tests.rs`, `policy/policy_tests*.rs`, `policy/proptest_tests.rs`, `keyring/encrypted_store_tests*.rs`.+* `core_tests.rs` covers `redact()`.++## Related++* [`security/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/security/README.md): authoritative internal-audience overview this page mirrors.+* [Architecture overview](architecture.md): wider system context.+* [Agent Harness](agent-harness.md): where `SecurityPolicy` is consulted on every tool dispatch.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/architecture/tauri-shell.md b/docs/gitbooks/docs/gitbooks/en/developing/architecture/tauri-shell.mdnew file mode 100644index 0000000000..f0f9f52cc2--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/architecture/tauri-shell.md@@ -0,0 +1,319 @@+---+description: >-+ The desktop host in crates/openhuman-app/: Tauri v2 and WebView, the IPC+ command surface, the embedded core's lifecycle, and the core JSON-RPC bridge.+icon: desktop+---++# Tauri Shell++`crates/openhuman-app/` is the desktop host for OpenHuman: Tauri v2 and WebView, IPC commands, window management, and the bridge to the embedded `openhuman-core` Rust runtime over core JSON-RPC. It does **not** duplicate the full domain stack; that lives in `crates/openhuman-core` (library `openhuman_core`; the `openhuman-core` binary is `crates/openhuman-cli/src/main.rs`).++## Responsibilities++1. **Web UI**. Load the Vite build from `app/dist` (or dev server on port 1420).+2. **IPC**. Expose an explicit set of Tauri commands (see [Commands](#tauri-ipc-commands-cratesopenhuman-app)).+3. **Core lifecycle**. Run the core JSON-RPC server as an in-process tokio task (`core_process.rs`) and hand the renderer its URL/bearer via `core_rpc_url` / `core_rpc_token`.+4. **Window + tray**. Desktop window behavior (main, mascot, notch, overlay windows) and system tray (see `lib.rs`).+5. **Session ownership**. Log the user in and keep the current user fresh (`session/`, backed by `openhuman_tinyhumans::session`): exchange the login token, validate the JWT against `GET /auth/me`, cache `/auth/me`, and hand the resulting credential to the core with `auth.set_credential`. The core never talks to the backend's auth endpoints itself.++## Core process model++`app/package.json` `core:stage` is intentionally a no-op kept for script compatibility. The desktop app links the core in-process, so local builds no longer need a staged `openhuman-core-*` sidecar under `crates/openhuman-app/binaries/`.++## Stuck process recovery++Normal app quit runs teardown from `RunEvent::ExitRequested`: long-lived scanner tasks stop, the embedded core's cancellation token is triggered, and the final process sweep sends `SIGTERM` to direct children before escalating holdouts with `SIGKILL` after a short grace period. Sweep summaries are logged as `[app] sweep: term=N kill=M total=K`; any nonzero `kill` count is a warning and means a child ignored graceful shutdown.++On macOS, hard exits (Force Quit, `SIGKILL`, renderer crash) can skip normal teardown. The next launch runs startup recovery before the app runtime starts: it lists OpenHuman processes whose executable path belongs to the launching `.app/Contents`, skips the current process, sends `SIGTERM`, waits briefly, then `SIGKILL`s stragglers that still match the same pid+command. Logs use the `[startup-recovery]` prefix.++Startup recovery skips when `OPENHUMAN_CORE_REUSE_EXISTING=1` is set so manual CLI-core reuse still works. The Tauri command `process_diagnostics_list_owned` returns the currently owned process list; the macOS implementation is bundle-scoped, Linux/Windows currently return empty.++## Tauri shell architecture (`crates/openhuman-app/`)++### Overview++The **`crates/openhuman-app`** crate (Cargo package **`openhuman-app`**, lib **`openhuman`**, binary **`OpenHuman`**) is a **desktop-only** host. It embeds the React UI, registers plugins (deep link, opener, OS, notifications, autostart, updater), manages the main window and tray, and runs the core JSON-RPC server **in-process**.++Non-desktop targets fail at compile time (`compile_error!` in `lib.rs`).++### Directory layout (actual)++`crates/openhuman-app/src/` is a flat set of modules (no `commands/` or `utils/` subtree). Key modules:++```text+crates/openhuman-app/src/+├── lib.rs # `run()`, tray/menu, plugins, `generate_handler!`, most window/update/lifecycle commands+├── main.rs # Binary entry+├── core_process.rs # CoreProcessHandle: embedded core server task, RPC token, port conflict handling+├── core_rpc.rs # Auth helpers + `relay_http_rpc` host-side HTTP relay+├── gateway/ # Where the frontend's RPC goes: the core in this process, a+│ # core at a URL, or one this app provisions in a container /+│ # over SSH / both (tinybox). types · store · ops · registry ·+│ # commands+├── imessage_scanner/ # macOS-only: reads ~/Library/Messages/chat.db directly (never used CDP)+├── mascot_native_window.rs / notch_window.rs / window_state.rs+├── dictation_hotkeys.rs / ptt_hotkeys.rs / ptt_overlay.rs+├── native_notifications/+├── artifact_commands.rs # Artifact export (copy into Downloads)+├── directory_picker.rs # Native folder picker for the folder memory source (#5831)+├── external_navigation.rs # Keeps the main webview from navigating off-app; hands remote links to the OS browser+├── workspace_paths.rs # Safe workspace-relative file open/reveal/preview+├── app_update.rs # Updater support (commands live in lib.rs)+├── loopback_oauth.rs # Localhost OAuth redirect listener+├── session/ # Session owner: auth_* commands over openhuman_tinyhumans::session+├── claude_code.rs # Claude Code login launch+├── mcp_commands.rs # MCP client helpers+├── file_logging.rs # Log file sink + logs-folder commands+├── process_recovery.rs / process_kill.rs / local_data_reset.rs # process_recovery has per-platform submodules under process_recovery/+├── deep_link_ipc.rs / deep_link_ipc_windows.rs / deep_link_registration_check.rs+└── stderr_panic_hook.rs / reset_reboot_schedule.rs+```++This listing was rewritten against the real tree after #5478 / #5456. Gone with+the move off Chromium: `cdp/`, the `cef_*` preflight modules, `webview_accounts/`,+every `*_scanner/` but `imessage_scanner/`, the `meet_*` call window,+`fake_camera/` and `companion_commands.rs`. `webview_apis/` went later: it was+the WS bridge those scanners called, and once they were gone its router+dispatched nothing while still binding a loopback listener at boot.++There is **no** `src-tauri/src/services/session_service.rs` in this tree; session semantics are handled in the web layer + backend + core as applicable.++### Data flow: UI → core++```text+React (fetch)+ → POST http://127.0.0.1:<port>/rpc (URL from `core_rpc_url`,+ bearer from `core_rpc_token`)+ → embedded openhuman core server (tokio task in this process)+```++The renderer talks to the local core **directly over HTTP**: `app/src/services/coreRpcClient.ts` invokes `core_rpc_url` / `core_rpc_token` once, then issues plain `fetch()` calls. The `relay_http_rpc` Tauri command is a host-side fallback used only when the RPC URL is **not** a trustworthy origin for the secure `tauri://localhost` webview (e.g. a self-hosted runtime on a LAN IP, blocked as mixed content, #3865). In that case the Rust host delegates to `openhuman_rpc::post_json_rpc` from the shared `crates/openhuman-rpc` crate (feature `http-client`): 30 s timeout, redirects disabled when a bearer is present, status + body mirrored back verbatim as `HttpRpcResponse`. The shell adds only the gateway transport guard (`validate_remote_transport`, feature `gateways`) before delegating.++`CoreProcessHandle` in `core_process.rs` owns the embedded server task (started via `openhuman_rpc::server::run_server_embedded_with_ready` with a per-launch random bearer token) and handles stale-listener/port-conflict recovery.++### Window and tray behavior++- The shell creates a tray icon at startup (`RunEvent::Ready`) and wires actions to open the main window or quit. Tray setup is skipped on Linux packaged runs (GTK panic).+- Hide-to-tray is implemented in the `RunEvent::WindowEvent { CloseRequested }` handlers in `lib.rs`, not as IPC commands: macOS hides the whole app (`AppHandle::hide()`, #2049), Windows hides the top-level `Chrome_WidgetWin_1` frame via `EnumWindows` + `SW_HIDE` (#1607).+- On macOS `RunEvent::Reopen` (Dock click) restores and focuses the main window.++### Bundled resources++`tauri.conf.json` bundles **`../../crates/openhuman-core/src/agent/prompts`** so the core prompt markdown ships with the app.++### Related++- IPC surface: see the [Commands](#tauri-ipc-commands-cratesopenhuman-app) section below+- HTTP bridge: see the [Core bridge & helpers](#core-bridge--helpers-cratesopenhuman-app) section below+- Rust domains and runtime: `crates/openhuman-core/src/`, `crates/openhuman-core/src/core/`+- Shared RPC contracts + HTTP client: `crates/openhuman-rpc/` (also used by `crates/openhuman-tui` for envelope decoding)++## Tauri IPC commands (`crates/openhuman-app`)++All commands are registered in **`crates/openhuman-app/src/lib.rs`** inside `tauri::generate_handler![...]`: that list is the authoritative reference. The major families:++### Core RPC & diagnostics++| Command | Purpose |+| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |+| `core_rpc_url` | Return the **active gateway's** JSON-RPC URL: the embedded core's `http://127.0.0.1:<port>/rpc` unless another gateway is active |+| `core_rpc_token` | Return the active gateway's bearer. Paired with `core_rpc_url`: a token minted for the embedded core is meaningless to a core in a container |+| `core_rpc_endpoint` | Return the URL and bearer together from one resolved snapshot, so a gateway switch between two separate calls cannot pair one gateway's URL with another's token |+| `relay_http_rpc` | Host-side JSON-RPC POST (`{ url, token?, body }` → `{ status, body }`) for self-hosted runtimes the webview cannot fetch (mixed content, #3865) |+| `overlay_parent_rpc_url` | RPC URL inherited from a parent process (overlay windows), from `OPENHUMAN_CORE_RPC_URL` |+| `process_diagnostics_list_owned` | List OpenHuman processes owned by this app bundle (macOS; empty elsewhere) |++Use **`app/src/services/coreRpcClient.ts`** (`callCoreRpc`) from the frontend.++### Gateways: running the core somewhere else++A **gateway** is one way of reaching an OpenHuman core. Four exist: the core inside this+process, a core somebody else is running at a URL, and two this app provisions itself: in+a Docker container, or on a machine reached over SSH. The last two are the same code:+[tinybox](https://github.com/tinyhumansai/tinybox) models *reach* (`local` / `ssh`) and+*confinement* (`passthrough` / `docker`) as independent axes, so "a container on the build+server" is those two choices made separately rather than a third case with code of its own.++**The seam is one line.** A gateway resolves to a URL and a bearer, and `core_rpc_url` /+`core_rpc_token` answer from the active one. Every RPC call site in the renderer therefore+follows along unchanged: there is no per-gateway transport in the frontend, and+`services/transport/` (the iOS `ConnectionProfile` path) is not involved.++Provisioning is four tinybox calls: `create` a box publishing the core's port, `spawn` the+core in it detached with a freshly minted bearer, `forward` that published port back to+this machine, then poll the core's unauthenticated `/health`. The third step is the one+that is easy to omit and impossible to notice missing: publishing puts the port on the+*box's* host, which for an SSH placement is the far machine.++| Command | Purpose |+| ------------------ | -------------------------------------------------------------------------- |+| `gateway_list` | Every configured gateway, the built-in desktop one first |+| `gateway_save` | Add or replace a gateway. Does not activate it |+| `gateway_delete` | Forget a gateway. The running session is unaffected |+| `gateway_activate` | Provision if needed, then make it the one RPC goes to |+| `gateway_active` | Which gateway is active |+| `gateway_status` | `inactive` / `activating{step}` / `connected{endpoint}` / `failed{reason}` |++Records live shell-side in `gateways.json`, **not** renderer `localStorage`: an SSH+identity path and a remote bearer are materially more sensitive than a window position, and+the renderer's own notes on the cloud token (audit U3, `utils/configPersistence.ts`) already+say a renderer XSS can read anything kept there. The frontend holds a gateway *id*.++Shell-internal callers (`imessage_scanner`, `local_data_reset`) deliberately+keep talking to the embedded core: they are about *this* machine's iMessage database, *this*+install's data, and *this* machine's audio, so routing them to a remote gateway would be+wrong rather than incomplete.++Gated by the shell-local `gateways` Cargo feature (default on). That gate is unrelated to+the feature-forwarding rules in `AGENTS.md`, which govern which `openhuman_core` gates the+shell forwards; nothing here belongs in `scripts/ci/product-features.txt`.++Frontend: **`app/src/services/gatewayService.ts`**, surfaced in Settings → Core connection+(`components/settings/panels/core/GatewaySection.tsx`).++### Core & app lifecycle++| Command | Purpose |+| ------------------------------------------------- | --------------------------------------------- |+| `start_core_process` / `restart_core_process` | Start / restart the embedded core server task |+| `recover_port_conflict` / `force_quit_port_owner` | Resolve a foreign listener on the core port |+| `reset_local_data` | Wipe local app data (`local_data_reset.rs`) |+| `app_quit` / `restart_app` | Quit or relaunch the app |+| `get_active_user_id` | Read the active user id |++### Session (`session/`)++The shell is the session owner on the desktop: it talks to the TinyHumans backend's auth endpoints so the core never has to. `openhuman_tinyhumans::session` does the work; the shell adds the link to the core (`HttpCoreLink`, the same `(url, token)` the renderer uses, so a gateway switch is followed) and these commands. Errors carry a stable `PREFIX:` (`REJECTED`, `EXPIRED`, `TRANSIENT`, `CONSUME_FAILED`, `USER_ID_UNAVAILABLE`, `CORE`) the renderer classifies on.++| Command | Purpose |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `auth_login_with_token` | Exchange a one-time login token (`POST /auth/login-token/consume`), validate the JWT (`GET /auth/me`), install it in the core |+| `auth_store_session` | Install a JWT the renderer already holds (validated first) or the offline local token (stored as-is with its user) |+| `auth_logout` | Clear the session credential in the core |+| `auth_state` | The core's credential state plus the cached current user |+| `auth_current_user` | The current user from the `/auth/me` cache (5 s TTL, stale-while-revalidate, backoff); `force` bypasses the cache |++Events: `auth://changed` (credential or current user changed; payload `SessionState`) and `auth://expired` (the backend rejected the stored credential and it has been cleared; payload `{ source }`). `app/src/services/session/shellSessionEvents.ts` bridges them into the window events `CoreStateProvider` already handles.++A JWT accepted while the backend is unreachable (live `exp`, subject claim) is installed with a `pendingBackendValidation` placeholder user and revalidated in the background; a rejected JWT is never installed. In cloud mode the renderer targets a remote core the shell does not know about, so `app/src/services/session/sessionOwner.ts` runs a thin browser equivalent there (and in the browser build).++### Updates++`check_core_update` / `apply_core_update` (embedded core) and `check_app_update` / `download_app_update` / `install_app_update` / `apply_app_update` (desktop app, via the updater plugin).++### Hotkeys (dictation, PTT)++| Command | Purpose |+| ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| `register_dictation_hotkey` / `unregister_dictation_hotkey` | Global dictation shortcuts (`dictation_hotkeys.rs`) |+| `register_ptt_hotkey` / `unregister_ptt_hotkey` / `show_ptt_overlay` | Push-to-talk: see the [PTT section](#push-to-talk-ptt-hotkey--overlay) below |++### Notifications++`notification_permission_state` / `notification_permission_request` / `show_native_notification` provide the OS-level notification surface. They are implemented in `native_notifications`.++### Window management++| Command | Purpose |+| -------------------------------------------------- | ---------------------------------------------- |+| `activate_main_window` | Show + focus the main window |+| `set_titlebar_for_sidebar` | macOS only: switch the main window's title bar style when the sidebar collapses, so the webview keeps spanning the full window |+| `mascot_window_show` / `mascot_window_hide` | Toggle the mascot native window |+| `notch_window_show` / `notch_window_hide` | Toggle the notch window |++Hide-to-tray / reopen behavior is **not** an IPC command: it lives in the `RunEvent` handlers in `lib.rs` (see [Window and tray behavior](#window-and-tray-behavior)).++### Artifacts, logs, MCP, OAuth++| Command | Purpose |+| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------- |+| `download_artifact_to_downloads` | Copy an artifact straight to the Downloads folder (`artifact_commands.rs`); the Save-As dialog this used to sit behind was dropped with the shell's `rfd` dependency |+| `pick_directory_via_dialog` | Native OS folder picker for the folder memory source, returning an absolute path a `webkitdirectory` input cannot report (`directory_picker.rs`, #5831) |+| `reveal_logs_folder` / `logs_folder_path` | Open / return the file-logging folder (`file_logging.rs`) |+| `mcp_resolve_binary_path` / `mcp_open_client_config` | MCP client helpers (`mcp_commands.rs`) |+| `start_loopback_oauth_listener` / `stop_loopback_oauth_listener` | Localhost OAuth redirect listener (`loopback_oauth.rs`) |+| `claude_code_login_launch` | Launch the Claude Code login flow (`claude_code.rs`) |++### Workspace file links++From **`workspace_paths.rs`** (closes `#1402`). These commands accept workspace-relative paths only. The shell resolves each path against the active OpenHuman workspace, canonicalizes the target, and rejects traversal, absolute paths, URI-like prefixes, and symlink escapes before opening or reading anything.++| Command | Purpose |+| --------------------------------- | ---------------------------------------------------------------------- |+| `open_workspace_path` | Open an existing workspace file or directory with the OS default app. |+| `reveal_workspace_path` | Reveal an existing workspace file or directory in the OS file manager. |+| `preview_workspace_text` | Read a capped UTF-8 text preview from an existing workspace file. |++### Push-to-talk (PTT) hotkey + overlay++Registered in **`lib.rs`** (`ptt_hotkeys.rs` + `ptt_overlay.rs`). These commands manage the global push-to-talk shortcut and the floating overlay window.++| Command | Signature | Purpose |+| ----------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| `register_ptt_hotkey` | `(shortcut: String) -> Result<(), String>` | Register (or re-register) a global hotkey for push-to-talk. Emits Tauri events `ptt://start { session_id }` (key pressed) and `ptt://stop { session_id }` (key released). Returns an error string if the shortcut conflicts with dictation or if the OS rejects it (e.g. Wayland, Accessibility permission required on macOS). |+| `unregister_ptt_hotkey` | `() -> Result<(), String>` | Unregister the current PTT hotkey and tear down the overlay window. |+| `show_ptt_overlay` | `(active: bool, session_id: u64) -> ()` | Show (`active: true`) or hide (`active: false`) the floating PTT overlay window. The window is focus-stealing-free (`focus: false`). Called by `PttHotkeyManager.tsx` via `app/src/utils/tauriCommands/ptt.ts`. |++**Event flow:** `register_ptt_hotkey` wires the OS hotkey to fire `ptt://start` / `ptt://stop` Tauri events that `PttHotkeyManager.tsx` subscribes to via `@tauri-apps/api/event`. The manager forwards them into the `pttService` state machine which drives the audio capture → transcribe → chat-send pipeline.++**Conflict detection:** `register_ptt_hotkey` checks for overlap with the active dictation shortcuts before registering. If a conflict is detected it returns `"ConflictsWithDictation(<shortcut>)"` without registering anything, and the settings panel surfaces this as `pttSettings.errorConflictsWithDictation`.++### Synthetic input main-thread executor (native registry, not `invoke`)++Registered in **`lib.rs`** at startup under the event-bus native-request method+`computer.input_on_main_thread` (`INPUT_ON_MAIN_THREAD_METHOD`, defined in+`openhuman_core::tools::computer::main_thread`). This is **not** a+`@tauri-apps/api` `invoke` command. It is an in-process native request the+**core** dispatches to the **shell** so synthetic input runs on the real app+main thread.++Why: enigo's macOS keyboard-layout lookup (`TSMGetInputSourceProperty`) traps+(`_dispatch_assert_queue_fail` / `EXC_BREAKPOINT`) and crashes the desktop host when+called off the main thread. The `mouse` / `keyboard` tools therefore never call+enigo on their tokio worker; they build a closure and dispatch it here, where+the shell runs it via `AppHandle::run_on_main_thread`.++| Field | Shape |+| ------------ | --------------------------------------------------------------------------------------------------- |+| Method | `computer.input_on_main_thread` |+| Request | `MainThreadInputOp { run: Box<dyn FnOnce() -> Result<String, String> + Send> }` (passed by value) |+| Response | `Result<String, String>`: `Ok(message)` on success, `Err(reason)` on failure |+| Availability | Desktop only. Headless / CLI builds register no executor; the core call then returns a clean `Err`. |++### Removed / not present++The following **do not** exist in the current `generate_handler!` list: `greet`, `core_rpc_relay` (superseded by direct `fetch` + `relay_http_rpc`), `ai_get_config` / `ai_refresh_config` / `write_ai_config_file`, `show_window` / `hide_window` / `toggle_window` / `minimize_window` / `maximize_window` / `close_window`, the `openhuman_*` daemon/service helpers, `exchange_token`, `get_auth_state`, `socket_connect`, `start_telegram_login`. Authentication and sockets are handled in the **React** app and **core** process, not via these IPC names.++### Example: core RPC++```typescript+import { callCoreRpc } from "../services/coreRpcClient"; // app/src/services/coreRpcClient.ts++// Direct HTTP to the embedded core (URL + bearer resolved via+// `core_rpc_url` / `core_rpc_token` under the hood):+const result = await callCoreRpc({+ method: "your.rpc.method",+ params: { foo: "bar" },+});+```++---++_See `crates/openhuman-app/src/lib.rs` (`generate_handler!`) for the authoritative list._++## Core bridge & helpers (`crates/openhuman-app`)++The Tauri crate **does not** embed a duplicate Socket.io server or Telegram client; it focuses on **in-process core lifecycle** and the thin HTTP/auth glue around the core's JSON-RPC surface.++### `CoreProcessHandle` (`core_process.rs`)++- Runs the core's HTTP/JSON-RPC server as a **tokio task inside the Tauri host** via `openhuman_rpc::server::run_server_embedded_with_ready`: no sidecar binary.+- Generates a per-launch 256-bit hex bearer token (`generate_rpc_token`) and hands it to the embedded server; the renderer reads it via the `core_rpc_token` command.+- Stale-listener policy (#1130): if the core port is already occupied, probes whether the listener is an old OpenHuman core (terminate + respawn) or something foreign (surface the conflict). `OPENHUMAN_CORE_REUSE_EXISTING=1` opts back into attach-to-existing for debugging.+- Managed as Tauri state in `lib.rs` (`app.manage(core_handle)`).++### `core_rpc` (`core_rpc.rs`)++- Shared auth helpers for host-side calls to the local core (URL from `OPENHUMAN_CORE_RPC_URL` or the default port; bearer from `core_process::current_rpc_token`).+- **`relay_http_rpc`** Tauri command: a thin wrapper over `openhuman_rpc::post_json_rpc` (`crates/openhuman-rpc`, feature `http-client`) for self-hosted runtimes on non-trustworthy origins; `bearer_header`, `redact_url_for_log` and `HttpRpcResponse` are re-exported from that crate (see [Core RPC & diagnostics](#core-rpc--diagnostics)).diff --git a/docs/gitbooks/docs/gitbooks/en/developing/building-rust-core.md b/docs/gitbooks/docs/gitbooks/en/developing/building-rust-core.mdnew file mode 100644index 0000000000..59c5ff4d8e--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/building-rust-core.md@@ -0,0 +1,209 @@+---+description: Build the Rust core from scratch on a fresh machine.+icon: terminal+---++# Building the Rust Core++This page is the contributor-facing reference for compiling the Rust core on a fresh machine.++It covers the **core workspace and its sibling crates**:++* Cargo package: `openhuman`+* Binary: `openhuman-core`+* Library: `openhuman_core`++The root `Cargo.toml` is a virtual workspace whose members are `crates/openhuman-core`, `crates/openhuman-embed`, `crates/openhuman-rpc`, `crates/openhuman-tinyhumans`, `crates/openhuman-cli`, and `crates/openhuman-tui`. `crates/openhuman-app` (the Tauri desktop shell) is excluded from that workspace and builds from its own manifest.++If you want the full desktop app (`pnpm dev`, Tauri, frontend tooling), use [Getting Set Up](getting-set-up.md). That path has extra JavaScript, submodule, and desktop-runtime requirements that are **not** needed for a core-only `cargo` workflow.++## 1. Install the pinned Rust toolchain++The repository pins Rust in [`rust-toolchain.toml`](https://github.com/tinyhumansai/openhuman/blob/main/rust-toolchain.toml):++* Channel: `1.96.1`+* Components: `rustfmt`, `clippy`++The pin exists because `rusqlite` 0.40 / `libsqlite3-sys` 0.38 use the `cfg_select!` macro, stabilized in 1.96 (unstable through 1.95).++Recommended install:++```bash+rustup toolchain install 1.96.1 --component rustfmt --component clippy+rustup default 1.96.1+```++You can also let `cargo` auto-install from `rust-toolchain.toml` after `rustup` itself is installed.++## 2. Clone the repo++Core-only work:++```bash+git clone https://github.com/tinyhumansai/openhuman.git+cd openhuman+```++That is enough for the Rust workspace. Core sources, the package manifest, and the authoritative domain implementation live under `crates/openhuman-core/`. The stable host-facing library facade is the sibling `crates/openhuman-embed/` package, while the terminal frontend is `crates/openhuman-tui/`. The `openhuman-core` binary itself, the developer and benchmark bins, and the root `tests/*.rs` / `examples/*.rs` targets live in `crates/openhuman-cli/`, which depends on `crates/openhuman-tinyhumans/` for the SDK-backed backend transport the core does not carry on its own. Shared JSON-RPC contracts and the HTTP client used by the Tauri shell and the TUI live in `crates/openhuman-rpc/`.++The recursive submodules under repo-root `vendor/` are required for the core build too, not just the desktop shell: `crates/openhuman-core/Cargo.toml` path-depends on `vendor/tinyagents`, `vendor/tinymemory`, `vendor/tinymcp`, and the rest of the `tiny*` family, and the root `Cargo.toml` `[patch]` tables point into `vendor/tinymemory`, `vendor/tinyflows`, `vendor/tinychannels`, `vendor/motosan-ai-oauth`, and the `tinyinference` copy nested under `vendor/tinyagents/`.++```bash+git submodule update --init --recursive vendor/+```++Desktop/Tauri work has extra requirements on top of this: follow [Getting Set Up](getting-set-up.md) for those.++## 3. Build commands++From the repository root:++```bash+# Fast dependency + type check+cargo check --manifest-path Cargo.toml++# Debug build of the actual CLI / RPC binary+cargo build --manifest-path Cargo.toml -p openhuman-cli --bin openhuman-core++# Check the stable host-facing embedding facade+cargo check --manifest-path Cargo.toml -p openhuman-embed++# Check the shared RPC contracts + HTTP client crate+cargo check --manifest-path Cargo.toml -p openhuman-rpc++# Build the terminal frontend (embeds the core in-process)+cargo build --manifest-path Cargo.toml -p openhuman-tui++# Check the desktop shell (separate Cargo world, own manifest/lockfile)+cargo check --manifest-path crates/openhuman-app/Cargo.toml++# Release build+cargo build --manifest-path Cargo.toml --release -p openhuman-cli --bin openhuman-core++# Rust tests+cargo test --manifest-path Cargo.toml+```++Notes:++* The core library's package name is `openhuman` (crate `openhuman_core`), but the runnable binary, `openhuman-core`, is built from the `openhuman-cli` package (`crates/openhuman-cli/src/main.rs`), which is why the commands above pass `-p openhuman-cli`.+* The built binary lands at `target/debug/openhuman-core` or `target/release/openhuman-core`.++### Faster local linking (optional)++The `openhuman` core crate links a large single rlib, so the edit → `cargo check`/`cargo test` inner loop is frequently link-bound. A faster linker (mold on Linux, lld on macOS) can cut a large slice off every incremental relink. [`.cargo/config.toml`](https://github.com/tinyhumansai/openhuman/blob/main/.cargo/config.toml) documents the manual opt-in, but the easiest path is:++```bash+# installs mold/lld detection into $CARGO_HOME/config.toml, never the+# repo's tracked .cargo/config.toml, so it's a per-machine opt-in+scripts/dev-setup-linker.sh++# preview the change first+scripts/dev-setup-linker.sh --dry-run+```++Install the linker first (`apt install mold` / `brew install llvm`). The script detects it and exits with instructions if it's missing. It's idempotent: re-running it after the linker is already configured is a no-op. CI enables the same flag directly via `RUSTFLAGS` in the Linux Rust jobs; this script exists so local `cargo` invocations get the same speedup without depending on a container.++### Feature gates and binary size++`crates/openhuman-core/Cargo.toml` builds most of its domains behind Cargo features. A bare `cargo check` compiles the contributor default set (`media`, `skills`, `flows`, `mcp`, `channels`, `http-server`, `scheduler-gate`, `file-logging`, `modules`), which is not the same as what the desktop app ships: `scripts/ci/product-features.txt` is the single source of truth for the shipped product's gate list, and `scripts/ci/check-feature-forwarding.mjs` asserts that `crates/openhuman-app/Cargo.toml` forwards exactly that set. Turning a gate off drops real code and, for some gates, whole native dependencies. For measured binary sizes and RSS across a few feature recipes, see [Performance](performance.md).++## 4. macOS prerequisites++Install:++* Xcode Command Line Tools: `xcode-select --install`++Why:++* Native dependencies (`cpal` for audio capture behind the `inference` feature, which `voice` requires; the `objc2` Contacts cohort compiled by the vendored `tinymemory` crates) compile C/Objective-C code during the build and need Apple toolchains and SDK headers present.++After Xcode CLT is installed, the core should build with the cargo commands above.++## 5. Linux prerequisites++### Core-only package set++Install these packages before running `cargo` on a fresh Linux machine.++**Ubuntu / Debian:**++```bash+sudo apt-get update+sudo apt-get install -y \+ build-essential cmake pkg-config clang libssl-dev libclang-dev \+ libasound2-dev libxi-dev libxtst-dev libxdo-dev libudev-dev \+ libstdc++-14-dev+```++**Arch Linux:**++```bash+sudo pacman -S --needed base-devel cmake pkgconf clang openssl \+ alsa-lib libxi libxtst xdotool libevdev+```++> On Arch, `clang` includes `libclang` and `base-devel` includes `gcc` (providing `libstdc++`), so separate `-dev` packages are not needed.++Why these matter:++* `build-essential` / `base-devel`, `cmake`, `pkg-config` / `pkgconf`: native builds used by transitive Rust dependencies.+* `clang`, `libclang-dev`: bindgen (used by native crates such as `cpal`'s ALSA bindings) and C/C++ compilation paths.+* `libssl-dev` / `openssl`: OpenSSL headers needed by some networking dependencies.+* `libasound2-dev` / `alsa-lib`, `libxi-dev` / `libxi`, `libxtst-dev` / `libxtst`, `libxdo-dev` / `xdotool`, `libudev-dev` (included in Arch `systemd-libs`), `libevdev`: required by audio/input/device crates (`cpal`, `enigo`/X11 input handling) pulled into the core build.+* `libstdc++-14-dev`: `clang`-driven builds may pick GCC 14 C++ headers on Ubuntu runners; this keeps `libstdc++.so` resolvable for those native crates.++### Linux desktop/Tauri package set++If you are building the desktop shell instead of the core-only crate, install the broader dependency set.++**Ubuntu / Debian** (mirrored from [`.github/workflows/build-desktop.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/build-desktop.yml)):++```bash+sudo apt-get update+sudo apt-get install -y \+ libgtk-3-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev \+ patchelf cmake libasound2-dev libxdo-dev libxtst-dev libx11-dev libxi-dev \+ libevdev-dev libssl-dev libclang-dev \+ libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 \+ libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 \+ libgbm1 libpango-1.0-0 libcairo2 libatspi2.0-0 libxshmfence1 libu2f-udev+```++**Arch Linux:**++```bash+sudo pacman -S --needed gtk3 webkit2gtk-4.1 libayatana-appindicator \+ librsvg patchelf nss nspr at-spi2-core libcups libdrm \+ libxkbcommon libxcomposite libxdamage libxfixes libxrandr \+ mesa pango cairo libxshmfence+```++Use the desktop lists only when you need `crates/openhuman-app/`; for root-crate work, the smaller core-only list above is the relevant baseline.++## 6. Windows prerequisites++Install:++* Rust via `rustup`+* Visual Studio Build Tools 2022 or Visual Studio with the **Desktop development with C++** workload+* The MSVC target used by CI and release builds: `x86_64-pc-windows-msvc`++Recommended commands after the Microsoft toolchain is installed:++```powershell+rustup toolchain install 1.96.1 --component rustfmt --component clippy+rustup target add x86_64-pc-windows-msvc+cargo build --manifest-path Cargo.toml -p openhuman-cli --bin openhuman-core+```++Use the MSVC toolchain, not MinGW, to match CI and release builds.++## 7. Related paths++* [Getting Set Up](getting-set-up.md): full desktop contributor setup with `pnpm`, Tauri, and submodules. The core runs in-process inside the desktop shell (see [Tauri Shell](architecture/tauri-shell.md)); there is no sidecar staging step.+* [OpenHuman Architecture](architecture/): where the core fits into the desktop app and RPC flow.+* [Deep Architecture Reference](architecture/architecture.md): the full crate map and repository layout.+* [Embedding](embedding.md): using `crates/openhuman-embed` to run the core as a library in another product.+* [Engines](engines.md): the pluggable LLM, embedding, memory, and search backends the core can run against.+* [Performance](performance.md): binary size, cold start, and memory numbers across feature recipes.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/cef.md b/docs/gitbooks/docs/gitbooks/en/developing/cef.mdnew file mode 100644index 0000000000..c05e57c240--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/cef.md@@ -0,0 +1,122 @@+---+description: >-+ Historical design notes from when OpenHuman shipped its own Chromium (CEF)+ runtime. The shell now runs on stock Tauri (Wry); kept as background only.+icon: chrome+---++# Chromium Embedded Framework (historical)++{% hint style="warning" %}+**Historical.** The desktop shell no longer ships CEF. `crates/openhuman-app/` builds on upstream Tauri's native webview runtime (Wry: WKWebView / WebView2 / WebKitGTK), and `AGENTS.md` forbids restoring CEF or CDP-scanner assumptions. The native iMessage scanner remains separate because it reads `chat.db` directly. Everything below describes the retired runtime and is kept only as design background; the file paths it cites (`crates/openhuman-app/src/webview_accounts/`, `scripts/ensure-tauri-cli.sh`, `vendor/tauri-cef`) no longer exist.+{% endhint %}++For about a year OpenHuman did not run on the platform's built-in webview. It shipped its own **Chromium Embedded Framework (CEF) runtime** through a fork of `tauri-runtime`, and that single decision was load-bearing for almost every "OpenHuman knows what's happening in your tools" feature in the product.++This page explains why CEF was in the bundle, what the codebase used it for, and what replaced each piece. Nothing described below is in the shipped app.++## Why CEF instead of a stock webview++Stock Tauri uses each platform's native webview. WKWebView on macOS, WebView2 on Windows, WebKitGTK on Linux. Those work fine for rendering the OpenHuman app itself. They have one fatal limitation for our use case: **none of them expose Chrome DevTools Protocol (CDP)**.++CDP is the load-bearing primitive. Every "watch what's happening inside Slack / WhatsApp / Telegram / Discord / Meet" feature in OpenHuman talks to those embedded apps via CDP, not via injected JavaScript. CDP gives us:++- `Target.getTargets` to discover every page and service worker.+- `IndexedDB.requestDatabaseNames` / `requestDatabase` / `requestData` to walk a third-party app's local storage.+- `DOMSnapshot.captureSnapshot` for read-only DOM inspection that doesn't trip framework reactivity.+- `Runtime.evaluate` for ephemeral one-shot reads (a single fixed JSON serializer, never a persistent bridge).+- `Page.addScriptToEvaluateOnNewDocument` for the small number of cases where we genuinely need a renderer-side shim before page JS runs.++Stock webviews give none of that, which is why CEF was vendored.++**What replaced it.** Browser automation moved out of the shell entirely: a real Chrome driven over CDP from the Rust side, through the `tinycomputer` module, as a separate process the agent either launches or attaches to. See [Browser & Computer Control](../features/native-tools/browser-and-computer.md). The scanners that walked a third-party app's IndexedDB are gone; the one that survived, iMessage, never needed a browser because it reads `chat.db` directly.++The vendored runtime lived at `crates/openhuman-app/vendor/tauri-cef/` (forked from the upstream `tauri-cef` branch onto `tinyhumansai/tauri-cef:feat/cef-notification-intercept`, currently CEF 146.4.1). Every Tauri crate is patched at `crates/openhuman-app/Cargo.toml` via `[patch.crates-io]` to point at this fork. The vendored `cargo-tauri` CLI bundles Chromium correctly into `Contents/Frameworks/`; stock `@tauri-apps/cli` produces a broken bundle that panics in `cef::library_loader::LibraryLoader::new`. `scripts/ensure-tauri-cli.sh` (removed) reinstalled the vendored CLI whenever the fork is newer than the installed binary.++## What CEF was used for++### Embedded third-party webviews++Every connected provider that runs as a hosted web app gets its own child CEF webview:++- WhatsApp Web+- Telegram Web+- Slack+- Discord+- Google Meet+- Gmail+- Zoom+- Google Messages+- browserscan++Per-account storage is isolated to `{app_local_data_dir}/webview_accounts/{id}/`. Two Slack workspaces, two browser profiles. Code (removed): `crates/openhuman-app/src/webview_accounts/mod.rs`.++### CDP-driven scanners++Each provider had a **scanner module** in `crates/openhuman-app/src/` (all removed except `imessage_scanner/`). Every scanner holds a long-lived WebSocket to CEF's `--remote-debugging-port=19222` and ticks on a fixed schedule:++| Scanner | Cadence | What it does |+| ------------------- | ------------------------------- | -------------------------------------------------------------------- |+| `whatsapp_scanner` | 2s DOM tick + 30s full IDB walk | Reads message stores, pulls media metadata |+| `telegram_scanner` | Same | Plus QR-login hand-off to native Telegram Desktop |+| `slack_scanner` | 30s IDB walk | Pure IDB - no DOM scrape needed |+| `discord_scanner` | Periodic | Channel + DM state via CDP |+| `meet_scanner` | Periodic | Live captions + participant state during calls |+| `wechat_scanner` | Periodic | WeChat Web chat list + active conversation DOM scrape via CDP |+| `gmessages_scanner` | Periodic | Google Messages Web read-only IndexedDB walk |+| `imessage_scanner` | Periodic | **No webview.** Reads `~/Library/Messages/chat.db` directly on macOS |++Each scan emitted `webview:event` payloads from the shell, so scanning continued whether the UI window was open or backgrounded. (The native iMessage scanner's old `openhuman.memory_doc_ingest` RPC call no longer exists in the core.)++### Google Meet mascot camera++The flashiest CEF trick, and the one that went with it. The Meet agent did not just _attend_ a meeting, it **broadcast** itself as a camera. That worked because CEF let us:++1. Inject a tiny bridge (`camera_bridge.js`) via `Page.addScriptToEvaluateOnNewDocument` before any Meet code runs.+2. Override `navigator.mediaDevices.getUserMedia` so it returns a `MediaStream` from a hidden 640×480 canvas instead of a real camera.+3. Render the mascot SVG on that canvas, swapping mood states (idle, thinking, talking) via `window.__openhumanSetMood(...)` driven from Rust over CDP.++There's also a build-time path that rasterizes the mascot SVG to Y4M and uses CEF's native `--use-file-for-fake-video-capture` flag, a fully native fake-camera source with no JS at all.++Code (removed): `crates/openhuman-app/src/meet_video/`.++### Native notification interception++The fork at `feat/cef-notification-intercept` adds renderer-side shims for `Notification.permission`, `Notification.requestPermission()`, and `navigator.permissions.query({name: "notifications"})`. These now install in the real `tauri-runtime-cef` path on every runtime code path, so when Slack checks if it can show notifications, the answer is consistent with what CEF's permission callbacks already granted.++This was the bulk of the (since removed) `docs/TAURI_CEF_FINDINGS_AND_CHANGES.md`. It's why Slack stops asking the same permission five times in a session.++## The "no new JS injection" rule++The rule is documented in [`AGENTS.md`](https://github.com/tinyhumansai/openhuman/blob/main/AGENTS.md): **migrated providers load with zero injected JavaScript**. All scraping happens natively over CDP from the scanner side.++This matters because anything host-controlled that runs inside a third-party origin is an attack-surface liability. A persistent JS bridge inside Slack is one Slack update away from breaking, and one mistake away from leaking the bridge to attacker-controlled JS. CDP from outside the renderer is strictly better.++| Provider | Migrated? | What loads at startup |+| ----------- | ------------- | -------------------------------- |+| WhatsApp | Yes | Zero JS |+| Telegram | Yes | Zero JS |+| Slack | Yes | Zero JS |+| Discord | Yes | Zero JS |+| browserscan | Yes | Zero JS |+| Gmail | grandfathered | Legacy `runtime.js` bridge |+| LinkedIn | grandfathered | Legacy `LINKEDIN_RECIPE_JS` |+| Google Meet | grandfathered | Camera + audio + caption bridges |++Legacy injection should shrink, never grow. New providers go straight onto the CDP-only path.++## Removed sections++This page used to carry a CEF prewarm note, Windows and Linux startup-triage+runbooks, a plugin-audit table, and a "where this could evolve" design section.+They are dropped rather than kept: the runbooks told a maintainer to collect+logs and set environment variables that no longer exist, and the design section+has been overtaken. The one idea in it that did happen, browser automation as a+first-class agent tool, is+[Browser & Computer Control](../features/native-tools/browser-and-computer.md).++## See also++- [`AGENTS.md`](https://github.com/tinyhumansai/openhuman/blob/main/AGENTS.md): the canonical rule that no JavaScript injection is added to child webviews, and that CEF and CDP-scanner assumptions are not restored.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/claude-code.md b/docs/gitbooks/docs/gitbooks/en/developing/claude-code.mdnew file mode 100644index 0000000000..022b100f0c--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/claude-code.md@@ -0,0 +1,105 @@+---+description: Routing a workload through the Claude Code CLI or the Claude Agent SDK.+icon: terminal+---++# Claude Code CLI provider++OpenHuman can route any chat workload through Anthropic's `claude` CLI instead of calling the Anthropic HTTP API directly. The CLI handles model selection, auth, and prompt-cache management; OpenHuman drives it as a long-lived, session-resuming child process, parses its stream-json output, and hands it an MCP endpoint so the model can reach native OpenHuman state (memory, threads, agents, search). This is one of several pluggable LLM backends; see [Engines](engines.md) for the full list.++The provider itself, `ClaudeCodeProvider`, is owned by `tinyagents-harness` (vendor/tinyagents), not by OpenHuman: see [its README](https://github.com/tinyhumansai/tinyagents/blob/main/crates/tinyagents-harness/src/providers/claude_code/README.md) for the full file map and implementation notes. OpenHuman only wires it up in `crates/openhuman-core/src/inference/provider/factory/subprocess_providers.rs`, which supplies the MCP endpoint (`OpenHumanMcpEndpoint`, below) and reads the resulting model string back into its own routing.++## Requirements++* Claude Code CLI **≥ 2.0.0** (`MIN_CLI_VERSION`), either on `PATH`, at one of the supported well-known install locations, or selected with `OPENHUMAN_CLAUDE_CLI=/abs/path/to/claude`.+* An Anthropic API key in `ANTHROPIC_API_KEY`, **or** a pre-existing `~/.claude/.credentials.json` from `claude login`.+* The `http-server` Cargo feature (on by default): OpenHuman exposes its MCP tools to the CLI over a loopback HTTP endpoint (`crate::mcp::server::ensure_local_http`), not by spawning `openhuman-core mcp` as a subprocess. Without that feature, the provider still runs, but the CLI gets no OpenHuman tools.++## Routing a workload through the CLI++The factory grammar accepts a new prefix: `claude-code:<model>[@<temperature>]`. Apply it via the standard inference settings (per-role, locked decision #3):++```bash+# Through the JSON-RPC update endpoint:+openhuman-core rpc openhuman.inference_update_model_settings \+ --json '{"chat_provider":"claude-code:claude-sonnet-4-5"}'+```++| Role string | Field updated |+| -------------------- | -------------------------------- |+| `chat_provider` | foreground chat replies |+| `reasoning_provider` | long-context reasoning workloads |+| `agentic_provider` | multi-step agentic loops |++A workload set to `claude-code:<model>` always spawns a fresh `claude` child per turn; concurrency is capped at `MAX_CONCURRENT_TURNS = 4` per `ClaudeCodeProvider` instance (see [Per-turn behavior](claude-code.md#per-turn-behavior)).++## Verifying the install++The status RPC is on the existing inference namespace:++```bash+openhuman-core rpc openhuman.inference_claude_code_status+```++Returns one of (`CliStatus` in [`tinyagents-harness`'s `claude_code/types.rs`](https://github.com/tinyhumansai/tinyagents/blob/main/crates/tinyagents-harness/src/providers/claude_code/types.rs)):++* `{"status":"ok","version":"2.0.4","path":"/usr/local/bin/claude"}`: ready+* `{"status":"not_installed"}`: no usable `claude` was found through the configured override, `PATH`, or the supported fallback locations+* `{"status":"outdated","version":"1.9.0","min_required":"2.0.0","path":"…"}`: bump CLI+* `{"status":"unusable","path":"…","reason":"…"}`: binary present but the version probe failed++Binary lookup uses this precedence: `OPENHUMAN_CLAUDE_CLI` first, then the `PATH` search, then the ordered fallback locations. The fallback list covers the native installer and common user-local, Bun, npm-global, and Homebrew installations. When the CLI is found through a fallback, its directory and user bin directories are prepended to the child process `PATH`, while the inherited entries remain available.++The same status is rendered in the settings panel via `ClaudeCodeStatusCard` ([`app/src/components/settings/panels/ai/ClaudeCodeStatusCard.tsx`](https://github.com/tinyhumansai/openhuman/blob/main/app/src/components/settings/panels/ai/ClaudeCodeStatusCard.tsx)).++## Per-turn behavior++`ClaudeCodeProvider::run_chat` acquires one of `MAX_CONCURRENT_TURNS` (4) semaphore permits, plus a per-thread mutex so two overlapping calls for the same conversation cannot race on the same session UUID. Each turn then:++1. Resolves a per-thread CC session UUID from `<workspace_dir>/claude-code-sessions.json`. New threads get a fresh RFC-4122 v4 UUID; the CLI requires v4 specifically for `--resume`.+2. Asks the host's `McpEndpointProvider` for an MCP endpoint. OpenHuman's implementation (`OpenHumanMcpEndpoint`) lazily starts one in-process HTTP MCP server per core (`crate::mcp::server::ensure_local_http`, loopback only) and returns its URL plus a bearer token; the config file passed via `--mcp-config` carries that token in its `Authorization` header. If starting the endpoint fails, the turn still proceeds, just without OpenHuman tools.+3. Spawns the CLI with:+ * `-p --input-format stream-json --output-format stream-json --verbose --include-partial-messages --add-dir <project_dir>`+ * `--mcp-config <scratch>/openhuman-mcp-config.json --strict-mcp-config` when the endpoint resolved, so only the configured MCP servers are visible+ * `--permission-mode acceptEdits` (default) or `bypassPermissions` (full access, see below)+ * by default, `--disallowedTools Bash,BashOutput,KillShell,WebFetch,WebSearch,Task`, so CC's own shell, network, and subagent-fanout builtins stay off and OpenHuman tools (`mcp__openhuman__*`) are the only way to reach those capabilities; omitted entirely when full access is on+ * `--session-id <uuid>` on first turn, `--resume <uuid>` thereafter+ * `--model <model>` (the suffix after `claude-code:`)+ * `--append-system-prompt-file <scratch>/append-system-prompt.txt` if the conversation carries a system message (a file, not an argv value, so a large harness prompt does not hit Windows' argv length limit)+4. Pipes stdin: full conversation history folded into a text preamble on a new session, just the pending user turn(s) on `--resume` (the CLI already holds its own prior-turn context server-side).+5. Streams stdout through the JSONL parser, then the event mapper, into `ProviderDelta`s on the request's `stream` sink.++On exit non-zero the driver bubbles stderr (capped at 16 KiB) up as the error message.++On macOS the spawn is wrapped in a Seatbelt jail (`sandbox-exec`) by default when `/usr/bin/sandbox-exec` exists; set `OPENHUMAN_CLAUDE_CODE_SANDBOX=0` to opt out. The profile blocks reads and writes under the first `.openhuman*`-named ancestor of `workspace_dir` (this provider's own session store and settings), not the CLI's own file tools. Linux and Windows have no OS-level wall yet.++### Permission posture and full access++The default posture, `acceptEdits`, restricts CC to file reads and edits under `project_dir` and withholds shell, network, and `Task` fan-out via `--disallowedTools`. A user can opt into full access (CC's entire toolset, including Bash) either through the settings toggle persisted in `<workspace_dir>/claude_code_settings.json`, or with `OPENHUMAN_CLAUDE_CODE_PERMISSION_MODE=bypass|bypassPermissions|full`. This is an explicit user choice; enabling the Claude Code provider alone never grants shell or network access.++## Auth resolution order++1. `ANTHROPIC_API_KEY` env var (highest precedence, set on the spawned child).+2. A host-provided auth-profile store, or Claude Pro/Max OAuth: both still future work.+3. `~/.claude/.credentials.json`: the CLI's own login from `claude login` (Pro/Max subscription), used transparently by simply not setting `ANTHROPIC_API_KEY` on the child, so the CLI reads its own credentials (the Keychain, on macOS, under the `Claude Code-credentials` service).+4. None: the CLI will fail with an auth error.++The `openhuman.inference_claude_code_auth_status` RPC reports the richer state for the Settings → AI panel by spawning `claude auth status --json` (bounded by a 10-second timeout) rather than reading the credentials file directly, since a macOS login lives in the Keychain, not on disk.++## Tool surface exposed to the CLI++The CLI sees these tools as `mcp__openhuman__<name>`, served over the loopback HTTP MCP endpoint described above (the same tool set the stdio MCP server in [`crates/openhuman-core/src/mcp/server/`](../../../../../../crates/openhuman-core/src/mcp/server/) exposes to other MCP clients):++* `core.list_tools`, `core.tool_instructions`+* `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn`, `memory.forget`+* `agent.list_subagents`, `agent.run_subagent` (write, flagged `destructiveHint` per MCP spec)+* `searxng_search`++The MCP server enforces `SecurityPolicy::ToolOperation` checks; `agent.run_subagent`, `memory.learn` and `memory.forget` act (write); the rest are read-only. The CLI's own `tool_use` blocks (its internal Read/Bash/etc. calls) are never surfaced to OpenHuman as harness tool calls: the CLI has already executed them by the time they appear in the stream, so `event_mapper.rs` only strips their argument JSON out of the visible text.++## Limitations (v1)++* Vision input is forwarded as native image blocks when pasted images are available to the Claude Code provider. Images that cannot be read are sent as a short text notice.+* Every role routed to `claude-code:` shares the same `MAX_CONCURRENT_TURNS` semaphore; under load a CC turn waits in queue rather than failing fast.+* Cost accounting from the CLI's `result.total_cost_usd` is captured in the mapper but not yet wired into OpenHuman's billing layer ([`crates/openhuman-core/src/platform/cost/`](../../../../../../crates/openhuman-core/src/platform/cost/)).+* Linux and Windows run the CLI unconfined; the Seatbelt jail is macOS-only.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/developing.md b/docs/gitbooks/docs/gitbooks/en/developing/developing.mdnew file mode 100644index 0000000000..370b4bb748--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/developing.md@@ -0,0 +1,91 @@+---+description: Build, run, test, and ship OpenHuman from source.+icon: code-branch+---++# Overview++OpenHuman is open source under GPLv3 at [github.com/tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman). This section is for contributors and anyone running OpenHuman from source.++If you just want to use the app, head to [Getting Started](../overview/getting-started.md). If you're here to read the architecture, hack on a feature, or land a PR, you're in the right place.++***++## Why the harness is light++Most of what makes OpenHuman fast is a choice made early on: the core is a Rust library, not a set of services talking to each other over sockets. Agents run in-process, so a turn pays for a function call instead of a process boundary or an RPC hop. We've measured 500 agents alive at once in a single process at roughly 1.77 MiB of marginal memory each, cold agent turns land around 100 ms, and a stripped build with only the domains you need can come in at 51 MiB. [Performance](performance.md) has the numbers and how we got them, and the rig that produces them is public at [tinyhumansai/openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks).++Everything above that floor is modular: cargo feature gates decide what compiles in, loadable native modules carry the heavier engines, and the engines themselves, model providers, embeddings, memory, search, are chosen by config rather than baked into the binary. That's what [Pluggable engines](engines.md), [Loadable modules](loadable-modules.md) and [Jev](jev.md) cover.++## Where things live++| Path | What's there |+| ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `app/` | pnpm workspace `openhuman-app`. Vite + React frontend ([`app/src/`](../../../../../../app/src/)) and the Tauri desktop host ([`crates/openhuman-app/`](../../../../../../crates/openhuman-app/)). |+| `crates/` | Rust crates ([overview](https://github.com/tinyhumansai/openhuman/blob/main/crates/README.md)). Six workspace members: `openhuman-core` (package `openhuman`: the core library, domains under `src/<domain>/`, the controller contract and in-process dispatch under `src/core/`; **no binary and no JSON-RPC server**), `openhuman-rpc` (JSON-RPC 2.0 over the core: envelopes, HTTP client, and the server), `openhuman-embed` (the typed library facade), `openhuman-tinyhumans` (the only crate that may depend on `tinyhumans-sdk`: backend transport, hosted RPC proxies, host-side session owner; every host installs it first), `openhuman-cli` (the `openhuman-core` binary and every root `tests/` and `examples/` target), `openhuman-tui` (terminal frontend). Plus `openhuman-app` (the Tauri host), which is excluded from the root workspace and builds from its own manifest. |+| `gitbooks/` | This site (the public-facing docs, [source](../)). |+| `docs/` | Internal maintainer docs: test-coverage matrix, release smoke checklist, library benchmarking and minimal-recipe notes, translated READMEs, `community/` ([`docs/`](../../../../../)). |++[`AGENTS.md`](https://github.com/tinyhumansai/openhuman/blob/main/AGENTS.md) at the repo root is the source of truth for AI agents working on the codebase ([`CLAUDE.md`](https://github.com/tinyhumansai/openhuman/blob/main/CLAUDE.md) is a symlink to it). Same rules apply to humans.++***++## Start here++If it's your first time pulling the repo:++1. [**Getting Set Up**](getting-set-up.md). Toolchain, dependencies, the Tauri CLI, everything `pnpm dev` needs to actually start.+2. [**Building the Rust Core**](building-rust-core.md). Fresh-machine setup for the Rust workspace only: pinned toolchain, OS packages, and exact `cargo` commands.+3. [**Architecture**](architecture/architecture.md) (with the [overview](architecture/)). How the desktop app, the in-process Rust core, the JSON-RPC bridge, and the dual sockets fit together. Read this before you make non-trivial changes.+4. [**Frontend**](architecture/frontend.md) and [**Tauri Shell**](architecture/tauri-shell.md). The React app and the desktop host that wraps it.+5. [**MCP Server**](mcp-server.md). Opt-in stdio MCP mode for exposing read-only OpenHuman memory tools to local clients.++***++## The core, in depth++* [**Performance**](performance.md). What "light and fast" means in numbers: memory per agent, cold-start timing, binary size, and how the benchmarks are run. Raw rigs and results live in the public [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks) repo.+* [**Pluggable engines**](engines.md). How the LLM, embeddings, memory, and web search layers are chosen by config, and what's available for each.+* [**Jev**](jev.md). The fast probability model behind tool selection and routine browser decisions, and why it beats brute-force retrieval on both speed and accuracy.+* [**Embedding OpenHuman**](embedding.md) (see also [`crates/openhuman-embed`](../../../../../../crates/openhuman-embed/)). Using `openhuman-embed` to run the core, and any number of agents on it, inside another Rust product.+* [**One TinyHumans API key**](tinyhumans-api-key.md). What a single key unlocks: managed inference, embeddings, web search, media, integrations, voice, and Jev.++***++## Testing++OpenHuman ships with three test layers. Know which one your change belongs in (the Rust integration targets are described in [`tests/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/tests/README.md), the helper scripts in [`scripts/README.md`](https://github.com/tinyhumansai/openhuman/blob/main/scripts/README.md)):++* [**Testing Strategy**](testing-strategy.md). When to write Vitest vs cargo tests vs WDIO.+* [**E2E Testing**](e2e-testing.md). WDIO/Appium specs, dual-platform setup (Linux tauri-driver, macOS Appium Mac2), and how to run a single spec locally.+* [**Agent Observability**](agent-observability.md). The artifact-capture layer that makes E2E and agent runs debuggable after the fact.++PRs must clear the **≥ 80% coverage on changed lines** gate. Add tests for new behavior, not just the happy path.++***++## Shipping++* [**Release Policy**](release-policy.md). Version policy, release cadence, OAuth + installer rules.+* [**Cloud Deploy**](../features/cloud-deploy.md). Backend/cloud-side deployment when a change crosses the desktop boundary.++***++## Going deeper++* [**Agent Harness**](architecture/agent-harness.md). The tinyagents-based turn loop (checkpointing, circuit breakers, sub-agent handback, journals/replay) and how to extend the tool surface.+* [**Workflows**](../features/workflows.md). The tinyflows-backed `flows` domain: triggers, trust origins, approval-gated runs, and the `flows_*` RPC surface.+* [**Loadable modules**](loadable-modules.md). Native `cdylib` modules the core loads at runtime, and how they are admitted.+* [**Hooks**](hooks.md). User-owned scripts that run before a tool executes, after a file edit, or when a turn finishes.+* [**Chromium Embedded Framework**](cef.md). Historical design notes from the CEF era; the shell now runs on stock Tauri (Wry).++***++## Contributing++* Open issues and PRs at [tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman). The [`vendor/`](../../../../../../vendor/) submodules (tinyagents, tinymemory and friends) have their own repos under [tinyhumansai](https://github.com/tinyhumansai).+* PRs target `main`. Push to your fork, not upstream.+* Follow [`CONTRIBUTING.md`](https://github.com/tinyhumansai/openhuman/blob/main/CONTRIBUTING.md) and the issue/PR templates.+* Keep changes focused. A bug fix doesn't need surrounding cleanup; a one-shot operation doesn't need a helper.++Help building toward AGI doesn't have to mean shipping a kernel, bugfixes, docs, integrations, and tests all move the bar.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/e2e-testing.md b/docs/gitbooks/docs/gitbooks/en/developing/e2e-testing.mdnew file mode 100644index 0000000000..154d093000--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/e2e-testing.md@@ -0,0 +1,305 @@+---+description: >-+ The desktop and web end-to-end suites: the WDIO and tauri-driver harness,+ how to run a spec locally or in Docker, the environment variables each lane+ reads, and which lanes actually execute in CI.+icon: vials+---++# E2E Testing++End-to-end coverage runs in three lanes: a Rust mock-backend suite, a+Playwright web suite, and a desktop suite driven through `tauri-driver`. Only+the Linux desktop harness runs on a schedule; macOS and Windows are manual.++## Overview++Desktop E2E tests use **WebDriverIO (WDIO)** to drive the app through a single `tauri-driver` (WebDriver) session against its native Wry/WebKit webview:++| Platform | Driver | Port | App format | Selectors |+| --------- | ------------------------------ | ---- | ------------ | --------- |+| **Linux** | tauri-driver + WebKitWebDriver | 4444 | Debug binary | CSS / DOM |++The app moved from CEF to Tauri's native Wry webview in #5456. The old Appium Chromium-driver backend attached over CEF's remote-debugging port; CDP only exists under a Chromium engine, so that backend was removed in #5478 along with CEF itself. Linux CI now drives the debug binary under Xvfb through `tauri-driver`. macOS and Windows have no automated desktop E2E coverage until a native driver (Appium Mac2 / WinAppDriver) replaces the removed one; that work is tracked in #5485. `pnpm --filter openhuman-app test:e2e:build` still produces a `.app` bundle on macOS for manual testing, but there is no supported automated session there yet.++---++## Quick start++### Linux++```bash+# Build the E2E app+pnpm --filter openhuman-app test:e2e:build++# Run every spec in one shared tauri-driver session+pnpm --filter openhuman-app test:e2e:session++# Run all flows, sharded by suite category+pnpm --filter openhuman-app test:e2e:all:flows++# Run a single spec+bash app/scripts/e2e-run-spec.sh test/e2e/specs/smoke.spec.ts smoke+```++`app/scripts/e2e-run-session.sh` starts `tauri-driver` on `TAURI_DRIVER_PORT`+(default `4444`) with `WebKitWebDriver` as its native driver, waits for its+`/status` endpoint, then runs WDIO against `app/test/wdio.conf.ts`. On+headless Linux the app itself runs under **Xvfb** for a virtual display; the+driver process does not need one.++### Docker on macOS (Linux harness locally)++Run the same Linux-based harness from macOS using Docker.++```bash+# Build + run all E2E flows+docker compose -f e2e/docker-compose.yml run --rm e2e++# Build the app first (if needed)+docker compose -f e2e/docker-compose.yml run --rm e2e \+ pnpm --filter openhuman-app test:e2e:build++# Run a single spec+docker compose -f e2e/docker-compose.yml run --rm e2e \+ bash app/scripts/e2e-run-spec.sh test/e2e/specs/smoke.spec.ts smoke+```++Requires Docker Desktop or Colima. The repo is bind-mounted so builds persist between runs.++---++## Architecture++### Platform detection++`app/test/e2e/helpers/platform.ts` now exports two functions, both hardcoded+to `true`: `isTauriDriver()` and `supportsExecuteScript()`. They date from an+earlier harness split between an accessibility-tree macOS driver and a+DOM-based Linux driver. Every session today exposes the WebView DOM and+supports `browser.execute()`, so specs that still branch on either check+always take the DOM-capable path. Treat them as compatibility shims, not+active platform detection.++### Element helpers++`app/test/e2e/helpers/element-helpers.ts` provides a unified API over the WebView DOM:++| Helper | Behavior |+| ------------------------- | -------------------------------------------- |+| `waitForText(text)` | XPath over DOM text content |+| `waitForButton(text)` | `button` / `[role="button"]` XPath |+| `clickText(text)` | Standard `el.click()` |+| `clickNativeButton(text)` | Standard `el.click()` on button |+| `clickToggle()` | `[role="switch"]` / `input[type="checkbox"]` |+| `waitForWindowVisible()` | Window handle check |+| `waitForWebView()` | `document.readyState` check |+| `hasAppChrome()` | Window handle check |+| `dumpAccessibilityTree()` | HTML page source |++### Stable test IDs++Prefer stable `data-testid` hooks for UI affordances that E2E specs click or poll. Use the taxonomy `<surface>-<element>-<id?>`, for example:++- `cron-jobs-panel`, `cron-refresh`+- `cron-job-row-<jobId>`, `cron-job-toggle-<jobId>`, `cron-job-run-<jobId>`, `cron-job-view-runs-<jobId>`, `cron-job-remove-<jobId>`+- `settings-nav-<routeId>`+- `skill-row-<skillId>`, `skill-install-<skillId>`, `skill-uninstall-<skillId>`+- `thread-row-<threadId>`, `new-thread-button`, `send-message-button`+- `onboarding-next-button`++Use `waitForTestId(testId)` and `clickTestId(testId)` from `element-helpers.ts` when a spec targets one of these hooks. Keep text selectors for user-visible copy assertions, not row/action discovery.++### Deep link helpers++`app/test/e2e/helpers/deep-link-helpers.ts` handles auth deep links:++- **Primary path**: `browser.execute(window.__simulateDeepLink(url))`, which works against the WebView on every platform tauri-driver supports.+- **macOS-only fallbacks** (unexercised by CI today, since macOS has no automated desktop session): the `macos: deepLink` extension command, then `open -a ...`.+- Linux has no shell fallback: `xdg-open openhuman://...` needs a `.desktop` file registering the URL scheme, which the CI container does not have, so `triggerDeepLink` throws immediately if the WebView simulate call fails there.++For release candidates, also run one manual secondary-instance smoke on Linux+or macOS when touching single-instance or deep-link startup code (this+exercises `tauri-plugin-single-instance`, which OpenHuman registers with the+`deep-link` feature):++1. Launch OpenHuman normally and leave it running.+2. Trigger `openhuman://auth?token=e2e-token&key=auth` through the OS opener.+3. Confirm the already-running window receives the callback instead of a+ second app instance starting.+4. Confirm the secondary process exits cleanly.++This catches regressions where a second instance starts (or exits with an+error) before Tauri's deep-link forwarding path is installed.++### Writing cross-platform specs++1. **Use helpers** from `element-helpers.ts`, never use raw `XCUIElementType*` selectors in specs+2. **Use `clickNativeButton(text)`** instead of inline button-clicking code+3. **Use `hasAppChrome()`** instead of checking for `XCUIElementTypeMenuBar`+4. **Use `waitForWebView()`** instead of checking for `XCUIElementTypeWebView`+5. For macOS-only tests, use `process.platform` guards or separate spec files+6. Use `navigateViaHash(route)` for hash routes; it waits for the hash,+ `document.readyState`, and a mounted React root before returning. After+ onboarding, `walkOnboarding()` also waits for `#/home` plus a Home-page+ marker before specs navigate elsewhere.++---++## Environment variables++| Variable | Default | Description |+| --------------------------- | ---------- | ---------------------------------------------------------------------- |+| `TAURI_DRIVER_PORT` | `4444` | Port `tauri-driver` listens on; `wdio.conf.ts` connects here |+| `E2E_MOCK_PORT` | `18473` | Mock backend server port |+| `E2E_PORT_BASE` | unset | Web lane port block: mock `base`, core `base+1`, web host `base+2` |+| `OPENHUMAN_WORKSPACE` | (temp dir) | App workspace directory |+| `OPENHUMAN_SERVICE_MOCK` | `0` | Enable service mock mode |+| `OPENHUMAN_E2E_MODE` | unset | Enables destructive test-support RPCs; the E2E runner sets this to `1` |+| `OPENHUMAN_E2E_AUTH_BYPASS` | unset | Enable JWT bypass auth |+| `DEBUG_E2E_DEEPLINK` | (verbose) | Set to `0` to silence deep link logs |+| `E2E_FORCE_CARGO_CLEAN` | unset | Force cargo clean before E2E build |++Two web E2E sessions on one machine need separate ports. The lane refuses to+start when any of its three ports is already listening, because its readiness+probes are ordinary HTTP GETs that the other session's mock, core and web host+answer just as happily, and `openhuman-core run` falls back to a neighbouring+port rather than exiting, so it would stay alive on a port nothing probes+(#5918). Set `E2E_PORT_BASE` for the build and the run alike: the mock and core+ports are compiled into the bundle and cannot be changed afterwards (#6478).++```bash+E2E_PORT_BASE=31000 pnpm --filter openhuman-app test:e2e:web+```++---++## CI workflows++### Push / PR checks++The default pull-request gate is `.github/workflows/ci-fast.yml`: quality+checks plus the complete unit-test suites for each changed area. No E2E suite+runs on a pull request to `main`.++`.github/workflows/ci-full.yml` runs on pull requests targeting `release` and+on every push to it, and carries three E2E lanes:++| Lane | Job | Platform |+| --- | --- | --- |+| Rust mock backend | `rust-e2e` | Linux |+| Playwright web | `playwright-e2e` | Linux |+| Desktop | `e2e-desktop`, via `e2e-reusable.yml` | Linux only |++The desktop lane calls the reusable workflow with `run_linux: true`,+`run_macos: false` and `run_windows: false`, so only the Linux harness+executes. The job's "3 OS" title names the matrix the reusable workflow is+able to run, not the one CI Full asks for.++macOS and Windows desktop E2E therefore have no scheduled coverage on any+branch. `.github/workflows/e2e.yml` is a manual dispatch whose `run_macos` and+`run_windows` inputs default to `false` as well, so someone has to opt in+explicitly to get cross-platform desktop signal before a promotion. Both stay+off until #5485 lands a native driver for each platform.++---++## Troubleshooting++### Linux: "WebView not ready" timeout++This usually means `tauri-driver` never reached its `/status` endpoint, or the app crashed before mounting its WebView. Use `app/scripts/e2e-run-session.sh`, which starts `tauri-driver` and waits on that endpoint before invoking WDIO, rather than driving the app by hand.++Ensure `DISPLAY` is set and Xvfb is running:++```bash+export DISPLAY=:99+Xvfb :99 -screen 0 1280x1024x24 &+```++Also ensure dbus is started (required by webkit2gtk):++```bash+eval $(dbus-launch --sh-syntax)+```++### Linux: `tauri-driver` or `WebKitWebDriver` not found++Install `tauri-driver` with `cargo install tauri-driver`, and make sure `WebKitWebDriver` is on `PATH` (on Debian/Ubuntu it ships in `webkit2gtk-driver`) or point `WEBKIT_WEBDRIVER` at its location; `e2e-run-session.sh` defaults to `/usr/bin/WebKitWebDriver`.++### macOS: Deep links not working in `tauri dev`++Deep links require a `.app` bundle. Use `pnpm tauri build --debug --bundles app` instead.++### Docker: Build is slow on first run++The first Docker build compiles Rust and installs the E2E harness dependencies. Subsequent runs use cached layers. Cargo registry and git sources are cached via Docker volumes.++## Spec: Notifications++**File**: `app/test/e2e/specs/notifications.spec.ts`++Tests notification RPC methods via the in-process core and the Notifications UI page:++- `notification_ingest`, creates a new notification via core RPC+- `notification_list`, verifies the ingested notification is returned+- `notification_mark_read`, marks a notification as read+- `notification_stats`, checks aggregate statistics shape+- UI: Notifications page renders the integration notifications section (`[data-testid="integration-notifications-section"]`)+- UI: Notifications page shows the System Events section (`[data-testid="system-events-section"]`)++**Run**:++```bash+bash app/scripts/e2e-run-spec.sh test/e2e/specs/notifications.spec.ts notifications+```++**Platform note**: both the RPC calls and the UI assertions in this spec run inside the same `tauri-driver` session, which supports `browser.execute()`.++---++## Agent-observable artifact flow++### Starting a composer test++Chat drafts persist per thread. Before a spec types its initial prompt, call+`replaceChatComposerText(input, prompt)` from+`app/test/playwright/helpers/chat-composer.ts`. It selects and deletes the+restored draft, waits for the empty value, types through keyboard events, and+checks the exact prompt. Use `clearChatComposer(input)` when a case needs an+empty composer. These helpers support both textarea and Lexical surfaces.++Cases that exercise draft restoration or append a follow-up should keep their+draft and drive that behavior explicitly. The helper's browser regressions live+in `app/test/playwright/specs/chat-composer-helper.spec.ts`.++For a canonical, inspectable run that drops screenshots, page-source dumps, and mock request logs on disk:++```bash+bash app/scripts/e2e-agent-review.sh+```++Artifacts land in `app/test/e2e/artifacts/<timestamp>-agent-review/`. Full details + helper API: [`agent-observability.md`](agent-observability.md). Any failing test triggers `wdio.conf.ts`'s `afterTest` hook, which writes `failure-*.png` + `failure-*.source.xml` into the same run dir.++---++## Rust inference provider E2E++These tests (`tests/inference_provider_e2e.rs`) use **wiremock** to mock HTTP upstreams and require no live LLM API calls. They cover OpenAI-compat chat, Anthropic auth style, per-model temperature suppression, Ollama local provider, and the `/v1` HTTP endpoint auth layer.++```bash+# Local:+bash scripts/test-rust-inference-e2e.sh++# Via Docker (Linux, same image as CI):+docker compose -f e2e/docker-compose.yml run --rm inference-e2e+```++---++## See also++- [Testing strategy](testing-strategy.md): which layer a given test belongs in.+- [Agent observability](agent-observability.md): the artifact flow the review run writes to.+- [Tauri shell](architecture/tauri-shell.md): the Wry webview `tauri-driver` attaches to.+- [Building and installing OpenHuman](getting-set-up.md): toolchain and submodules a local E2E build needs.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/embedding.md b/docs/gitbooks/docs/gitbooks/en/developing/embedding.mdnew file mode 100644index 0000000000..7aea352430--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/embedding.md@@ -0,0 +1,451 @@+---+description: >-+ Embedding the core in another Rust process: one Runtime, any number of+ independently configured Agents on it.+icon: code+---++# Embedding OpenHuman++`openhuman-embed` is a typed Rust library for running the OpenHuman core+in-process inside another product. It is the same core that ships in the+desktop app and the CLI, minus the Tauri shell and the RPC server: business+rules, agent turns, memory, tools and sandboxing, called directly from your+own binary.++## Adding the dependency++Use the default contributor feature set:++```toml+[dependencies]+openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed" }+```++Or select a narrower build:++```toml+[dependencies]+openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed", default-features = false, features = ["inference", "mcp"] }+```++Every feature on this crate forwards to the same-named feature on+`openhuman-core`: `default`, `http-server`, `inference`, `documents`,+`hosting`, `modules`, `voice`, `web3`, `runtime-node`, `media`,+`flows`, `skills`, `mcp`, `crash-reporting`, `channels`,+`whatsapp-web`, `file-logging`, `scheduler-gate` (eighteen entries including+`default`). Two of them also gate+items on this crate's own surface: `mcp` gates `HttpHeader`,+`McpAuthConfig`, `McpServer`, `AgentSpec::mcp` and `HarnessBuilder::mcp`;+`skills` gates `AgentSpec::skills_dir` and `HarnessBuilder::skills_dir`.++Set your product's identity once at startup, before building any client:++```rust+use openhuman_embed::{set_product_identity, ProductIdentity};++if let Some(identity) = ProductIdentity::new("opencompany") {+ set_product_identity(identity);+}+```++## Two steps: a Runtime, then any number of Agents++The library API has two levels. First, one `Runtime` for the process:+features, background services, backend URL, the TinyHumans API key. Then+any number of independently configured agents on it, each with its own+provider, access tier, working directory, MCP servers and skills.++```rust,no_run+use openhuman_embed::{Access, AgentSpec, McpServer, Provider, Runtime, Workspace};++# async fn demo() -> Result<(), Box<dyn std::error::Error>> {+let runtime = Runtime::builder()+ .workspace(Workspace::dir("/var/lib/my-product/openhuman"))+ .api_key("th_live_...") // the only credential in library mode+ .build()+ .await?;++let reviewer = runtime.agent(+ AgentSpec::new("reviewer")+ .system_prompt("You review pull requests and never edit files.")+ .access(Access::readonly())+ .skills_dir("./skills/review") // copied into this agent's own skills root+ .action_dir("/srv/checkouts/pr-42"),+)?;++let fixer = runtime.agent(+ AgentSpec::new("fixer")+ .provider(Provider::openai_compatible("https://api.example/v1", "sk-...").model("gpt-5"))+ .access(Access::full())+ .mcp(McpServer::stdio("github", "gh-mcp", ["stdio"]))+ .action_dir("/srv/checkouts/pr-42"),+)?;++let review = reviewer.run("Summarise the risks in this change.").await?;+let fix = fixer+ .turn(format!("Address these findings:\n{}", review.reply))+ .send()+ .await?;+println!("{}", fix.reply);++// Continue a conversation with the same agent.+let again = fixer.turn("Now run the tests.").session(&fix.session_id).send().await?;+println!("{}", again.reply);+# Ok(())+# }+```++An agent owns its provider and model, its access tier and turn origin, its+`action_dir`, its MCP servers, its skills root+(`<workspace>/agents/<id>/skills/`), its system prompt, its tool scope and+sandbox mode, and a narrowed domain set or tool-group list. Every turn+dispatches under that agent's own context, so config, domain gating,+tool-group filtering and skill discovery all read that agent's settings and+never another agent's. Transcripts are keyed by agent id, and a turn resumes+only its own thread.++The runtime owns the workspace and credential store, the event bus, the+keyring, background services, the registered domain set (agents can only+narrow it, so enable `mcp` or `skills` at runtime build time if any agent+needs them), and the API key.++Layout under a runtime-owned root:++```text+<root>/config.toml, auth-profiles.json, core.token+<root>/workspace/session_db/, session_raw/<session_key>.<agent>[.g<n>].jsonl, agents/<agent>/skills/+<root>/agents/<agent>/action/ default action_dir+```++## AgentSpec++`AgentSpec::new(id)` starts from the built-in orchestrator's definition+(prompt, tools, delegation) applied to a fresh id, except every registered+tool is visible by default (`ToolScopeSpec::Wildcard`) rather than the+desktop's own narrower set. Chain builder methods to override:++- `.system_prompt(text)` and `.definition(spec)` for the prompt, tool scope,+ disallowed tools, sandbox mode, iteration cap, temperature, display name+ and delegation blurb (`AgentDefinitionSpec`).+- `.provider(Provider)` / `.model(id)` for which model answers and where.+- `.access(Access)` for what the agent may do.+- `.tool_groups(ToolGroups)` and `.domains(DomainSet)` to narrow further,+ never wider than the runtime's own set.+- `.mcp(McpServer)` (repeatable) for MCP servers only this agent can call.+- `.skills_dir(path)` to copy skill bundles into this agent's own root.+- `.include_user_skills(bool)` to also let the agent see the operator's+ `~/.openhuman/skills` (off by default).+- `.action_dir(path)` for the agent's read/write root.+- `.trust(path, access)` to grant a directory outside `action_dir`.+- `.tools(factory)` to hand the agent real in-process tools built fresh per+ turn, rather than routing host callbacks through an MCP server.+- `.config(f)` as an escape hatch for config fields the spec does not model.++Agent ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`; avoid the built-in ids+(`orchestrator`, `summarizer`, ...), which the runtime-wide delegation+catalog resolves to the shipped definitions.++## Access tiers++`Access` sets two things together on purpose: the autonomy tier that drives+the security policy, and the turn origin the approval gate checks. Setting+only the tier produces an agent whose shell, edit and exec tools all+silently refuse, which reads as a weak model rather than a missing scope.++- `Access::readonly()`: observe only, no writes, no shell, no network side+ effects. Safe default for an untrusted prompt.+- `Access::supervised()`: act, but park risky operations for a human+ decision. Unlike the desktop default, this **turns the autonomy policy on**+ for that agent (`Access` sets the policy flag as well as the tier), so the+ approval gate really is live and an unattended harness stalls here until an+ approval answers or the ten-minute TTL denies it. The user-facing default is+ the opposite: `[autonomy] enabled = false`, where the gate is inert. See+ [Approval Gate](../features/approval-gate.md).+- `Access::full()`: act autonomously, no approval pauses. Grants real shell+ and file access under `action_dir`; point it at a directory you are+ willing to have changed. Hard blocks still apply regardless of tier:+ credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and the workspace's own+ internal state stay off limits.++`.trust(path, access)` grants a directory outside the action root, and+`.allow_tool_install(bool)` opts into OS package installation, off in every+preset including `full()` because it reaches outside the action directory+that otherwise bounds the blast radius.++## Provider: BYOK or managed++`Provider::inherit()` uses whatever inference the runtime or the machine is+already configured with: the account's managed backend, a local Ollama or+LM Studio, or a configured BYOK provider. `Provider::openai_compatible(url,+key)` points a turn at a specific OpenAI-compatible endpoint and bearer;+`/chat/completions` is appended to `url`, so pass the API root. `.model(id)`+pins the model id on either; it is advisory, since a model no configured+provider serves falls back rather than erroring.++An agent that names its own `Provider` never touches the runtime's API key.+One that names none inherits the runtime's default: managed inference on+the API key when one was supplied, or the machine's own configuration+otherwise.++## Workspace++`Workspace::Ephemeral` (the default) is a throwaway directory removed when+the harness or runtime drops; nothing here touches a real install, and+sessions do not survive the process. `Workspace::dir(path)` is a+caller-owned directory that persists across runs. `Workspace::Inherit`+reuses the machine's configured OpenHuman workspace, the same one the+desktop app and CLI use, resolved the usual way+(`OPENHUMAN_WORKSPACE`, `active_user.toml`, `~/.openhuman/...`); an inherited+workspace is the operator's, so the harness will not copy skills into it.++`Workspace::stateless()` keeps nothing durable on disk: every agent's+transcripts, turn journal, run status, goals and todos go through the+runtime's session store (`RuntimeBuilder::session_store`, required), a+`SessionStoreProvider` the host implements over its own database and scopes+by agent id. It is the shape for a cloud host serving many users from one+process; see the embed crate's README, "Conversations in a host store".++## Tool scopes and sandbox modes++`AgentDefinitionSpec::tools(ToolScopeSpec::Wildcard)` exposes every+registered tool (the default); `ToolScopeSpec::Named(vec![...])` restricts+an agent to exactly those tool names, dropping unknown ones at build time.+`.disallow_tools([...])` hides specific tools even when the scope would+include them.++`SandboxModeSpec` confines an agent's shell and file tools:++- `SandboxModeSpec::None` (default): only the access tier and path policy+ apply.+- `SandboxModeSpec::ReadOnly`: write and execute tools are filtered out+ entirely.+- `SandboxModeSpec::Sandboxed`: commands run under the platform jail or+ Docker backend.++## MCP servers++`McpServer::stdio(name, command, args)` launches a local subprocess+speaking newline-delimited JSON-RPC; `McpServer::http(name, endpoint)`+reaches a remote server over Streamable HTTP. Both support `.env(...)` or+`.auth(McpAuthConfig)`, `.allow_tools([...])` / `.deny_tools([...])` to+narrow which remote tools an agent sees (worth setting for a large server,+since every exposed tool costs prompt budget), `.timeout_secs(n)` and+`.description(text)`. Servers declared through `AgentSpec::mcp` are private+to that agent; other agents on the same runtime do not see them. Servers are+fixed at build time: there is no way to add one to a running harness.++## Skills++`AgentSpec::skills_dir(dir)` copies skill bundles into+`<workspace>/agents/<id>/skills/`, visible only to that agent. Bundles are+copied rather than symlinked because skill discovery rejects symlinked+bundles. `.include_user_skills(true)` additionally lets the agent discover+skills the operator installed under `~/.openhuman/skills`; the default+hides them, since an embedded agent should see what its host installed, not+what the machine's user did.++## Multi-turn sessions and progress streaming++`agent.turn(message)` returns a builder. `.session(id)` continues an+existing conversation; without it a fresh session id is minted and returned+on `TurnOutcome::session_id`. `.model(id)` and `.temperature(t)` override+those settings for one turn. `.cwd(dir)` roots that turn's filesystem and+shell tools somewhere other than the agent's configured `action_dir`.+`.route(Route)` sends one turn to a specific endpoint instead of the+account's configured route. `.origin(AgentTurnOrigin)` states the calling+authority explicitly, for a turn that is not a human at a terminal, such as+a workflow node or a scheduled job.++`.on_progress(sender)` streams tool calls, deltas and turn boundaries as+they happen. The core awaits every send, so the channel is real+backpressure: a receiver that stops draining stalls the turn.++```rust,no_run+# use openhuman_embed::Agent;+# async fn go(agent: &Agent) -> anyhow::Result<()> {+let (tx, mut rx) = tokio::sync::mpsc::channel(256);+let printer = tokio::spawn(async move {+ while let Some(progress) = rx.recv().await {+ eprintln!("[progress] {progress:?}");+ }+});+let outcome = agent.turn("go").on_progress(tx).send().await?;+let _ = tokio::time::timeout(std::time::Duration::from_secs(30), printer).await;+println!("{}", outcome.reply);+# Ok(()) }+```++`.seed(history)` replaces a session's history for one turn with the caller's+own rows (`(role, content)` pairs) rather than reading the transcript; only+a runtime-owned `Agent` can honour it, since it silently discards whatever+that session held, and it is meant to be paired with a session id the turn+is not sharing with turns that expect their history intact. `.meter(f)`+reports what a turn spent, including a turn that ran and then failed.++## Harness: the one-agent shorthand++`Harness` is a `Runtime` plus exactly one agent, built from one set of+inputs, for a host that only ever needs one:++```rust,no_run+use openhuman_embed::{Access, Harness, Provider, Workspace};++# async fn demo() -> Result<(), Box<dyn std::error::Error>> {+let harness = Harness::builder()+ .provider(Provider::openai_compatible("https://api.example/v1", "sk-...").model("gpt-5"))+ .workspace(Workspace::Ephemeral)+ .access(Access::readonly())+ .build()+ .await?;++let first = harness.run("Summarize what you can see.").await?;+let second = harness+ .turn("Now list the risks.")+ .session(&first.session_id)+ .send()+ .await?;+println!("{}", second.reply);+# Ok(())+# }+```++`harness.runtime()` and `harness.agent()` hand out the underlying `Runtime`+and `Agent`, so a host that outgrows one agent adds more on the same+runtime rather than rebuilding.++## Connecting to the hosted backend++`openhuman-embed` alone installs no backend transport: agents, memory,+skills, tools and RPC all run, and every hosted-backend surface (billing,+integration tools, channel relay, cloud voice) answers with a typed+`BACKEND_UNAVAILABLE:` error. `openhuman-tinyhumans::RuntimeBuilder` mirrors+`openhuman_embed::RuntimeBuilder` method for method and installs the+SDK-backed transport on `build()`:++```rust+use openhuman_tinyhumans::{embed::Workspace, RuntimeBuilder};++let runtime = RuntimeBuilder::new()+ .workspace(Workspace::Ephemeral)+ .api_key("th_...")+ .build()+ .await?;+```++Hosts that boot the core themselves rather than through either builder (the+desktop shell, the TUI, the CLI, test fixtures) call `install` once before+the first backend-touching dispatch:++```rust+openhuman_tinyhumans::install(openhuman_tinyhumans::InstallOptions::default())?;+```++That call also registers the seven hosted RPC proxy domains (billing, team,+referral, announcements, webhooks, channel linking and backend-brokered OAuth)+into the core's controller registry. See+[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans+API key unlocks once it is installed this way.++## Library mode has no user login++`RuntimeBuilder::api_key` installs a TinyHumans API key into the runtime's+credential store before the core boots. Managed inference then sends it as+`Authorization: Bearer <key>` to the TinyHumans endpoint, backend REST calls+send it as `x-api-key`, and the scheduler gate treats the runtime as signed+in. There is no `/auth/me` round trip, no session JWT, nothing to expire. An+agent that names its own `Provider` never touches the key at all.++## One runtime per process++The keyring master key, the RPC bearer, the global event bus and the+process's domain subscribers are process-scoped, so a second runtime would+silently share them while believing it had a separate workspace.+`RuntimeBuilder::build` returns `RuntimeError::AlreadyRunning` instead;+agents, not runtimes, are the unit of multiplicity within one process.++Build the tokio runtime yourself rather than using `#[tokio::main]`. A turn+is a large async state machine, and a sub-agent nesting inside it overflows+tokio's default 2 MiB worker stack:++```rust,no_run+use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};++let runtime = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .thread_stack_size(AGENT_WORKER_STACK_BYTES)+ .max_blocking_threads(MAX_BLOCKING_THREADS)+ .build()+ .expect("tokio runtime");+```++## A narrow build, measured++`docs/library-minimal-recipe.md` measures a headless recipe aimed at+100 to 1,000 live agents on a 2 GB RAM / 2 vCPU box:++```bash+cargo build --release \+ -p openhuman-embed \+ --no-default-features --features "skills,flows"+```++Stripped binary size: 51.0 MiB with no optional gates at all, about 60.4 MiB+with `skills,flows` enabled (the recipe above), against 115.9 MiB unstripped+with every gate on. See [Performance](performance.md) for how that build+size relates to per-agent memory and cold-start time when many agents share+one process.++## Examples to run++Against any OpenAI-compatible endpoint:++```bash+OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \+OPENHUMAN_EXAMPLE_API_KEY=sk-... \+OPENHUMAN_EXAMPLE_MODEL=gpt-5 \+ cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"+```++Or against the machine's own configured inference, in its real workspace:++```bash+OPENHUMAN_EXAMPLE_INHERIT=1 cargo run -p openhuman-embed --example run_turn -- "Hello."+```++Two agents on one runtime, BYOK or managed:++```bash+OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \+OPENHUMAN_EXAMPLE_API_KEY=sk-... \+OPENHUMAN_EXAMPLE_MODEL=gpt-5 \+ cargo run -p openhuman-embed --example two_agents -- "Describe this directory."++OPENHUMAN_EXAMPLE_TINYHUMANS_API_KEY=th_... \+ cargo run -p openhuman-embed --example two_agents -- "Describe this directory."+```++`OPENHUMAN_EXAMPLE_BACKEND_URL` points non-inference backend calls+somewhere specific, and `OPENHUMAN_EXAMPLE_SKILLS_DIR` supplies skill+bundles. The repository-root `examples/embed_headless.rs` and+`examples/embed_kernel.rs` drive `CoreBuilder` from `openhuman-core`+directly, without this crate; run them with `cargo run --example+embed_headless`.++Tests worth reading alongside the examples, all under+`crates/openhuman-embed/tests/`: `harness_embed.rs` proves+`Harness` runs a real turn against a mocked provider with nothing else+bound; `runtime_agents.rs` runs three agents with different+providers, access tiers, skills, MCP servers and working directories on one+runtime; `public_api.rs` pins the host-facing embedding contract at+compile time. Run them with:++```bash+cargo test -p openhuman-embed --features inference,mcp,skills+```++See also: [Jev](jev.md) for the decision model an embedded agent's tool+search can use, [Pluggable engines](engines.md) for the inference, memory+and search backends an agent chooses by config, and+[One API key for everything](tinyhumans-api-key.md) for what a TinyHumans+API key unlocks in library mode.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/engines.md b/docs/gitbooks/docs/gitbooks/en/developing/engines.mdnew file mode 100644index 0000000000..d6129d79ed--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/engines.md@@ -0,0 +1,133 @@+---+description: >-+ The four swappable engine families (models, embeddings, memory, search) and+ how each one is selected by config rather than code.+icon: gears+---++# Pluggable engines++OpenHuman routes four kinds of work, chat and reasoning, embeddings, memory,+and web search, through a config key rather than a hardcoded client. Each has+a managed default that needs no key, plus a bring-your-own-key or local path.+This page is the map of what's supported and the exact key or environment+variable that selects it; the linked pages under Features cover setup and+tradeoffs.++## LLM providers++Chat, reasoning, vision, and coding workloads route through per-workload+provider fields (`chat_provider`, `reasoning_provider`, `agentic_provider`,+`coding_provider`, `vision_provider`, and more), each a string of the form+`<slug>:<model>`. Leaving a field unset, blank, or set to `cloud` keeps it on+the managed default.++Supported routes:++- **Managed (TinyHumans)**: the default. Access to the OpenRouter model+ catalogue with no key to manage.+- **Local**: a runtime the user installs and runs (Ollama, LM Studio, MLX,+ OMLX), addressed as `ollama:<model>`, `lmstudio:<model>`, `mlx:<model>` or+ `omlx:<model>`, with the endpoint in `[local_ai] base_url`. OpenHuman does+ not install the runtime or download models; the user pulls them.+- **A local OpenAI-compatible endpoint**: any server that speaks the OpenAI+ chat API, as `local-openai:<model>` or registered with its own slug and+ endpoint.+- **Claude Code / Claude Agent SDK**: a provider slug that shells out to an+ installed Claude Code CLI instead of calling a hosted API.+- **26 BYOK slugs**, each shipped with a preset endpoint so only a key is+ needed: `openai`, `anthropic`, `google`, `openrouter`, `orcarouter`, `groq`,+ `mistral`, `deepseek`, `together`, `fireworks`, `cerebras`, `xai`,+ `moonshot`, `gmi`, `huggingface`, `nvidia`, `zai`, `minimax`, `stepfun`,+ `kilocode`, `deepinfra`, `novita`, `venice`, `vercel-ai-gateway`, `sumopod`,+ `modelscope`.++Provider definitions live under `crates/openhuman-core/src/inference/provider/`+(`factory.rs` resolves a `<slug>:<model>` string to a client; `types.rs` holds+the provider shapes). Full setup and the local-model capability table are+in [Local models & bring your own+key](../features/model-routing/local-and-byok-models.md); routing behavior+and fallback order are in [Automatic Model+Routing](../features/model-routing/README.md).++## Embeddings++Embeddings route through a separate provider selection+(`embeddings.update_settings` over RPC, or `embeddings_provider` for+per-workload override), independent of the chat provider:++- **Managed** (default): the OpenHuman backend's Voyage-backed embedding+ endpoint. Works on a fresh install with no local daemon.+- **Voyage**: direct Voyage AI API with your own key.+- **OpenAI**: cloud embeddings via the OpenAI API.+- **Cohere**: the Cohere embed API with your own key.+- **Ollama**: a local model the user has pulled, `bge-m3` recommended+ (`ollama pull bge-m3`). Memory v2 does not use these; the memory engine+ embeds on its own side.+- **Custom**: any OpenAI-compatible embeddings endpoint.++Implementation: `crates/openhuman-core/src/inference/embedding_host/` (`mod.rs`+lists the providers; `factory.rs` builds the client; `schemas.rs` defines the+`embeddings.*` RPC surface, including `set_api_key` per provider slug).++## Memory++Memory v2 (`docs/specs/memory-v2.md`) is Recall, Fetch and Store over a+pluggable engine. The contract is `tinymemory-api` (vendored at+`vendor/tinymemory/`): a `MemoryEngine` trait with `recall`, `fetch`, `store`,+`forget`, `list` and `health`, plus an `EngineDescriptor` that declares whether+the engine is hosted, needs an endpoint or key, and which fetch modes it+supports. `tinymemory::list_engines` and `build_engine` are the registry.++Two engines ship, both served by `tinymemory-integrations` (the three TinyMemory crates are `tinymemory-api`, `tinymemory-tools` and `tinymemory-integrations`):++| id | what | endpoint | key |+| --- | --- | --- | --- |+| `tinyhumans` | CortexDB hosted behind the TinyHumans backend (`/memory/*`) | the backend origin | the signed-in session or API key, resolved per request through the host credential seam |+| `cortexdb` | the user's own CortexDB (direct `/v1/*`) | `[memory.engines.cortexdb] endpoint` (default `https://api-v1.cortexdb.ai`) | stored in the OS keychain as `memory-cortexdb` |++Select one with `[memory] engine` or from Connections > Memory > Engine+(`openhuman.memory_engine_set`). `memory::engine::resolve` binds it: signed out+with no CortexDB key means **memory is off** (the `memory` tool is not+registered, ingestion is a no-op and RPCs answer `MEMORY_OFF`). Built engines+are cached by a fingerprint of engine id, endpoint and credential identity, so+changing any of them rebuilds the engine on the next call. There is no engine+migration: switching engines starts empty, and the one-time import of a v1+store uploads to whichever engine is selected, after explicit consent.++Both engines declare `fetch_modes = [hybrid]` because the CortexDB recall wire+has no keyword/vector switch; asking for another mode fails with `UNSUPPORTED`.++Related pages: [Memory](../features/memory.md) and+[Memory architecture](architecture/memory.md).++## Web search++`[search] engine` selects the active provider; only one is active at a time,+mirroring the LLM provider model:++- `managed` (default): backend-proxied, no key needed.+- `parallel`: search, extract, chat, research, enrich, and dataset tools+ against the Parallel API.+- `brave`: Brave Search (web, news, images, videos).+- `querit`: Querit web search.+- `exa`: Exa neural search (search, find-similar, contents). Direct to+ `api.exa.ai`, never through the managed backend.+- `tavily`: Tavily search and extract (web, news, finance). Direct to+ `api.tavily.com`.+- `disabled`: no search tools registered.++A BYOK engine selected without a stored key falls back to `managed` rather+than leaving the agent with no search tool at all.++SearXNG is a separate toggle (`[searxng] enabled`, `base_url`) rather than a+`search.engine` value, since it points at a self-hosted instance instead of a+vendor API. The providers themselves live in the `tinysearch` module+(`vendor/tinysearch`), which owns the per-provider transports and the role+dispatch; the host keeps provider resolution and credential policy in+`crates/openhuman-core/src/search/` and+`crates/openhuman-core/src/config/schema/tools/search.rs`, and the host's+provider list is taken from the contract rather than maintained separately.++See [Web Search](../features/native-tools/web-search.md) for the tool surface+each engine exposes.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/getting-set-up.md b/docs/gitbooks/docs/gitbooks/en/developing/getting-set-up.mdnew file mode 100644index 0000000000..5500e3d7c6--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/getting-set-up.md@@ -0,0 +1,181 @@+---+description: >-+ Building OpenHuman from source: the pinned toolchain, the vendored submodules,+ the Tauri CLI wrapper, and local desktop builds, plus the release installers+ for each platform.+icon: wrench+---++# Getting Set Up++This guide covers the full desktop/source install path plus the release installers, so pick whichever path matches what you're doing:++1. Build OpenHuman from source+2. Install the latest stable release binaries++If you only need the Rust workspace under `crates/` on a fresh machine (no Node, no Tauri), use [Building the Rust Core](building-rust-core.md) instead. That page has the pinned Rust toolchain, OS package prerequisites, and the exact `cargo` commands for `openhuman-core`.++## Prerequisites++* `git`+* Node.js 24 or newer (see `app/package.json`)+* `[email protected]` (see the root `package.json` `packageManager` field)+* Rust 1.96.1 through `rustup` with `rustfmt` and `clippy` (see `rust-toolchain.toml`)+* CMake, required by native Rust dependencies+* Every `vendor/` submodule listed in `.gitmodules`, initialized recursively (`git submodule update --init --recursive`). The root `Cargo.toml` `[patch]` tables point into that tree, so cargo reads each manifest whether the crate is optional or not; a subset is always a build break+* Platform desktop build tools: Xcode Command Line Tools on macOS, or the Tauri GTK/WebKit/AppIndicator package set on Linux++macOS Homebrew quick start:++```bash+brew install node@24 pnpm rustup-init cmake+rustup toolchain install 1.96.1 --profile minimal+rustup component add rustfmt clippy --toolchain 1.96.1+```++Arch Linux quick start:++```bash+sudo pacman -S --needed nodejs npm rustup cmake base-devel clang openssl \+ alsa-lib xdotool libxtst libxi libevdev gtk3 webkit2gtk-4.1 \+ libayatana-appindicator librsvg patchelf nss nspr at-spi2-core \+ libcups libdrm libxkbcommon libxcomposite libxdamage libxfixes \+ libxrandr mesa pango cairo libxshmfence+npm install -g [email protected]+rustup toolchain install 1.96.1 --profile minimal+rustup component add rustfmt clippy --toolchain 1.96.1+```++## Build from source (local compile)++Run from the repository root:++```bash+# 1) Clone and enter the repo+git clone https://github.com/tinyhumansai/openhuman.git+cd openhuman++# 2) Fetch the vendored tiny* crate submodules+git submodule update --init --recursive++# 3) Install JS deps (workspace)+pnpm install++# 4) Build desktop app artifacts+pnpm build+```++For local development instead of production build:++```bash+# Web-only UI development+pnpm dev++# Desktop app development: runs scripts/run-dev-macos.sh (`cargo tauri dev` with a dev config override)+pnpm dev:app++# Other Tauri CLI commands (from app/node_modules) run against crates/openhuman-app/+pnpm tauri build+```++## Install latest stable release (macOS/Linux x64)++Primary install command:++```bash+curl -fsSL https://raw.githubusercontent.com/tinyhumansai/openhuman/main/scripts/install.sh | bash+```++Installer behavior:++* Resolves latest stable OpenHuman release for your platform+* Validates artifact digest when available+* Installs locally (no sudo by default)+* macOS: installs `OpenHuman.app` into `~/Applications`+* Linux x64: installs AppImage as `~/.local/bin/openhuman` and writes a desktop entry++### Arch Linux package recipe++The repository includes an `openhuman-bin` AUR recipe at [`packages/arch/openhuman-bin`](../../../../../../packages/arch/openhuman-bin/). It uses the official x86\_64 AppImage as the binary source, extracts the bundled application tree during `makepkg`, installs a desktop entry, and exposes `/usr/bin/openhuman`.++Until the package is published on AUR, build it locally on Arch:++```bash+cd packages/arch/openhuman-bin+makepkg --syncdeps --install+```++After publication, Arch users can install it with:++```bash+yay -S openhuman-bin+```++Useful flags:++```bash+# Preview actions without writing files+curl -fsSL https://raw.githubusercontent.com/tinyhumansai/openhuman/main/scripts/install.sh | bash -s -- --dry-run+```++## Windows (latest stable)++Use PowerShell:++```powershell+irm https://raw.githubusercontent.com/tinyhumansai/openhuman/main/scripts/install.ps1 | iex+```++Windows installer behavior:++* Resolves latest stable release+* Downloads MSI/EXE for x64+* Verifies digest when available+* Runs per-user install where supported by installer package++## ARM Linux build (aarch64)++CI builds the `aarch64-unknown-linux-gnu` target on an `ubuntu-24.04-arm` runner with the same Tauri command as x64 (see [`.github/workflows/build-desktop.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/build-desktop.yml)). Locally, with the Linux desktop package set installed:++```bash+pnpm tauri build --target aarch64-unknown-linux-gnu --bundles deb appimage+```++The shell is stock Tauri on Wry, so the resulting binary needs no extra library path. Install the `.deb` bundle with `dpkg -i`.++Manual download links (all platforms):++* Website: https://tinyhumans.ai/openhuman+* Latest release: https://github.com/tinyhumansai/openhuman/releases/latest++## Troubleshooting++### Stale `openhuman` RPC process on the core port++**Symptom**++A previous Tauri build or `openhuman-core run` harness left a process listening on `OPENHUMAN_CORE_PORT` (default `7788`). Until issue #1130 the new Tauri build would silently attach to that listener, leading to version drift and 401s when the new build's `OPENHUMAN_CORE_TOKEN` didn't match.++**Current behavior (issue #1130)**++`core_process::ensure_running` now probes the port at startup:++* If `GET /` identifies the listener as an OpenHuman core (JSON body with `"name": "openhuman"`), it is treated as a stale process from a previous run and proactively terminated (`SIGTERM`, then `SIGKILL` after 750ms on Unix; `taskkill /F /T /PID` on Windows). The Tauri host then spawns its own fresh embedded core.+* If the listener is something else (or doesn't speak HTTP), startup fails loudly with the conflict surfaced in the log instead of silently attaching.+* Set `OPENHUMAN_CORE_REUSE_EXISTING=1` to opt back into the legacy attach-to-anything behavior, useful when running `openhuman-core run` as a manual debugging harness.++**Manual cleanup (still works)**++```bash+pkill -f "OpenHuman.app/Contents"+pkill -f "openhuman-core"+```++***++## See also++* [Building the Rust Core](building-rust-core.md): the cargo-only path, without Node or Tauri.+* [E2E Testing Guide](e2e-testing.md): the harness a local desktop build feeds.+* [Architecture](architecture/architecture.md): what the shell, the core and the frontend each own.+* [Cloud deployment](../features/cloud-deploy.md): running the same core headless on a server.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/hooks.md b/docs/gitbooks/docs/gitbooks/en/developing/hooks.mdnew file mode 100644index 0000000000..d1ca9a1947--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/hooks.md@@ -0,0 +1,274 @@+---+description: >-+ File-based hooks that observe and gate an agent turn, with a+ Cursor-compatible contract.+icon: link+---++# Hooks++A hook is a script you own that OpenHuman runs at a specific moment (before a+tool executes, after a file is edited, when a turn finishes) and whose answer+the agent obeys. It is how you make the agent follow a rule that lives in your+repository rather than in our code: block `rm -rf`, run the formatter after every+edit, write an audit line per tool call, refuse to read `.env`.++The contract is deliberately the same as+[Cursor's](https://cursor.com/docs/hooks): same file name, same event names,+same stdin envelope, same stdout decision, same exit codes. A hook script written+for either host runs on the other unchanged.++> There is a second, unrelated meaning of "hook" in this codebase: the in-process+> Rust traits in `crates/openhuman-core/src/agent/hooks.rs` that an *embedding host* installs+> by compiling against the core. Those are for building a product on top of+> OpenHuman. This page is about the file-based kind, for using OpenHuman.++## The file++`hooks.json`, schema version 1:++```json+{+ "version": 1,+ "hooks": {+ "beforeShellExecution": [+ {+ "command": "./.openhuman/deny-destructive.sh",+ "matcher": "^\\s*(rm|dd|mkfs)\\b",+ "timeout": 5,+ "failClosed": true+ }+ ],+ "afterFileEdit": [+ { "command": "./.openhuman/format.sh", "matcher": "\\.rs$" }+ ]+ }+}+```++Four locations are read, and **they concatenate: a more specific file cannot+remove a broader one's rules**:++| Layer | Path |+| ----- | ---- |+| System | `/etc/openhuman/hooks.json` · `/Library/Application Support/OpenHuman/hooks.json` · `%ProgramData%\OpenHuman\hooks.json` |+| User | `~/.openhuman/hooks.json` |+| Workspace | `<workspace_dir>/hooks.json` |+| Project | `<action_dir>/.openhuman/hooks.json` |++Concatenation is safe because the **strictest verdict wins**: across every hook+that ran, deny beats ask beats allow. Adding a hook can never loosen a policy+another one set, which is what lets a repository ship its own `hooks.json` onto+a machine an operator has already locked down.++### Fields++| Field | Meaning |+| ----- | ------- |+| `command` | Program to run (or the prompt text, for `"type": "prompt"`). Runs with its own `hooks.json` directory as cwd. |+| `type` | `command` (default) or `prompt`. |+| `matcher` | Which occurrences reach this hook, see below. Absent means all. |+| `timeout` | Seconds. Falls back to `[hooks] default_timeout_secs` (30). |+| `failClosed` | Treat a crashed, missing, or timed-out hook as a denial. Default `false`. |+| `loop_limit` | Follow-ups this hook may inject per session. Default 5; `0` means unlimited. |+| `model` | Model override for a `prompt` hook. |+| `enabled` | Set `false` to park a hook without deleting it. |++## The protocol++The event arrives on **stdin** as one JSON object. The decision goes to+**stdout**. The exit code decides how stdout is read:++| Exit | Meaning |+| ---- | ------- |+| `0` | stdout is the decision. Empty stdout is a no-op. |+| `2` | Deny, whatever stdout said. stderr becomes the reason the agent is told. |+| anything else | Failure. **Fails open** (the action proceeds) unless `failClosed`. |++A timeout, a missing interpreter, and unparseable stdout all take that same+failure path. That symmetry is the point: a hook that denies only when it+manages to run is not a security control, so `failClosed` covers every way a+script can fail to answer.++stdout is parsed leniently: the last standalone JSON object wins, so a script+that logs progress before answering works as written.++### Decision object++Every field is optional, and each event honours the subset it defines:++```json+{+ "permission": "allow" | "deny" | "ask",+ "user_message": "shown to the human",+ "agent_message": "shown to the model",+ "updated_input": { "…": "replacement tool arguments" },+ "additional_context": "appended to the tool result",+ "continue": false,+ "followup_message": "sent as another user turn",+ "env": { "KEY": "value" }+}+```++`ask` escalates to the approval gate where one is available; inside the tool+middleware, which has no approval channel, it denies rather than quietly+allowing.++## Events++`hook_event_name` in the envelope tells a script which moment it is in. Names are+matched loosely: `preToolUse`, `PreToolUse` and `pre_tool_use` are the same+event, and Claude Code's `UserPromptSubmit` aliases onto `beforeSubmitPrompt`.++| Event | Fires | Honours |+| ----- | ----- | ------- |+| `preToolUse` | before any tool | `permission`, `updated_input`, `agent_message` |+| `postToolUse` | after a tool succeeded | `additional_context` |+| `postToolUseFailure` | after a tool failed | - |+| `beforeShellExecution` | before `shell` / `node_exec` / … | `permission`, `agent_message` |+| `afterShellExecution` | after one completed | - |+| `beforeReadFile` | before `file_read` / `read_diff` | `permission` |+| `afterFileEdit` | after `file_write` / `edit` / `apply_patch` | - |+| `beforeMCPExecution` / `afterMCPExecution` | around an MCP tool | `permission` |+| `beforeSubmitPrompt` | on a chat message, before the model | `continue`, `permission`, `additional_context` |+| `subagentStart` | before a delegation | `permission` |+| `subagentStop` | after one (not fired yet, see below) | `followup_message` |+| `stop` | after a turn | `followup_message` |+| `afterAgentResponse` | on the assistant's message | - |++`sessionStart`, `sessionEnd`, `preCompact`, `afterAgentThought` and `subagentStop`+are defined: they parse, match, execute, and can be exercised with `hooks test`,+but the core does not fire them yet. (`subagentStop` is the near miss: the handler+`hooks::ops::subagent_stopped` is complete, but the in-progress+`agent/subagent_host` cutover currently fires only `subagentStart` and returns+without ever calling the stop side.) Configuring one+produces a load warning saying so, and `hooks list` reports `"wired": false` for+it. That is deliberate: a hook that silently never runs is the worst thing this+system can do to you.++### Derived events++OpenHuman has no separate "shell execution" or "file read" call site: those are+the `shell`, `file_read` and `file_write` tools going through the ordinary tool+seam. So the shell, file and MCP events are *derived* from tool calls, and their+payloads are reshaped the way a Cursor hook expects: a `command` string, a+`file_path`, an `edits` array. Both the generic `preToolUse` and the specialised+event fire, generic first.++## Matchers++One string, matched against a subject the event chooses: the tool name for tool+events, the command line for shell events, the path for file events, the agent id+for subagent events.++* absent or `*`: everything+* `Shell`: a literal, case-insensitive name+* `Read|Write|Shell`: alternation+* `MCP:search_docs`: an MCP tool by name+* anything containing punctuation: a regular expression (`^rm\b`, `\.rs$`)++An invalid regex matches **nothing** and logs.++## Latency++Gating events run their hooks sequentially and the turn waits; a denial+short-circuits the rest. Observational events (`afterShellExecution`,+`postToolUseFailure`, `afterAgentResponse`, …) are dispatched onto a background+task and the turn never waits, so an audit hook that hangs must not hang the agent.++When nothing is configured, the harness bridge is not installed at all, so an+unconfigured host pays nothing per tool call.++## Environment++Hook processes inherit the core's environment plus:++`OPENHUMAN_PROJECT_DIR` (also exported as `CLAUDE_PROJECT_DIR` and+`CURSOR_PROJECT_DIR`), `OPENHUMAN_VERSION`, `OPENHUMAN_HOOK_EVENT`,+`OPENHUMAN_SESSION_ID`, `OPENHUMAN_AGENT_ID`.++## Prompt hooks++`"type": "prompt"` writes the policy in English instead of shell. The text is+sent to a model with the event JSON substituted for `$ARGUMENTS`, and the model+answers `{"ok": true}` or `{"ok": false, "reason": "…"}`.++```json+{ "command": "Deny if $ARGUMENTS deletes anything outside /tmp.", "type": "prompt" }+```++It costs a model call per event, so put it on rare, high-stakes moments, not on+every tool call.++## Inspecting and debugging++Three RPC methods, on the `hooks` namespace:++```bash+openhuman-core hooks list # what is configured, from which file, and whether it is wired+openhuman-core hooks reload # re-read every layer+openhuman-core hooks test --event beforeShellExecution \+ --payload '{"command":"rm -rf /","sandbox":false}'+```++Over JSON-RPC the same three are `openhuman.hooks_list`, `openhuman.hooks_reload`+and `openhuman.hooks_test`.++`hooks test` fires one synthetic event in the foreground and reports what each+matching hook decided, including hooks for observational events that a real+dispatch would run detached. Debug a hook with it rather than by asking the agent+to do the dangerous thing to see whether the rule fires.++## Host switches++`config.toml`:++```toml+[hooks]+enabled = true # off means no hooks.json is read and no bridge installed+default_timeout_secs = 30 # for hooks that name no timeout of their own+```++## Example++`.openhuman/hooks.json`:++```json+{+ "version": 1,+ "hooks": {+ "beforeReadFile": [{ "command": "./.openhuman/no-secrets.sh", "matcher": "\\.env" }],+ "afterFileEdit": [{ "command": "./.openhuman/fmt.sh", "matcher": "\\.rs$" }]+ }+}+```++`.openhuman/no-secrets.sh`:++```sh+#!/bin/sh+echo '{"permission":"deny","agent_message":"Secrets files are off limits. Ask the user for the value you need."}'+```++`.openhuman/fmt.sh`:++```sh+#!/bin/sh+cat > /dev/null # drain stdin; this hook does not read the event+cargo fmt >/dev/null 2>&1+echo '{}'+```++Both need `chmod +x`.++## Implementation++The engine and the whole `hooks.json` contract live upstream, in+`tinyagents_runtime::command_hooks`: the types, the file and its layering, the+matcher, running one hook (stdin, timeout, exit codes), selection and ordering+and aggregation, the context envelope, and follow-ups.++What stays in `crates/openhuman-core/src/hooks/` is the host half: `bridge`+(mounting the engine on the harness's existing tool and turn seams), `ops` (the+moments with no existing seam), `host`, `schemas` (the RPC surface) and+`prompt_eval`. The beside-code `README.md` there is the authoritative split.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/jev.md b/docs/gitbooks/docs/gitbooks/en/developing/jev.mdnew file mode 100644index 0000000000..c5238a3ca5--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/jev.md@@ -0,0 +1,217 @@+---+description: >-+ The small decision model: what it answers, where it is called, what it+ costs, and how it is configured.+icon: scale-balanced+---++# Jev++Jev is a decision model, not a text generator. Give it a request and a+handful of labelled options, and it returns a calibrated probability for+each one in about 150 milliseconds. OpenHuman uses it as a fast, cheap judge+wherever a turn needs to pick from a short list rather than write prose: tool+selection during a search, and step-by-step browser control.++The models are `jev-1.13` and `jev-latest`, built by TypeSafe AI and reached+through the TinyHumans System One proxy or, for a BYOK OpenRouter route,+directly. Pricing is $0.042 per million input tokens, output free, and a+typical tool search costs one to two thousand tokens. There is no session,+no chain of thought, and nothing to stream: one request, one set of+probabilities.++## Three question types++Jev answers three kinds of question, defined in `tinyjevclient`:++- **Choice**: probabilities over a set of named options, so the caller can+ pick the best one, the top three, or discard everything below a+ confidence floor.+- **Score**: a single calibrated number for one thing, rather than a choice+ among several.+- **Noul**: a yes/no probability, used where OpenHuman needs "does this even+ apply" rather than "which of these applies."++Tool search uses a Choice and a Noul in the same request: the Choice picks+a tool from the shortlist (plus a `none` option), and the Noul answers+whether the request needs a tool at all. Browser control uses Jev+repeatedly, once per step, to decide the next action.++## Why retrieval comes first++Jev accepts at most 255 options in one Choice, and its accuracy drops as+the option list fills with entries that have nothing to do with the+request. So nothing in OpenHuman ever hands Jev a whole tool catalogue.+`tinytools-jev` (`vendor/tinyagents/vendor/tinytools/crates/tinytools-jev/`)+narrows first and decides second:++1. A retriever (BM25 by default, or an embedding-based ranker when one is+ configured) shortlists `retrieval_k` candidates, 20 by default. This step+ is skipped when the catalogue already fits in one Choice.+2. One request to Jev: a Choice over the shortlist plus `none`, and a Noul+ asking whether the request needs a tool at all.+3. Hits come back ranked by probability, `none` removed, anything below+ `min_probability` (0.05 by default) dropped.++`JevRankerConfig::with_strategy` picks how the catalogue gets narrowed:++- `RetrieveThenDecide` (the default): retrieve top 20, decide once. Bounded+ by the retriever's recall, since a paraphrase the retriever misses never+ reaches Jev.+- `FamilyThenDecide`: one evaluation picks the candidates' family first (a+ toolkit or pack; anything without one falls into `core`), then a second+ evaluation runs per chosen family (`max_families`, default 2, run+ concurrently) over every member of that family. A family that fits in one+ Choice skips retrieval entirely, so a paraphrase is judged on meaning at+ both stages instead of being filtered out lexically before Jev sees it.++## How OpenHuman uses it++### Tool search++The tinyagents harness owns the `tool_search` / `tool_call` bridge over+every tool registered as deferred. `openhuman-tinyhumans` installs+`TinyHumansJevRanker` (`crates/openhuman-tinyhumans/src/jev/ranker.rs`) as+the process-wide ranker for that bridge+(`crates/openhuman-core/src/agent/tinyagents/discovery/`). The product+default uses `RetrieveThenDecide` with the process's embedding provider as+the retriever, so retrieval finds candidates by meaning rather than by+shared words before Jev decides among them.++The ranker resolves its Jev route and credential fresh on every search+rather than caching them at install time, because a desktop can sign in and+out while the process keeps running. The route is `agent.tool_search.jev_route`+(see [Configuration](#configuration)): the TinyHumans proxy, TypeSafe's own+API, or OpenRouter's System One API. The built Jev client is cached by+route, credential and backend URL, so a stable session does not rebuild an HTTP+client on every search. When the process has no usable embedding provider,+`TinyHumansJevRanker` refuses outright and the harness answers with its own+BM25 ranking instead of running a Jev decision over a lexical shortlist that+would only add a network round trip for no gain.++### Browser control++`crates/openhuman-core/src/modules/browser_task.rs` hands browser tasks to+TinyComputer's task members (`StartTask`, then `AwaitTask` until the task+pauses or finishes), confined to the browser surface and the allowed websites.+The decision model is chosen in `[computer] decision_model`: Jev (through+the hosted proxy when signed in, or the user's OpenRouter key), OpenJev, or+Sage. A failed step goes to the rescue model (`[computer] rescue_model`,+up to `max_rescues` times) before the task fails. An irreversible step pauses+as `needs_approval`; the browser tool holds it behind a one-use token and only+`confirm_pending`, through the host approval gate, answers `ContinueTask`.++`crates/openhuman-core/src/modules/browser_sites.rs` keeps what finished+browser tasks learned, per site, in `<workspace>/state/computer/sites/`, and+hands it to the next task on the same site: the plan a run finished with, as+`StartTask.flow` for the same goal and facts (no planning), and the elements+it found, as `StartTask.memory` (a remembered element costs one yes/no instead+of a search). Only a run that finished (`done`, or its payment checkpoint)+teaches anything; a plan is kept only when its run needed no rescue and holds+no fact value its goal does not, and a reused plan that fails or needs a+rescue is forgotten. Elements holding a fact value or page text are not kept,+entries expire after 30 days unused, and none of it reaches the agent's memory+or prompts. `[browser] learn_from_tasks` turns it off, and+`modules.browser_forget_sites` forgets one site or all.++## Measured results++From `docs/plans/jev-tool-search-baseline.md`, measured 2026-09-22 against+215 core tools plus 1,000 recorded Composio actions, with 160 hand-written+requests (66 mapped to a Composio action, 63 to a core tool, 31 that no tool+should answer):++| Ranker | Top-1 | Top-3 | Needless calls (of 31) | p50 latency |+| --- | --- | --- | --- | --- |+| BM25 | 22.5% | 38.0% | 26 | 28 ms |+| Jev, BM25 top-20 then decide | 57.4% | 62.0% | 1 | 1.5 s |+| Jev, embedding top-20 then decide (product default) | 62.0% | 66.7% | 1 | 1.5 s |+| Jev, family then decide | 62.0-64.3% | 67.4-69.0% | 1 | 1.3 s |++On the Composio-only slice, `FamilyThenDecide` with an embedding cut for+oversized families reaches 80.3% top-1 and 87.9% top-3, against BM25's 18.2%+and 36.4%. The gap comes mostly from retrieval, not the decision itself:+under `RetrieveThenDecide` with BM25 shortlisting, Jev's Composio top-3+(72.7%) lands exactly on BM25's recall@20, meaning Jev is choosing correctly+from everything it was shown but a paraphrase like "ping alex" for+`SLACK_SEND_MESSAGE` never reaches it. Letting Jev pick the family first+removes the shortlist for every toolkit that fits in one Choice and lifts+Composio top-3 into the high 80s.++Needless tool calls collapse under any Jev configuration: BM25 answers 26 of+31 tool-less requests with a (wrong) tool anyway, while Jev's `none` option+and `needs_tool` Noul let it abstain on all but one.++## Configuration++`ToolSearchConfig` (`crates/openhuman-core/src/config/schema/agent.rs`) is+the `[agent.tool_search]` block:++```toml+[agent.tool_search]+ranker = "jev" # "jev" (default) | "auto" | "bm25" | "compare"+jev_route = "auto" # "auto" (default) | "tinyhumans" | "typesafe" | "openrouter"+# jev_base_url = "http://127.0.0.1:18080" # typesafe/openrouter origin override+top_k = 3+```++- `ranker = "jev"`: use the installed decision-model ranker, falling back to+ BM25 only when it fails or the process has no TinyHumans credential.+- `"auto"`: same fallback behaviour as `"jev"`.+- `"bm25"`: the built-in lexical ranker only, no network call.+- `"compare"`: serve Jev, but also record the BM25 ranking in the+ `tool.searched` telemetry, so the two can be compared on live traffic+ without changing what the model sees.+- `jev_route`: where the Jev decision calls go. `"auto"` uses the TinyHumans+ credential when the process has one, else `TYPESAFE_API_KEY` (direct to+ TypeSafe), else an OpenRouter key (`OPENROUTER_API_KEY`, or the stored+ `openrouter` BYOK key). `"tinyhumans"`, `"typesafe"` and `"openrouter"` pin+ one route and never fall through to another credential. Override per launch+ with `OPENHUMAN_JEV_ROUTE`.+- `jev_base_url`: replaces the API origin of the `typesafe` / `openrouter`+ routes (a metering proxy, a mirror). Remote origins must be HTTPS; HTTP is+ accepted for literal loopback IPs only. Override per launch with+ `OPENHUMAN_JEV_BASE_URL`.+- `top_k`: how many matches a search returns when the model does not ask for+ a specific number. Three by default, enough to choose from without+ returning so many schemas that the point of deferring them is lost.++Without an embedding provider, or without a credential for the selected Jev+route, tool search falls back to BM25 automatically, so `auto` and `jev` cost+nothing extra with no credential. A BYOK setup with no TinyHumans account+needs an embedding provider that does not depend on one (for example+`memory.embedding_provider = "custom:<OpenAI-compatible endpoint>"`) as well as+a TypeSafe or OpenRouter key.++## Running the benchmark++```bash+cargo run -p openhuman-cli --bin tool-search-bench -- --ranker all --misses+cargo run -p openhuman-cli --bin tool-search-bench -- --ranker jev --family --embedding+cargo run -p openhuman-cli --bin tool-search-bench -- --dump-catalogue+```++`OPENHUMAN_BACKEND_API_KEY` (or `TYPESAFE_API_KEY`) selects the credential;+without one the bench ranks through the signed-in TinyHumans session, same+as the product.++## Where the code lives++- `vendor/tinyagents/vendor/tinytools/crates/tinytools-jev/`: the+ transport-neutral `ToolRanker` implementation, its retrieval strategies,+ and the `JevRankerConfig` / `JevRanking` types.+- `crates/openhuman-tinyhumans/src/jev/`: the TinyHumans-specific evaluator+ (`TinyJevEvaluator`, over `tinyjevclient`) and the process-installed+ ranker (`TinyHumansJevRanker`).+- `crates/openhuman-core/src/agent/tinyagents/discovery/`: the host slot+ that holds the installed ranker and turns `[agent.tool_search]` into the+ policy a turn runs with.+- `crates/openhuman-core/src/modules/browser_task.rs`: the browser-task+ entry point that runs `JevController`.+- `docs/plans/jev-tool-search-baseline.md`: the full benchmark writeup this+ page's numbers come from.++See also: [Performance](performance.md) for the wider cost and density+picture, [Pluggable engines](engines.md) for the other swappable pieces+around inference and memory, and [Embedding OpenHuman](embedding.md) for+running an agent as a library, including one that uses tool search.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/loadable-modules.md b/docs/gitbooks/docs/gitbooks/en/developing/loadable-modules.mdnew file mode 100644index 0000000000..f92d0dae8c--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/loadable-modules.md@@ -0,0 +1,98 @@+---+description: >-+ How capability arrives at runtime instead of compile time: the TinyBus module+ ABI, the pinned registry, admission checks, and what happens when one faults.+icon: puzzle-piece+---++# Loadable modules++Feature gates decide what compiles into the binary. Modules decide what the binary can *reach* once it is running. A module is a first-party native library, loaded into the core process, serving a small typed interface over TinyBus.++The trade is explicit: a module shares the core's address space and its crash domain, so it is trusted code and the admission checks matter. In exchange, a user who never generates a document never pays for the document writer, in download size, in resident memory, or in dependency surface.++## The registry++`crates/openhuman-core/src/modules/registry/` compiles in **fourteen** records. Only this registry may select an artifact; nothing reads a module name from config and goes looking.++| Module | Provides |+| --- | --- |+| `tinycomputer` | Desktop and browser observation and control |+| `tinysearch` | Web-search provider dispatch |+| `tinydocs` | Document extraction and `.docx` / `.pptx` synthesis |+| `tinywallet` | Key derivation and transaction signing |+| `tinyjuice` | Tool-output compression and recovery |+| `tinyvoice` | Audio framing, VAD, wake-word gating, hallucination detection |+| `tinyruntime` + `tinyruntime-nodejs` + `tinyruntime-python` | Runtime discovery and warm interpreter pools |+| `tinymcp` | The MCP client and registry |+| `tinyconnectors` | OAuth connector actions and triggers |+| `tinybox` | Sandbox capability discovery |+| `tinychannels` | Messaging channel transports |+| `tinyhosts` | Hosting provider operations |++Each record carries a version, the release it came from, and one **`PlatformAsset` per supported build**: thirteen of the fourteen publish eleven (`ubuntu-24.04` and `ubuntu-22.04` × `x86_64`/`arm64`, `macos-26` and `macos-15` × `arm64`/`x86_64`, `windows-2025-x86_64`, `windows-2022-x86_64`, `windows-11-arm64`), and `tinycomputer` publishes seven because it has no Linux backend.++Every asset carries a SHA-256 **copied verbatim from the published release's own checksum file**. Do not compute a replacement pin from a local build: the point of the digest is that it describes the artifact the release workflow signed, not the one on your machine.++## Resolution order++Each step exists to avoid the cost of the next:++1. Already serving on the host's broker.+2. An operator override: a path in `[modules].overrides`, or a `*_TEST_MODULE` environment variable.+3. The module search path: `OPENHUMAN_MODULE_PATH`, then the platform data directories.+4. Bundled releases staged into the app at build time.+5. The release cache, downloading only if `[modules].allow_download` is true.++An override **bypasses the digest check**, because the artifact is whatever is at that path. That is acceptable only because it is the operator's own file named by the operator's own config, and it is why the block cannot *add* a module that is not already in the registry.++Platform candidates are ordered newest-first with fallthrough. On Linux, glibc 2.39 or newer prefers the 24.04 build and falls back to 22.04; 2.35 or newer gets 22.04; anything older, and musl or an unknown libc, gets an **empty** candidate list, so no published artifact can load there by design.++## Admission++In order, and all of it before any module code runs:++1. Directory ownership and mode, and a regular platform library file within the size cap.+2. The digest allowlist beside the artifact, when present, which is authoritative for its directory.+3. Resolve the ABI descriptor symbol, and validate its frozen 16-byte prefix before reading the rest.+4. Validate the full descriptor: matching pointer width, endianness and target triple, a compatible TinyBus series, and module feature bits that are a subset of the host's. A module built with `panic = "abort"` is **refused**, because a panic that aborts takes the host with it.+5. Parse the manifest and resolve dependencies, rejecting missing providers, cycles and name clashes.+6. Initialize, take the vtable, attach the transport.++Each module declares its interface in its own small `*-bus` contract crate: the interface name, the object path, one constant per member, and a contract version. The bind rule is majors equal **and** the module's minor at least the host's, so a newer module serves an older host and the reverse is refused rather than half-working. Never redeclare a contract type in OpenHuman, and call members through the contract's constants rather than string literals.++## Faults are terminal++Of the eleven lifecycle states, five are terminal: rejected, faulted, failed, stopped and disabled. A module in one of those answers "unavailable" immediately and is **never retried in the same process**.++That is the direct consequence of the other rule: **the loader never unloads a library.** A stopped module releases its transport and its names, but its code, thread-locals, panic metadata and callback addresses stay mapped until the process exits. Replacing an artifact needs a restart. Retrying a faulted module in place would be running code whose invariants you already know are broken.++Untrusted code does not belong here. It belongs in a separate process, which is what the sandbox backends are for.++## Configuration++```toml+[modules]+enabled = true # off means the features say so, rather than failing at use+allow_download = true # false suits an air-gapped or reproducible deployment+# install_dir = "…" # defaults to the user cache dir, then the workspace+```++Nothing is downloaded silently either way: the digest comes from the compiled-in registry rather than from the release being fetched.++The `modules` RPC namespace exposes `list`, `status` and `load` (by id, never by path), plus `computer_status` and `browser_check_readiness` for the computer module's own readiness, and `browser_forget_sites`, which forgets what browser tasks learned about one site or every site (see [jev.md](jev.md)).++## Adding or moving one++A module's behaviour belongs in the submodule that owns it, not here. The host side is the adapter: the proxy, the config it pushes at initialization, and the policy around the call. When you change a module:++1. Land the change upstream and cut a release there.+2. Move the gitlink under `vendor/`.+3. Update the record's version, release URL and digests from that release's checksum file.+4. Test both the gate-on and gate-off builds, since a leaf gate's absence should mean "absent", not "present and failing".++## See also++- [Architecture](architecture/README.md): where modules sit relative to the core.+- [Building the Rust core](building-rust-core.md): the feature gates that decide what compiles.+- [Performance and footprint](performance.md): what the lazy-loading trade is worth.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/mcp-server.md b/docs/gitbooks/docs/gitbooks/en/developing/mcp-server.mdnew file mode 100644index 0000000000..a2cafb7466--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/mcp-server.md@@ -0,0 +1,215 @@+---+description: Run OpenHuman Core as a read-only stdio Model Context Protocol server.+icon: plug+---++# MCP Server++OpenHuman Core can run as an opt-in stdio MCP server for local MCP clients such+as Claude Desktop, Cursor, or Zed.++```bash+openhuman-core mcp+```++The command does not start the HTTP JSON-RPC server. It reads newline-delimited+JSON-RPC 2.0 messages from stdin and writes MCP responses to stdout. Logs go to+stderr; add `--verbose` for debug output.++## Client provenance++During `initialize`, the MCP server captures `params.clientInfo.name` for the+stdio session. The name is normalized by trimming leading and trailing+whitespace, converting to lowercase, replacing each sequence of+non-ASCII-alphanumeric characters with a single hyphen, then trimming leading+and trailing hyphens. For example, `Claude Desktop` becomes `claude-desktop`,+`Cursor` becomes `cursor`, and `Windsurf` becomes `windsurf`.++If the client omits `clientInfo.name`, sends an empty value, or sends a name+that normalizes to nothing, the session falls back to the bare `mcp` source+label. Write-capable MCP tools should use this session source label for memory+provenance so old clients keep the existing `mcp` behavior and identifiable+clients can write as `mcp:<client>`.++## Tools++The MCP surface routes through the existing controller registry plus the core+security policy: read tools pass the read gate, and three tools pass the act+gate. Two of them, `memory.learn` and `memory.forget`, are also recorded on the+MCP write-audit path; `agent.run_subagent` is not, because the sub-agent's own+side-effecting calls are audited through the approval gate instead:++| MCP tool | Backing RPC | Purpose |+| ------------------- | ------------------------------------ | ----------------------------------------------------------------------- |+| `web_search`\* | `openhuman.tools_web_search` | Ranked web search through the configured providers, with fallback. |+| `web_answer`\* | `openhuman.tools_web_answer` | Grounded answer with citations (Gemini with Google Search by default). |+| `searxng_search`\* | `openhuman.tools_searxng_search` | Search a configured self-hosted SearXNG instance. |+| `memory.recall` | `openhuman.memory_recall` | Ask a question; get an answer with citations (read-only). |+| `memory.fetch` | `openhuman.memory_fetch` | Raw hits for a query, with metadata filters and a cursor (read-only). |+| `memory.list` | `openhuman.memory_items_list` | Page through stored items, newest first (read-only). |+| `memory.learn` | `openhuman.memory_learn` | Store one learning (adds an item; non-destructive). |+| `memory.forget` | `openhuman.memory_forget` | Permanently remove items by id (destructive; act-gated). |+| `core.list_tools` | served in-layer | The live core agent tool catalog OpenHuman exposes to its orchestrator. |+| `core.tool_instructions` | served in-layer | The Markdown tool-use instruction block injected into prompt-guided agents. |+| `agent.list_subagents` | served in-layer | The registered sub-agent definitions the core can dispatch. |+| `agent.run_subagent` | served in-layer | Run a registered sub-agent and return its final response (act-gated). |++- Tools marked \* are listed only when a provider can serve them: `web_search`+ and `web_answer` when their search role has a usable provider (a signed-in+ session, or a provider with your own key), `searxng_search` when SearXNG is+ enabled in search settings.++`web_search` accepts `query`, optional `max_results` (1-20) and optional+`provider` (pins one provider and disables fallback). `web_answer` accepts+`query` and optional `depth` (`quick` or `deep`). `searxng_search` accepts+`query` and optional `max_results` (1-20).+`memory.recall` accepts `question` plus optional `filter` and `limit`.+`memory.fetch` accepts `query` plus optional `mode`, `filter`, `limit` and+`cursor`; `mode` must be one the active memory engine supports, and both launch+engines (`tinyhumans`, `cortexdb`) support only `hybrid`, so leave it out+unless you know otherwise. `memory.list` accepts optional `filter`, `limit` and+`cursor`. `limit` defaults to 10 and is capped at 100. `filter` takes any of+`workspace`, `folder`, `file_path`, `language`, `repo`, `commit`, `url`,+`thread_id`, `agent_id`, `kinds` (`document`, `conversation`, `learning`),+`sources`, `tags_any`, `observed_after` and `observed_before` (RFC 3339).+`memory.learn` accepts `text` plus optional `kind` (`preference`, `fact`,+`procedure`, `correction`, `other`) and `confidence` (0 to 1). `memory.forget`+accepts `ids` (1 to 100). Memory tools answer `MEMORY_OFF` when no memory engine+is usable. See [Memory v2](https://github.com/tinyhumansai/openhuman/blob/main/docs/specs/memory-v2.md) for the model.++Enable SearXNG under Connections → Search, in `config.toml`, or via environment:++```toml+[search.providers.searxng]+enabled = true+route = "direct"++[searxng]+enabled = true+base_url = "http://localhost:8080"+max_results = 10+default_language = "en"+timeout_seconds = 10+```++```bash+OPENHUMAN_SEARXNG_ENABLED=true+OPENHUMAN_SEARXNG_BASE_URL=http://localhost:8080+OPENHUMAN_SEARXNG_MAX_RESULTS=10+OPENHUMAN_SEARXNG_DEFAULT_LANGUAGE=en+OPENHUMAN_SEARXNG_TIMEOUT_SECONDS=10+```++## Resources++The MCP server exposes the bundled prompt assets as static resources. Clients+that support `resources/list` and `resources/read` can inspect the full agent+personality and subagent prompt templates without executing any tool calls.++### Capability advertisement++The `initialize` response includes:++```json+{+ "capabilities": {+ "tools": {},+ "resources": { "subscribe": false, "listChanged": false }+ }+}+```++### URI scheme++| URI | Content |+| --------------------------------- | ------------------------------------------------------ |+| `openhuman://prompts/identity` | `IDENTITY.md` (core agent identity) |+| `openhuman://prompts/soul` | `SOUL.md` (core agent personality and values) |+| `openhuman://prompts/user` | `USER.md` (user-profile context) |+| `openhuman://prompts/agents/<id>` | `<id>/prompt.md` for each of the 15 built-in subagents |++All resources have `mimeType: "text/markdown"`.++### Catalog parity++A unit test (`catalog_mirrors_builtins`) cross-references the resource catalog+against the `BUILTINS` slice in `loader.rs`. Adding a new built-in subagent+without a matching catalog entry fails CI.++### Resource templates++The catalog is fully static (every URI is concrete, none are templated), so+`resources/templates/list` always returns an empty `resourceTemplates` array.+The handler exists for MCP-spec compliance: clients that probe+`resources/templates/list` after seeing the `resources` capability get a+well-formed result instead of `-32601 Method not found`.++### Smoke test++```bash+printf '%s\n' \+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}' \+ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \+ '{"jsonrpc":"2.0","id":2,"method":"resources/list"}' \+ '{"jsonrpc":"2.0","id":3,"method":"resources/templates/list"}' \+ '{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"openhuman://prompts/identity"}}' \+ | openhuman-core mcp+```++## Tool registry++The HTTP JSON-RPC server also exposes a read-only global tool registry for+agents and dashboards that need discovery metadata without opening an MCP stdio+session:++| RPC method | Purpose |+| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `openhuman.tool_registry_list` | List MCP stdio tools and controller-backed tools with stable `tool_id`, route, version, input/output schemas, allowed agents, tags, enabled state, and health. |+| `openhuman.tool_registry_get` | Return one registry entry by `tool_id`, for example `memory.recall` or `tools.web_search`. |+| `openhuman.tool_registry_diagnostics` | Return redacted inventory counts, write-surface candidates, policy surfaces, and external capability-provider diagnostics. |++The registry is discovery-only. It does not change tool dispatch or permission+checks; MCP calls still go through `tools/call`, and controller-backed tools+still route through their existing JSON-RPC methods.++### External capability providers++OpenHuman can record trusted external capability providers in `config.toml`.+This is governance metadata only: it does not install packages, execute remote+code, or bypass the existing MCP/controller dispatch paths.++```toml+[[capability_providers]]+id = "Acme Tools"+display_name = "Acme Tools"+source_uri = "https://example.com/openhuman/acme-tools"+source_digest = "sha256:abc123"+trust_state = "trusted"+enabled = true+```++Provider ids are normalized before policy checks. For example, `Acme Tools`+becomes `acme-tools`; duplicates after normalization are rejected. A provider is+eligible for future admission checks only when it is both `enabled = true` and+`trust_state = "trusted"`. Missing provider config preserves the previous+behavior: the provider registry is empty and no existing tools are hidden.++## Smoke test++```bash+printf '%s\n' \+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}' \+ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \+ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \+ | openhuman-core mcp+```++The response should include `capabilities.tools` from `initialize` and the+curated tool names from `tools/list`. A successful run writes exactly two compact+JSON response lines to stdout; the `notifications/initialized` message is a+notification and has no response.++```text+{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{},"resources":{"subscribe":false,"listChanged":false}},"serverInfo":{"name":"openhuman-core","version":"<crate version>"},"instructions":"..."}}+{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"memory.recall",...},{"name":"memory.fetch",...},{"name":"memory.list",...},{"name":"memory.learn",...},{"name":"memory.forget",...}]}}+```diff --git a/docs/gitbooks/docs/gitbooks/en/developing/performance.md b/docs/gitbooks/docs/gitbooks/en/developing/performance.mdnew file mode 100644index 0000000000..f4a5b11c90--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/performance.md@@ -0,0 +1,183 @@+---+description: >-+ Measured footprint: agent density in one process, cold start, binary size,+ and the dependency-floor ratchet that keeps it there.+icon: gauge+---++# Performance and footprint++OpenHuman's Rust core runs in-process as a library, not as one OS process per+agent. That single decision is where most of the density numbers on this page+come from: a fixed bootstrap cost (allocator warm-up, code paging, registries,+detectors) is paid once per process and then shared across however many agents+run inside it, instead of being paid again for every agent.++Everything below was measured on Apple Silicon macOS, `--release` build,+against a deterministic mock inference provider (the `rss-bench` feature),+not real network calls. Treat the absolute numbers as this-machine numbers and+the ratios (density, marginal cost, binary delta) as the parts worth+generalizing. The scripts to reproduce them are listed at the end.++## Fleet: how many agents fit in one process++`library-fleet.sh` runs N concurrent live agents in a single process, with+latency-realistic mock inference (200 ms) so idle time behaves like a real+network wait instead of a busy loop. It reports the *marginal* RSS per+additional agent once the fixed base is paid, which is the number that+actually decides how many agents fit in a box.++| N agents | Marginal KiB/agent | Settled MiB | Idle CPU ms/10s | Threads | FDs |+| ---: | ---: | ---: | ---: | ---: | ---: |+| 50 | 1,985 | 223 | 3 | 71 | 420 |+| 100 | 1,866 | 356 | 3 | 123 | 820 |+| 500 | 1,770 | 1,393 | 3 | 211 | 3,220 |++500 agents in one process, measured, at roughly 1.77 MiB marginal cost each.+Idle CPU stays flat regardless of N, which is the property that matters: an+agent that isn't mid-turn should not be spending cycles. Thread count grows+about 0.35 per agent, which is the one line item worth watching before pushing+past 500 in production.++Thousands of agents on a single box is the direction this is heading, not a+number we've hit yet. The trend across 50/100/500 agents is a settling+marginal cost, not a rising one, which is what makes that direction plausible.++## In-process vs one process per agent++The same benchmark suite includes `library-instances.sh`, which spawns N+independent `library-profile` processes instead of N agents inside one+process. That measured about 47.8-48.2 MiB per instance, flat across N =+10/25/50, which puts roughly 42 instances in a 2 GiB box by summed RSS (an+upper bound; macOS has no PSS-equivalent metric to divide out shared pages).++One process per agent pays the ~30-50 MiB fixed base every time. The+in-process model pays it once. At the measured marginal cost, the one-process+fleet model is roughly 25 times denser than the per-process model for the same+memory budget.++## Cold start++| Scenario | Median settled RSS | Median duration |+| --- | ---: | ---: |+| `agent-turn` (cold, one turn, no delegation) | 47.6 MiB | 102 ms |+| `cold-phases` (nine bootstrap phases: config load, registry init, agent build, memory construction, first turn) | 51.2 MiB | 476 ms |++The `cold-phases` row is a historical measurement: that scenario was removed from the profile binary, so the number stands but cannot be re-run from this tree. Everything else on this page reproduces with the commands below.++A cold agent turn answers in about 102 ms. The full nine-phase bootstrap, the+thing a process pays exactly once, takes 476 ms. After that, a warmed turn in+the same process costs 0.5-1.9 MiB rather than the 26-31 MiB a first turn+retains, because most of a cold turn's cost is executable code paging in for+the first time, not per-turn allocation.++## Slim build footprint++A `--no-default-features --features rss-bench` build (drops every optional+domain) settles at about 15.2 MiB of private physical memory and roughly 42+MiB RSS. The rest of that RSS is reclaimable executable text and allocator+high-water retention, not live data: a deep attribution pass found about 3.2+MiB of live heap and 18.7 MiB of resident executable text inside that 42 MiB.++## Binary size by feature set++Cargo feature gates control what compiles in. Two starting points matter:+Contrib (`[features] default` in `crates/openhuman-core/Cargo.toml`, what a+bare `cargo check` builds) and Product (`scripts/ci/product-features.txt`,+what the desktop app ships).++| Build | Features | Unstripped | Stripped |+| --- | --- | ---: | ---: |+| Default (all gates) | Contrib/Product superset | 115.9 MiB | n/a |+| library-minimal | `skills,flows` | ~81.1 MiB | ~60.4 MiB |+| Pure slim | none | 68.4 MiB | 51.0 MiB |++The `skills,flows` recipe in+[`docs/library-minimal-recipe.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-minimal-recipe.md) is+the supported embed target for a headless host: it keeps SKILL.md execution+and saved-workflow runs, drops voice, web3, media, MCP and the desktop+automation stack, and lands about 30% smaller than the default build. Most of+that gain is binary size and code-paging surface; it only moves settled RSS by+about 3-5 MiB per scenario, since most of the RSS story is initialization and+allocator behavior rather than linked code size.++Do not describe this as a "15 MB binary." The smallest number on this page is+15.2 MiB of private memory in a slim, running process; the smallest binary is+51 MiB stripped with nothing enabled.++## Feature gates and loadable modules++Everything above compiles in at build time through Cargo features (`media`,+`skills`, `flows`, `mcp`, `channels`, `http-server`, `scheduler-gate`,+`file-logging`, `modules`, and more). Beyond that, several domains ship as+loadable native `cdylib` modules rather than being linked into the core+binary at all. The compiled registry pins fourteen records across twelve module names, because `tinyruntime` ships as a router plus two language providers: `tinycomputer`,+`tinysearch`, `tinydocs`, `tinywallet`, `tinyjuice`, `tinyvoice`,+`tinyruntime` with its Node and Python providers, `tinymcp`,+`tinyconnectors`, `tinybox`, `tinychannels` and `tinyhosts`, each behind a+small `*-bus` contract crate. A module loads into the same process and shares+its privileges, so the admission checks (ABI, manifest, dependency, digest)+matter more than for an ordinary dependency. See+[Loadable modules](loadable-modules.md) for the whole model.++## The kernel-floor ratchet++`scripts/kernel-floor.sh` measures the dependency graph of the `flows`+profile (`--no-default-features --features flows`, the surface a second host+would embed) along three numbers: package count, unique crate names, and+native (C/C++) build count. `scripts/kernel-floor.limits` holds the ceiling+for each, and the ratchet only moves down: a change that grows the graph has+to lower those numbers in the same PR, and raising one requires a written+justification a reviewer actually reads. Read the current ceiling out of the+file rather than from here; it moves, and the file keeps a dated history of+every move inline. This+is what stops the dependency floor silently growing back after each gating+effort sheds crates from it.++## How to reproduce++Every number above comes from the driver scripts under `scripts/profile/`,+built around `crates/openhuman-cli/src/bin/library_profile/main.rs`+(scenario implementations) and the `library-profile` / `rss-bench` binaries.+Benchmarks run from these scripts, not in CI.++```bash+# RSS/duration medians across fresh processes, all scenarios+./scripts/profile/library-bench.sh++# Same, against the slim (--no-default-features) recipe+./scripts/profile/library-bench.sh --slim++# Fleet sweep + the 2 GB / 2 vCPU budget gate+./scripts/profile/library-fleet.sh --agents "50,100,500" --target 1000 --budget-mib 2048++# Many-processes counterpart to the fleet sweep+./scripts/profile/library-instances.sh --instances "10,25,50" --hold-secs 30++# Dependency-floor ratchet+scripts/kernel-floor.sh flows+```++`scripts/profile/README.md` documents the remaining scripts (`library-cpu.sh`+for CPU profiling via samply, `library-heap.sh` for live-heap attribution via+dhat). Full methodology, caveats, and the per-scenario breakdown live in+[`docs/library-benchmarking.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-benchmarking.md) and+[`docs/library-minimal-recipe.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-minimal-recipe.md).++## Measurement conditions, stated plainly++These numbers were gathered on macOS, which has no cgroup memory limit to+enforce locally and no `/proc/<pid>/smaps_rollup`, so there is no true PSS+(proportional shared memory) reading available. RSS overcounts shared pages+in a way that matters more as agent count grows. The fleet and instances+numbers are a projection from measured marginal cost, not a live "did it+survive an OOM kill at N agents" test on the target 2 GB / 2 vCPU Linux box.+Every scenario also replaces network inference with a deterministic mock+provider at a fixed latency, so turn timings measure orchestration overhead,+not real model latency. Real Linux cgroup validation is documented follow-up+work, not something this page claims already happened.++For token-level cost rather than process footprint, see [Smart Token+Compression](../features/token-compression.md), which is the other half of+"cheap": it controls how much of what the harness assembles actually reaches+the model.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/quickstart.md b/docs/gitbooks/docs/gitbooks/en/developing/quickstart.mdnew file mode 100644index 0000000000..e6e15eb657--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/quickstart.md@@ -0,0 +1,264 @@+---+description: >-+ A step-by-step path from an empty Cargo project to many agents running on one+ OpenHuman runtime in your own Rust process.+icon: rocket+---++# Rust Quickstart++This page takes you from an empty Cargo project to a fleet of agents running in one process. Each step builds on the last and ends with code you can run. The full reference for every type used here is [Embedding OpenHuman](embedding.md).++## What you get++`openhuman-embed` runs the OpenHuman core inside your binary. There is no daemon to start and no RPC hop: a turn is a function call. You build one `Runtime` per process, then create as many `Agent`s on it as you need. Each agent has its own model, access tier, working directory, MCP servers and skills.++Sharing one process is where the density comes from. The fixed bootstrap cost is paid once, and each extra agent adds a marginal cost. With a mock inference provider, 500 agents in one process measured about 1.8 MiB of marginal memory each. Thousands of agents per box is the direction, not a measured result. The numbers and how to reproduce them are on the [Performance](performance.md) page.++## Prerequisites++You need Rust 1.96.1 or newer, the version pinned in [`rust-toolchain.toml`](https://github.com/tinyhumansai/openhuman/blob/main/rust-toolchain.toml). You also need an API key for any OpenAI-compatible endpoint, or a TinyHumans API key (see step 6).++If you depend on OpenHuman through Cargo as shown below, Cargo fetches the vendored submodules for you. If you build from a clone of the repository instead, initialize them first:++```bash+git submodule update --init --recursive vendor/+```++## Step 1: add the dependency++```toml+[dependencies]+openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed" }+# Needed for the tokio worker settings in step 2.+openhuman_core = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman" }+tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"] }+anyhow = "1"+```++The default feature set is the contributor build. To ship less code, turn defaults off and pick the features you use. The set below keeps the model provider layer and MCP:++```toml+openhuman-embed = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-embed", default-features = false, features = ["inference", "mcp"] }+```++Cargo applies `[patch]` tables only from the top-level workspace, so the ones in OpenHuman's [root `Cargo.toml`](https://github.com/tinyhumansai/openhuman/blob/main/Cargo.toml) do not reach your crate. They make every crate share one copy of `tinytools` and `tinyinference`. If dependency resolution fails over those crates, or you see two incompatible `tinytools` types, add the same `[patch]` sections to your own workspace.++Every feature forwards to the same-named feature on the core. `mcp` and `skills` also gate `AgentSpec::mcp` and `AgentSpec::skills_dir`, so enable them if your agents need those.++## Step 2: build the tokio runtime yourself++Do not use `#[tokio::main]`. A turn is a large async state machine, and a sub-agent nested inside a turn overflows tokio's default 2 MiB worker stack, which aborts the process. Build the runtime with the stack size and blocking-thread limit the core exports:++```rust+use openhuman_core::core::runtime::{AGENT_WORKER_STACK_BYTES, MAX_BLOCKING_THREADS};++fn main() -> anyhow::Result<()> {+ let rt = tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .thread_stack_size(AGENT_WORKER_STACK_BYTES)+ .max_blocking_threads(MAX_BLOCKING_THREADS)+ .build()?;+ rt.block_on(run())+}++async fn run() -> anyhow::Result<()> {+ Ok(())+}+```++The remaining steps fill in `run`.++## Step 3: your first agent++`Harness` is a runtime plus exactly one agent. It is the shortest path to a reply. This version points at an OpenAI-compatible endpoint with a key you supply, uses a throwaway workspace, and is read-only:++```rust+use openhuman_embed::{Access, Harness, Provider, Workspace};++async fn run() -> anyhow::Result<()> {+ let harness = Harness::builder()+ .provider(+ Provider::openai_compatible(+ "https://api.openai.com/v1",+ std::env::var("OPENAI_API_KEY")?,+ )+ .model("gpt-5"),+ )+ .workspace(Workspace::Ephemeral)+ .access(Access::readonly())+ .action_dir(std::env::current_dir()?)+ .build()+ .await?;++ let outcome = harness.run("What can you see in this directory?").await?;+ println!("{}", outcome.reply);+ Ok(())+}+```++Pass the API root as the URL; `/chat/completions` is appended for you. `Workspace::Ephemeral` is removed when the harness drops, so nothing touches an existing install. `Access::readonly()` allows no writes and no shell, which makes it safe to point at any directory.++A complete runnable version, with progress streaming, is the [`run_turn` example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/run_turn.rs):++```bash+OPENHUMAN_EXAMPLE_BASE_URL=https://api.openai.com/v1 \+OPENHUMAN_EXAMPLE_API_KEY=sk-... \+OPENHUMAN_EXAMPLE_MODEL=gpt-5 \+ cargo run -p openhuman-embed --example run_turn -- "What can you see in this directory?"+```++## Step 4: many agents on one runtime++When you need more than one agent, build the `Runtime` directly and create agents from `AgentSpec`s. This is what `Harness` does underneath, so moving to it later is a small change.++```rust+use openhuman_embed::{Access, AgentSpec, Provider, Runtime, Workspace};++async fn run() -> anyhow::Result<()> {+ let runtime = Runtime::builder()+ .workspace(Workspace::dir("/var/lib/my-product/openhuman"))+ .build()+ .await?;++ let provider = Provider::openai_compatible(+ "https://api.openai.com/v1",+ std::env::var("OPENAI_API_KEY")?,+ )+ .model("gpt-5");++ let reviewer = runtime.agent(+ AgentSpec::new("reviewer")+ .system_prompt("You review changes and never edit files.")+ .provider(provider.clone())+ .access(Access::readonly())+ .action_dir("/srv/checkouts/pr-42"),+ )?;++ let fixer = runtime.agent(+ AgentSpec::new("fixer")+ .system_prompt("You act on review findings inside your working directory.")+ .provider(provider)+ .access(Access::full())+ .action_dir("/srv/checkouts/pr-42"),+ )?;++ let review = reviewer.run("Summarise the risks in this change.").await?;+ let fix = fixer+ .turn(format!("Address these findings:\n{}", review.reply))+ .send()+ .await?;+ println!("{}", fix.reply);+ Ok(())+}+```++Agent ids must match `^[a-z0-9][a-z0-9_-]{0,63}$`. Avoid the built-in ids such as `orchestrator`.++The access tier is the main safety control:++* `Access::readonly()` observes only.+* `Access::supervised()` can act, but risky operations wait for a human decision. It turns the autonomy policy on for that agent, so an unattended process stalls at the first approval until the ten-minute timeout denies it.+* `Access::full()` acts autonomously with real shell and file access under `action_dir`. Point it at a directory you are willing to have changed. Credential stores such as `~/.ssh` stay blocked regardless.++`action_dir` is the agent's read and write root. `.trust(path, access)` grants a directory outside it.++MCP servers and skills are per agent. They need the `mcp` and `skills` features, and the runtime must have those domains enabled because agents can only narrow the runtime's set:++```rust+use openhuman_embed::McpServer;++let spec = AgentSpec::new("triage")+ .mcp(McpServer::stdio("github", "gh-mcp", ["stdio"]).deny_tools(["delete_repo"]))+ .skills_dir("./skills/triage");+```++A server declared on one agent is invisible to the others. Skill bundles are copied into `<workspace>/agents/<id>/skills/`, and the operator's `~/.openhuman/skills` stays hidden unless you call `.include_user_skills(true)`. Narrowing which tools an MCP server exposes with `.allow_tools` or `.deny_tools` matters for large servers, because every exposed tool costs prompt budget.++The [`two_agents` example](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-embed/examples/two_agents.rs) runs a reviewer and a fixer end to end.++## Step 5: multi-turn sessions and streaming++`agent.turn(message)` returns a builder. Each outcome carries a `session_id`; pass it back with `.session(..)` to continue the conversation. Without it, a new session is started.++```rust+let first = fixer.run("Run the tests.").await?;+let again = fixer+ .turn("Now fix the failures.")+ .session(&first.session_id)+ .send()+ .await?;+```++Transcripts are keyed by agent id, and a turn resumes only its own thread. With `Workspace::Ephemeral` sessions do not survive the process; use `Workspace::dir(..)` for that.++To watch a turn as it runs, attach a channel with `.on_progress(tx)`:++```rust+let (tx, mut rx) = tokio::sync::mpsc::channel(256);+let printer = tokio::spawn(async move {+ while let Some(progress) = rx.recv().await {+ eprintln!("[progress] {progress:?}");+ }+});+let outcome = fixer.turn("go").on_progress(tx).send().await?;+let _ = tokio::time::timeout(std::time::Duration::from_secs(30), printer).await;+```++The core awaits every send, so a receiver that stops draining stalls the turn. The timeout covers detached sub-agents that can hold a clone of the sender after `send()` returns. Other per-turn options are `.model(id)`, `.temperature(t)`, `.cwd(dir)` and `.origin(..)`.++## Step 6: managed inference with one API key++Instead of bringing a provider key for each agent, you can give the runtime a single TinyHumans API key. Agents that name no `Provider` then run on managed inference, and backend features such as integrations and search use the same key. See [One TinyHumans API key](tinyhumans-api-key.md) for what it unlocks.++`openhuman-embed` alone installs no backend transport, so hosted surfaces answer `BACKEND_UNAVAILABLE:`. To boot connected, use the `RuntimeBuilder` from `openhuman-tinyhumans`, which mirrors the embed builder and installs the transport on `build()`:++```toml+openhuman-tinyhumans = { git = "https://github.com/tinyhumansai/openhuman", package = "openhuman-tinyhumans" }+```++```rust+use openhuman_tinyhumans::{embed::{Access, AgentSpec, Workspace}, RuntimeBuilder};++let runtime = RuntimeBuilder::new()+ .workspace(Workspace::Ephemeral)+ .api_key(std::env::var("TINYHUMANS_API_KEY")?)+ .build()+ .await?;++let agent = runtime.agent(AgentSpec::new("helper").access(Access::readonly()))?;+let reply = agent.run("Hello.").await?;+println!("{}", reply.reply);+```++For a headless process that boots the core itself, set `OPENHUMAN_BACKEND_API_KEY` before startup instead. An agent that names its own `Provider` never uses the key.++## Step 7: going to scale++A few rules keep a large fleet small and predictable:++* Run one `Runtime` per process. A second `build()` returns `RuntimeError::AlreadyRunning`, because the keyring, event bus and domain subscribers are process-wide. Add agents, not runtimes.+* Build narrow. A headless build with `--no-default-features --features "skills,flows"` is about 60 MiB stripped, against 115.9 MiB with every gate on. The recipe is in [`docs/library-minimal-recipe.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-minimal-recipe.md).+* Narrow each agent. `.tool_groups(..)`, `.domains(..)`, `ToolScopeSpec::Named(..)` and `.disallow_tools(..)` cut prompt size and the surface an agent can reach.+* Pick a sandbox mode per agent through `AgentDefinitionSpec`: `SandboxModeSpec::None`, `ReadOnly` (write and execute tools are removed) or `Sandboxed` (commands run in the platform jail or Docker).+* For a cloud host serving many users from one process, use `Workspace::stateless()` with a `SessionStoreProvider` so conversations live in your own database. The embed crate README covers it under "Conversations in a host store".++To measure your own numbers, the scripts and method are in [`docs/library-benchmarking.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/library-benchmarking.md). The public benchmark results and rig are in [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks).++## Other ways in++You do not have to embed the library to use the core.++The JSON-RPC server runs the same core behind HTTP. Start it with `openhuman-core serve`; `GET /schema` lists every method, `GET /health` reports liveness, and `GET /events` streams events. The server lives in [`crates/openhuman-rpc`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-rpc/README.md).++The CLI is the `openhuman-core` binary, which exposes the same controllers as subcommands and is documented in [`crates/openhuman-cli`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-cli/README.md).++The terminal client is `openhuman-tui`, a ratatui front end that boots the core in its own process and drives the same chat surface as the desktop app. See [`crates/openhuman-tui`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-tui/README.md).++## Next steps++* [Embedding OpenHuman](embedding.md) is the full reference for `AgentSpec`, `Access`, workspaces, MCP, skills and the examples.+* [Architecture](architecture/architecture.md) and the [agent harness](architecture/agent-harness.md) explain how a turn runs.+* [Loadable modules](loadable-modules.md) covers the module contracts the core composes.+* [Pluggable engines](engines.md) covers the inference, memory and search backends an agent chooses by config.+* [Performance and footprint](performance.md) has the measured density, cold-start and binary-size numbers.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/release-policy.md b/docs/gitbooks/docs/gitbooks/en/developing/release-policy.mdnew file mode 100644index 0000000000..7721f76e4d--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/release-policy.md@@ -0,0 +1,150 @@+---+description: Release cadence, version policy, OAuth-and-installer rules. How shipping works.+icon: ship+---++# Release Policy++This runbook describes how we avoid users completing OAuth (including Gmail) on outdated desktop installers while the canonical flow is the latest release.++## Distribution++- GitHub Releases for [tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman/releases) are the primary source for desktop builds.+- The Tauri updater endpoint (see `scripts/prepareTauriConfig.js` and release workflows) should point users at the current release artifacts.+- Retiring old stable artifacts: When dropping a release line, remove or hide obsolete installer assets on GitHub Releases, update website / CDN download links to releases/latest (or current), refresh the updater manifest (e.g. Gist / `latest.json`) so it does not point users at deprecated builds, and spot-check that old direct URLs are redirected, 404, or 410 where appropriate. Verification: try known-old asset URLs from docs or bookmarks and confirm they no longer deliver primary install paths.++## Minimum app version for OAuth++Production web builds embed a minimum supported app semver at build time so OAuth deep links cannot complete on deprecated binaries. Each installer carries the floor that was set when that build was produced; raising the floor for users who never upgrade requires a new release they install (or in-app update). Optional future work: enforce a moving minimum via a runtime API with the bundled value as fallback only.++| Variable | Purpose |+| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |+| `VITE_MINIMUM_SUPPORTED_APP_VERSION` | e.g. `0.51.0` - desktop app must be ≥ this to finish `openhuman://oauth/success`. |+| `VITE_LATEST_APP_DOWNLOAD_URL` | Optional; defaults to `https://github.com/tinyhumansai/openhuman/releases/latest`. Opened when the gate blocks OAuth. |++Configure these as GitHub Actions variables. They must be present on both the standalone `pnpm build` step and the `tauri-apps/tauri-action` step env in `.github/workflows/build-desktop.yml` (the reusable matrix invoked by `release-production.yml` / `release-staging.yml`) so the Vite bundle embedded in shipped installers includes the gate. Leave `VITE_MINIMUM_SUPPORTED_APP_VERSION` unset for local dev (gate disabled).++Implementation: `app/src/utils/oauthAppVersionGate.ts`, `app/src/utils/desktopDeepLinkListener.ts`.++## Gmail / Google Cloud OAuth++- Redirect URIs in Google Cloud Console must match the current backend + tunnel callback paths.+- The desktop scheme (`openhuman://`) is stable; the installed binary must meet the minimum version when `VITE_MINIMUM_SUPPORTED_APP_VERSION` is set.++## Release checklist (avoid regressions)++1. Bump `app/package.json` and `crates/openhuman-app/tauri.conf.json` (and root `Cargo.toml` / core) per existing version workflows.+2. When dropping support for older installs, set `VITE_MINIMUM_SUPPORTED_APP_VERSION` to the new floor before or with that release (repo Actions variables + both workflow steps above).+3. Remove, redirect, or retire older stable installers and stale updater entries from user-facing surfaces (GitHub Release assets, website, CDN, updater feed). Confirm deprecated artifacts are not reachable from default install/update flows.+4. Smoke-test Gmail connect on a fresh install from releases/latest.+5. Complete the [manual smoke checklist](https://github.com/tinyhumansai/openhuman/blob/main/docs/RELEASE-MANUAL-SMOKE.md), then paste the completed sign-off block (verbatim, with every checked item left checked) as a GitHub commit comment on the `v<version>-staging` tagged commit that QA validated (there is no release PR in the promotion flow). Before approving the production run, the `Release-Approval` required reviewer verifies (a) the sign-off comment exists on the staging-tagged commit and (b) the production run actually targets that validated content: pass the staging-tagged SHA as `commit_sha`, or confirm nothing but `[skip ci]` version-bump commits separate it from the run's target. Anything more than bump commits means new content QA never smoked: re-run staging first.++## Branch model and CI lanes++Two long-lived branches, two CI lanes:++- `main`: where all feature/fix PRs land. Every PR runs CI Fast ([`ci-fast.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/ci-fast.yml)), with quality checks and complete unit-test suites for changed areas, gated at ≥ 80% diff coverage.+- `release`: a maintainer-promoted snapshot of `main` that releases are cut from. PRs targeting `release` and every push to `release` run CI Full ([`ci-full.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/ci-full.yml)): complete unit suites, Rust mock-backend E2E, Playwright web E2E, and desktop E2E on Linux. macOS and Windows desktop E2E are a manual dispatch whose inputs default to off until a native driver lands for each, so cross-platform desktop signal is opt-in rather than part of the matrix. The `CI Full Gate` check aggregates every lane except the Playwright spec run, which is non-blocking signal for now (`continue-on-error`, flaky under CI contention, #3615): a green gate does not prove Playwright specs passed, so check that lane's result in the run before cutting. Only the Playwright artifact _build_ is gated.++The cycle:++1. A maintainer dispatches [`promote-main-to-release.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/promote-main-to-release.yml), which pushes a merge commit from `main` into `release` (no PR). Re-dispatching refreshes `release` with main's latest while preserving fix commits already on `release`; when `release` already contains `main` it's a no-op.+2. CI Full runs on the promotion push. If it finds breakage, anyone with write access opens a fix PR directly against `release`; fix PRs run both lanes (CI Fast for quick lint and coverage feedback, CI Full as the merge-blocking `CI Full Gate` check), and the post-merge push re-runs CI Full on the merge result.+3. Once CI Full is green on `release` HEAD, cut production with `release-production.yml`. Staging may instead be dispatched from `main` when QA needs to validate main before promotion. The release workflows do not query or enforce the `CI Full Gate`; operators verify the relevant CI evidence before cutting.+4. A cut sourced from `release` back-merges `release` into `main` (`scripts/release/merge-release-into-main.sh`: fast-forward when possible, else a versioned merge commit such as `chore(release): merge release v1.2.4 back into main`), so bump commits and fix commits flow back. A staging cut sourced from `main` needs no back-merge. Version-bump commits carry `[skip ci]`.++Required GitHub settings for this model (repo Settings → Rules): `main` requires the `PR CI Gate` status check on PRs; `release` requires PRs for non-bypass actors with the `CI Full Gate` status check required (it runs on PRs targeting release); the release GitHub App's identity sits on the bypass list of both rulesets so the promote/release workflows can push directly.++## Workflows: staging vs. production++Two first-class GitHub Actions workflows, one per environment. Pick by intent rather than toggling a flag. Staging follows the selected `main` or `release` dispatch ref; production always checks out `release`, regardless of the dispatch ref shown by GitHub's workflow UI.++| Workflow | Branch | Bumps | Tags pushed | Concurrency group | Use when |+| -------------------------------------------------------------------------- | ------------------- | -------------------------------------------------- | -------------------- | -------------------- | --------------------------------------------------------------------------------------- |+| [`release-staging.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/release-staging.yml) | `main` or `release` | `patch` only | `v<version>-staging` | `release-staging` | Cutting a staging build for QA from the selected branch. |+| [`release-production.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/release-production.yml) | `release` | `patch` / `minor` / `major` (`release_type` input) | `v<version>` | `release-production` | Shipping a production release from validated `release` HEAD (or a pinned `commit_sha`). |++The matrix build / sign / Sentry-DIF / artifact-upload pipeline used by both flows lives in [`.github/workflows/build-desktop.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/build-desktop.yml) as a `workflow_call` reusable workflow. The two top-level workflows above own ref resolution, version bumping, tagging, and publish/cleanup; the build itself is shared.++### Android / Google Play++Android releases are handled by the separate [`.github/workflows/android-compile.yml`](https://github.com/tinyhumansai/openhuman/blob/main/.github/workflows/android-compile.yml) workflow, which builds a release Android App Bundle (`.aab`), signs it with the Play upload key, and uploads it to Google Play when publishing is enabled. The workflow keeps the unsigned and signed AABs as Actions artifacts for audit/debugging.++Manual Android uploads use the same workflow:++```bash+pnpm --dir app release:android:play -- --track internal+pnpm --dir app release:android:play -- --ref main --track production --status draft+```++Required GitHub Actions secrets:++| Secret | Purpose |+| ---------------------------------- | ------------------------------------------------------------------------------------------------- |+| `ANDROID_UPLOAD_KEYSTORE_BASE64` | Base64-encoded Play upload keystore (`.jks`). Use the upload key, not the Google app signing key. |+| `ANDROID_UPLOAD_KEY_ALIAS` | Keystore alias for the upload key. |+| `ANDROID_UPLOAD_KEYSTORE_PASSWORD` | Keystore password. |+| `ANDROID_UPLOAD_KEY_PASSWORD` | Key password. |+| `GOOGLE_PLAY_SERVICE_ACCOUNT_JSON` | Raw JSON for the Play Console service account with release permissions for `com.openhuman.app`. |++Optional GitHub Actions variables:++| Variable | Default | Purpose |+| --------------------- | ----------- | ----------------------------------------------------------------------- |+| `ANDROID_PLAY_TRACK` | `internal` | Play track to upload to (`internal`, `alpha`, `beta`, or `production`). |+| `ANDROID_PLAY_STATUS` | `completed` | Play release status (`completed`, `draft`, `inProgress`, `halted`). |++Google Play requires each upload to use a monotonically increasing Android `versionCode`. The release bump scripts update `app/src-tauri-mobile/tauri.conf.json`, `app/src-tauri-mobile/Cargo.toml`, and `app/src-tauri-mobile/Cargo.lock` alongside desktop files so the generated Android `tauri.properties` moves with each release.++### Cutting a staging build++1. Run Release (Staging) via `workflow_dispatch` from `release` (optionally pinning a release-reachable `commit_sha`; `create_tag = false` bumps + commits without tagging or building).+2. The workflow bumps `patch` on `release`, commits `chore(staging): vX.Y.Z [skip ci]`, pushes, and creates an immutable `vX.Y.Z-staging` tag at that commit.+3. Build matrix runs from the tag (not release HEAD), so reruns rebuild byte-identical content even if `release` has moved on.+4. The bump commit (and anything else on `release`) is merged back into `main`.+5. On failure the staging tag is auto-deleted; the bump commit on `release` stays so the next cut continues from `vX.Y.(Z+1)`.++There is no separate `staging` branch: staging cuts and production releases both live on `release`. The two are distinguished only by tag suffix (`-staging` vs none) and by which workflow created the tag.++### Shipping a production release++1. Run Release Production via `workflow_dispatch` with the desired `release_type` (`patch` / `minor` / `major`), from `release` HEAD or a pinned release-reachable `commit_sha`.+2. The run first parks on the `review-approval` job (`environment: Release-Approval`); a [required reviewer](#release-app-token-approval-gate-and-rotation) must approve before anything is pushed. Only after approval does `prepare-build` run the bump-and-tag path: bump on `release`, commit `chore(release): vX.Y.Z [skip ci]`, push, tag `vX.Y.Z`, build, publish.+3. `release` is merged back into `main` right after the cut.++### Tag policy and rollback++- **Naming.** Staging tags use the SemVer pre-release suffix `-staging` (`v1.2.4-staging`) so they sort _before_ the matching production tag.+- **Collisions.** Both workflows fail fast if the target tag already exists locally or on `origin`. Resolve by deleting the stale tag (org maintainers only) or bumping past it.+- **Rollback (production).** A failed build matrix triggers `cleanup-failed-release`, which deletes both the draft GitHub Release and the `v<version>` tag.+- **Rollback (staging).** A failed staging build deletes the `v<version>-staging` tag. The bump commit on the selected source branch is left in place; the next staging cut continues from the new patch number rather than re-using it (we accept a small "gap" in patch numbers over racing with concurrent merges).+- **Who can delete tags.** Same write-access as `main`. Workflow-driven cleanup deletes run with the workflow's token via `actions/github-script` (the GitHub App token is only used by `prepare-build` for the bump commit + tag push); manual deletes (`git push --delete origin <tag>`) require equivalent maintainer permissions.++## Release App token: approval gate and rotation++`release-production.yml` bumps the version, commits to `release` and back-merges into `main`, pushing those commits + tag with a GitHub App token (`secrets.XGITHUB_APP_ID` / `secrets.XGITHUB_APP_PRIVATE_KEY`) that bypasses branch protection. The same App pushes staging bumps to the selected `main` or `release` source (`release-staging.yml`) and promotion merge commits (`promote-main-to-release.yml`). A leaked private key (via a log, a compromised action, or a misconfigured runner) would let an attacker push arbitrary commits to protected branches ([CWE-250: Execution with Unnecessary Privileges](https://cwe.mitre.org/data/definitions/250.html)). Two controls bound that blast radius.++### Manual approval gate++The `review-approval` job runs before `prepare-build` and parks every production run on the `Release-Approval` GitHub environment, so a human must approve before any push happens.++One-time setup (repo Settings → Environments):++1. Create an environment named `Release-Approval` (exact name: the workflow references it verbatim).+2. Under Deployment protection rules, enable Required reviewers and add the maintainers allowed to authorize a production push to `main`. A reviewer cannot approve their own run unless _Prevent self-review_ is left off; for a release gate, keeping a second approver is preferred.+3. (Optional) Set a short wait timer of 0. The gate is a human decision, not a delay.++When a production run starts it shows "Waiting" on the `review-approval` job; an approver opens the run and clicks Review deployments → Approve. Rejecting (or cancelling) leaves `prepare-build` skipped, so nothing is pushed.++### Quarterly key rotation++Rotate `XGITHUB_APP_PRIVATE_KEY` every quarter (and immediately on any suspected exposure). Schedule: end of Mar / Jun / Sep / Dec.++1. In the GitHub App settings (Org → Settings → Developer settings → GitHub Apps → the release App), under Private keys click Generate a private key. Download the new `.pem`.+2. Update the repo secret: Settings → Secrets and variables → Actions → `XGITHUB_APP_PRIVATE_KEY` → paste the full new key (including the `-----BEGIN/END-----` lines). `XGITHUB_APP_ID` is unchanged.+3. Trigger a low-risk verification run (e.g. Release (Staging)) and confirm the Generate GitHub App token step succeeds and the push authenticates.+ Do not use Release Production for this check unless you intentionally want to cut a real bump commit: even with `create_release = false`, `prepare-build` still bumps the version and commits to `release` (staging with `create_tag = false` does too, but skips the tag/build and is the lower-risk probe).+4. Back in App settings → Private keys, delete the old key so only the freshly-issued one remains valid.+5. Record the rotation date in the PR description or the ops log so the next quarter's owner can see when it last happened.++Rotating invalidates any copy of the old key that may have leaked, capping the exposure window at one quarter.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/testing-strategy.md b/docs/gitbooks/docs/gitbooks/en/developing/testing-strategy.mdnew file mode 100644index 0000000000..7fb7a255b8--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/testing-strategy.md@@ -0,0 +1,296 @@+---+description: How OpenHuman tests its product - Vitest, cargo test, WDIO E2E. Where each test goes.+icon: vial+---++# Testing Strategy++How OpenHuman tests its product. Source of truth for "where does my test go?". Companion to [`TEST-COVERAGE-MATRIX.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/TEST-COVERAGE-MATRIX.md).++---++## Layers++| Layer | Where it lives | What it tests | Driver |+| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |+| **Rust unit** | Sibling `<module>_tests.rs` files beside the module under `crates/openhuman-core/src/<domain>/`, or a `tests/` subdir under a domain (e.g. `crates/openhuman-core/src/channels/tests/`); inline `#[cfg(test)] mod` blocks and files named `tests.rs`/`test.rs` fail `pnpm rust:layout` | Pure domain logic, schemas, RPC handler shape, in-memory state machines | `cargo test` |+| **Rust integration** | `tests/*.rs` at repo root, each an explicit `[[test]]` target in `crates/openhuman-cli/Cargo.toml` (`autotests = false`); `tests/raw_coverage/*.rs` is globbed by `build.rs` into the single `raw_coverage_all` target | Full domain wiring with real Tokio runtime, mock external services, JSON-RPC end-to-end (`tests/json_rpc_e2e.rs`), domain × domain interactions | `pnpm test:rust` (which calls `bash scripts/test-rust-with-mock.sh`) |+| **Vitest unit** | Co-located as `*.test.ts(x)` next to source under `app/src/**`, or under `app/src/**/__tests__/` | React components, hooks, store slices, pure utilities, service-layer adapters | `pnpm test` (root) or `pnpm --filter openhuman-app test:unit` |+| **WDIO E2E** | `app/test/e2e/specs/*.spec.ts` | Full desktop flow: UI → Tauri → in-process core → JSON-RPC; user-visible behaviour | All platforms: Linux CI drives the Wry-based debug build (macOS/Windows desktop E2E is disabled until a native driver lands, #5485). See [E2E Testing](e2e-testing.md). |+| **Manual smoke** | [`docs/RELEASE-MANUAL-SMOKE.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/RELEASE-MANUAL-SMOKE.md) | OS-level surfaces drivers cannot assert: TCC permission prompts, Gatekeeper, code signing, DMG install, OS-native toasts | Human at release-cut; the completed sign-off block is pasted as a GitHub commit comment on the `v<version>-staging` tagged commit QA validated. There is no release PR in the promotion flow, see [Release Policy](release-policy.md) |++---++## Decision tree - where does my test go?++```text+Is the change behind the JSON-RPC boundary (in `crates/openhuman-core/src/`, `crates/openhuman-rpc/`, or `crates/openhuman-embed/`)?+├─ YES - does it cross domains or talk to external services?+│ ├─ YES → Rust integration (tests/*.rs)+│ └─ NO → Rust unit (next to source)+└─ NO - change is in `app/`+ ├─ Is it a pure function, hook, slice, or component in isolation?+ │ └─ YES → Vitest unit (*.test.tsx co-located)+ └─ Is it user-visible AND it crosses UI ⇄ Tauri ⇄ embedded core ⇄ JSON-RPC?+ ├─ YES → WDIO E2E (app/test/e2e/specs/*.spec.ts)+ └─ Is it OS-level (TCC, Gatekeeper, install, OS toasts)?+ └─ YES → Manual smoke checklist+```++If a change touches more than one of these, write a test in **each** layer it touches. Don't substitute one for another.++---++## Failure-path requirement++Every feature leaf in the coverage matrix must have **at least one failure / edge** assertion in addition to the happy path. Examples:++- File-write tool: happy = wrote bytes; failure = path-restriction denial.+- OAuth flow: happy = token issued; edge = expired refresh token recovery.+- Memory store: happy = stored + recalled; edge = forget-then-recall returns nothing.++A spec that asserts only the happy path is incomplete.++---++## Mock policy++- **No real network in unit / integration / E2E.** Use the shared mock backend (`scripts/mock-api-core.mjs`, `scripts/mock-api-server.mjs`, `app/test/e2e/mock-server.ts`).+- Admin endpoints for tests: `GET /__admin/health`, `POST /__admin/reset`, `POST /__admin/behavior`, `GET /__admin/requests`.+- **External services** (Telegram, Slack, Gmail, Notion, Ollama, OpenAI, etc.) are stubbed at the mock backend level; tests assert the request shape via `getRequestLog()`.+- The only acceptable exception is a documented release-cut manual smoke step.++---++## Determinism rules++- No wall-clock waits, use `waitForApp`, `waitForAppReady`, `waitForWebView` helpers, or explicit element-readiness predicates.+- No shared filesystem state, every E2E spec runs inside an isolated `OPENHUMAN_WORKSPACE` (created/cleaned by `app/scripts/e2e-run-spec.sh`).+- No order-dependent specs, each spec must pass when run alone.+- No reliance on absolute coordinates or animation timing.+- Prefer synthesizing keyboard input via `browser.execute(...)` over `browser.keys()` (see `command-palette.spec.ts` for the pattern).++---++## What the existing harness gives you++- **Mock backend bootstrapping**: `startMockServer` / `stopMockServer` in `app/test/e2e/mock-server.ts`.+- **Auth shortcut**: `triggerAuthDeepLink` / `triggerAuthDeepLinkBypass` in `helpers/deep-link-helpers.ts` skips real OAuth.+- **Element helpers**: `clickNativeButton`, `waitForWebView`, `clickToggle` in `helpers/element-helpers.ts`, use these instead of raw `XCUIElementType*` selectors.+- **Shared flows**: `completeOnboardingIfVisible`, `navigateViaHash`, `navigateToSkills`, `walkOnboarding` in `helpers/shared-flows.ts`.+- **Core RPC from spec**: `callOpenhumanRpc` in `helpers/core-rpc.ts`, drives the embedded core directly when a UI step would be brittle.+- **Platform guards**: `isTauriDriver` and `supportsExecuteScript` in `helpers/platform.ts`. Desktop E2E runs the debug binary under Xvfb through `tauri-driver` on Linux; the Appium Chromium-driver backend went away with CEF, and macOS and Windows have no automated desktop session yet.+- **Artifact capture on failure**: `captureFailureArtifacts` runs from `wdio.conf.ts`, screenshots + DOM dumps land under `app/test/e2e/artifacts/`.++---++## Naming + structure conventions++- WDIO specs: `<feature-area>-flow.spec.ts` for end-to-end product flows; `<feature>.spec.ts` for narrower surfaces.+- Vitest co-location: prefer `Component.tsx` + `Component.test.tsx` siblings; use `__tests__/` only when grouping multiple related tests.+- Rust integration tests: snake_case file matching the surface, `<feature>_e2e.rs` for JSON-RPC-driven flows, `<feature>_integration.rs` for cross-domain.+- Each `describe` / `mod tests` block maps to a feature-list ID range, link the matrix row in a comment if the mapping is non-obvious.++---++## Pre-merge gates++Run before opening a PR. CI runs the same set, but local runs are faster:++```bash+# Rust core+cargo fmt --check+cargo check --manifest-path Cargo.toml # covers openhuman-core, openhuman-embed, openhuman-rpc, openhuman-tui+cargo clippy --manifest-path Cargo.toml -- -D warnings+cargo test --manifest-path Cargo.toml++# Tauri shell+cargo check --manifest-path crates/openhuman-app/Cargo.toml++# Frontend+pnpm typecheck+pnpm lint+pnpm format:check+pnpm test # vitest, via the app workspace++# Rust integration with mock backend+pnpm test:rust++# E2E (slow - run when behaviour changes user-visibly)+pnpm --filter openhuman-app test:e2e:build+bash app/scripts/e2e-run-spec.sh test/e2e/specs/<your-spec>.spec.ts <id>+```++---++## Not driver-automatable - manual smoke required++Some surfaces cannot be driven by WDIO / Appium because they cross OS-level trust boundaries or hardware paths. The complete checklist + sign-off block lives in [`docs/RELEASE-MANUAL-SMOKE.md`](https://github.com/tinyhumansai/openhuman/blob/main/docs/RELEASE-MANUAL-SMOKE.md), that file is the source of truth for what must be verified per release. Examples of what it covers:++- macOS TCC permission prompts (Accessibility, Input Monitoring, Microphone)+- Gatekeeper signature validation on first launch+- Code-sign integrity (`codesign --verify --deep --strict`)+- DMG install / drag-to-Applications flow+- Auto-update download + relaunch+- OS-native notification toasts on Linux (no display server visible to the driver beyond Xvfb)++If a feature has no automated coverage AND is not on the manual smoke list, treat it as untested, open a coverage gap.++---++## Coverage matrix as the contract++Every feature leaf in the [coverage matrix](https://github.com/tinyhumansai/openhuman/blob/main/docs/TEST-COVERAGE-MATRIX.md) maps to:++1. A test path or paths, **or**+2. A justified `🚫` with a manual-smoke entry.++When you add / remove / rename a feature, **update the matrix row in the same PR**. CI will guard this contract once #965 lands.++---++## A red Rust suite locally is usually not a defect++Most local Rust failures in this repo are environmental, and the environments+fail in ways that look exactly like product defects. Work down this list before+concluding anything. Each step is one command, and every one of them has caught+a wrong conclusion that was already on its way into an issue.++**Every prerequisite below carries the failure you get without it.** A step with+its failure attached is self-auditing: anyone can check in thirty seconds+whether it is still true, and a stale one announces itself. A bare list of steps+cannot be audited at all, which is how it rots into folklore. *If you cannot+produce the failure for an item, it does not belong here.*++**A note that tells you the cause is not evidence of the cause.** A line in a+doc or a memory saying "these fail locally, it is provisioning" is a+*pre-supplied conclusion*. It terminates the investigation before it starts,+which is worse than no note at all: one such note sent a worker looking for a+provisioning gap when the real cause was a product defect+(`agent definition \`harness\` was not found`, openhuman#6487). Use the steps,+not the folklore.++### 1. Did anything compile?++`cargo` exits **101** for at least three states that are identical from the+shell: nothing compiled, a test asserted false, or the process aborted.++```bash+grep -c "^test result" run.log # 0 = nothing ran+```++Zero `test result` lines means the question is *compilation or abort*, never+"which test failed". Then read the **first** error line:++- `failed to load source for dependency <x>` / `No such file or directory` →+ a submodule is not checked out.+- `fatal runtime error: stack overflow` with `signal: 6, SIGABRT` and no+ `test result` line at all → the process aborted; see step 3.++### 2. Are the submodules actually there, at every depth?++Some crates depend on submodules **nested inside other submodules**.+`openhuman-tinyhumans` is the clearest case: it needs `vendor/tinyhumans-sdk`+(top level) **and** `vendor/tinyagents/vendor/tinytools` (nested). A plain+`git submodule update --init` fetches the first and silently not the second, so+the obvious command leaves you with a compile failure that reads as a test+failure.++```bash+git submodule update --init+git -C vendor/tinyagents submodule update --init --recursive+```++*Falsified:* deinitialising `vendor/tinyagents/vendor/tinytools` and re-running+`cargo test -p openhuman-tinyhumans` gives, with **no** `test result` line:++```text+error: failed to get `tinytools` as a dependency of package `openhuman-cli v0.63.31`+ failed to load source for dependency `tinytools`+ No such file or directory (os error 2)+```++**Check content, never status.** `git submodule status` prints `-` only for+*unregistered* modules, and registration happens **before** checkout, so a+mid-flight init reads as ready while every working tree is still empty.+Observed mid-`update --init`: **13 `+`, 3 ` `, zero `-`** while `du -sh vendor`+was **120K** and `ls vendor/tinychannels` was empty.++```bash+du -sh vendor # 120K = empty; a real checkout is GBs+ls vendor/<module> | wc -l # 0 = empty, whatever status says+```++### 3. Is your feature set the one CI uses?++`cargo test -p openhuman --lib` on default features is a **materially smaller+product** than CI builds, and the difference changes test *outcomes*, not just+which tests exist.++The mechanism is worth understanding because it is invisible in the output: a+feature flag can gate the *registration* of a tool, a test's expected side is a+static allowlist while its actual side is computed by **introspecting the built+binary**, and so the flag silently moves the actual. Nothing is stubbed, nothing+is skipped, and the failure names a product concept,+*"agents that carry tools but whose prompt names none of them,"* with no+mention of a feature anywhere.++*Falsified, from the two runs side by side:* on `0f1ecc9d2`, `openhuman --lib`+fails **5** tests on default and **3** under CI's set; the two that differ are+pure profile artefacts+(`every_prompt_names_at_least_one_tool_it_can_call` needs `runtime-node`,+`the_withheld_block_renders_for_a_renamed_session_with_a_filter` needs+`documents`). Reproduce CI exactly before asserting anything:++```bash+RUST_MIN_STACK=67108864 cargo test -p openhuman --lib \+ --features "$(bash scripts/ci/product-features.sh)"+```++Tracked as openhuman#6512; per-profile detail in openhuman#6486.++**`RUST_MIN_STACK` is per-suite, not universal.**++*Falsified for `openhuman-tinyhumans`:* removing it and re-running still gives+`183 passed; 0 failed`. It is **not** a requirement there.++*Reported for `openhuman --lib`:* `web_chat` aborts with+`fatal runtime error: stack overflow` without it, which is why the CI lane+exports it. Not reproduced here: treat that as the reason the CI command above+carries it, and re-verify before relying on it elsewhere.++Two crates, one variable, opposite answers. That is the argument against a+single blanket recipe: do not add a prerequisite by reflex. One that is not+needed teaches contributors the docs are unreliable, and it is precisely how the+misleading note above came to exist: someone's defensively-accumulated setup,+written down as necessity, never falsified.++### 4. Only now suspect a defect, and make the silence speak++If it compiled, the submodules are present and the feature set matches CI, then+a failure may be real. The trap at this stage is a layer that *correctly*+discards detail: a sanitizer, a scrubber, a redactor. The symptom is a generic+message where a specific one was produced.++Patch the discarding line to print what it drops, run once, and read the+underlying error. On openhuman#6487 a sanitized+`hosted agent invocation was rejected by policy` was hiding+`Validation("agent definition \`harness\` was not found")`, which named the+defect outright. **Reading seven links of a chain correctly is not the same as+watching it fire.**++### Why this order++The cheap checks are first because a wrong answer early is invisible later: a+suite that never compiled reports the same exit code as one that failed, and a+plausible-but-wrong explanation gets *confirmed* rather than tested, because+confirming it succeeds. Knowing that features matter is not enough: the rule is+not applied at the moment of asserting. Running CI's literal command is.++---++## When in doubt++- Push the test as low in the layer stack as possible (Rust unit > Rust integration > Vitest > WDIO). Lower layers are faster, more deterministic, and cheaper to run.+- WDIO is for behaviours that genuinely cross UI ⇄ Tauri ⇄ embedded core ⇄ JSON-RPC. Don't drive a unit-testable concern through WDIO just because the UI exists.+- A failing happy path is a regression. A missing failure-path test is a gap. Both are bugs.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/theming.md b/docs/gitbooks/docs/gitbooks/en/developing/theming.mdnew file mode 100644index 0000000000..30adb5973c--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/theming.md@@ -0,0 +1,142 @@+---+description: >-+ The CSS token system behind every theme: how tokens are defined, how+ Tailwind consumes them, and how to add one.+icon: palette+---++# Theming (Token System)++OpenHuman is fully re-skinnable at runtime. Colours and fonts are driven by CSS+variables (the "tokens"), so a theme is just a set of values for those variables.+This page is the contributor reference for the token system.++## How it works++1. **Tokens**: `app/src/styles/tokens.css` defines every themeable colour as a+ space-separated **RGB channel triple** (e.g. `--surface: 255 255 255;`) plus+ font-role vars (`--font-title/heading/body/mono/serif`). The Light palette+ lives in `:root`; the Dark palette in `:root.dark`.++2. **Tailwind wiring**: the app runs Tailwind v4, so there is no+ `tailwind.config.js`. The `@theme` block in `app/src/index.css` exposes each+ token as a utility colour (`--color-surface: rgb(var(--surface));`, and so+ on), and Tailwind's opacity-modifier support handles `bg-surface/50` and+ `bg-primary-500/10` without any extra templating. Channel format (a+ space-separated RGB triple, never a hex string) is what makes that work: a+ hex string can't be composed with an opacity modifier this way.++3. **Runtime application**: `app/src/providers/ThemeProvider.tsx` resolves the+ active `Theme` and writes its overrides as inline `--token` / `--font-<role>`+ variables on `<html>`, toggling `.dark` from `theme.isDark`. Variables a theme+ doesn't override fall through to the tokens.css defaults; variables left over+ from a previous theme are removed on switch.++4. **State**: `app/src/store/themeSlice.ts` holds `activeThemeId` and+ `customThemes`. Built-in presets live in `app/src/lib/theme/presets.ts`.+ Users edit themes in **Settings → Theme Studio**+ (`app/src/components/settings/panels/ThemeStudioPanel.tsx`).++## Token taxonomy++| Group | Tokens | Tailwind utilities |+| -------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |+| Surfaces | `surface`, `surface-canvas`, `surface-muted`, `surface-subtle`, `surface-strong`, `surface-hover`, `surface-overlay` | `bg-surface`, `bg-surface-muted`, … |+| Text | `content`, `content-secondary`, `content-muted`, `content-faint`, `content-inverted` | `text-content`, `text-content-muted`, … |+| Borders | `line`, `line-strong`, `line-subtle` | `border-line`, `border-line-strong`, … |+| Accents | `primary-*`, `sage-*`, `amber-*`, `coral-*` (shades 50…950) | `bg-primary-500`, `text-coral-600`, … (var-backed, themeable, unchanged names) |+| Fonts | `font-title`, `font-heading`, `font-body`, `font-mono`, `font-serif` | `font-title`, `font-heading`, `font-body`, … |++The legacy `--cmd-*` and `--color-*` variable sets are thin aliases over these+canonical tokens. Don't add new colours there.++## Authoring components++- Use semantic utilities (`bg-surface`, `text-content`, `border-line`) for+ neutral surfaces/text/borders instead of `bg-white dark:bg-neutral-900` etc.+ You almost never need `dark:` variants for these, because the token flips for you.+- Use the accent palettes (`primary`/`sage`/`amber`/`coral`) for semantic colour;+ they're themeable with no extra work.+- Avoid hardcoded hex in `className` or inline `style`, since those bypass theming.++## Colour as identity: the four-ramp ceiling++A recurring shape in this codebase is a lookup table that answers "which thing+is this?" with a colour: a skill category, an event-log domain, a notification+provider, a catalogue source. Those tables are where stock Tailwind ramps keep+creeping back in, because a table with nine rows wants nine hues and the app+ships four.++**There are exactly four themeable ramps: `primary`, `sage`, `amber`, `coral`.**+Everything else in Tailwind's default palette (`emerald`, `violet`, `sky`,+`teal`, `indigo`, `cyan`, `rose`, `pink`, `purple`, …) resolves to a fixed oklch+value that ignores the user's active theme entirely. A table built on those hues+looks fine in the default skin and falls apart in every other one.++### The rule++1. **Map a stock ramp to its themeable equivalent at the same shade step:**+ `red → coral`, `green`/`emerald` → `sage`, `orange → amber`, `blue → primary`.+ `bg-emerald-50 text-emerald-700` becomes `bg-sage-50 text-sage-700`.++2. **Hues that have no equivalent do not get one.** `violet`, `teal`, `sky`,+ `cyan`, `indigo`, `pink` and `purple` are not "nearly primary" or "nearly+ sage". Do not invent a fifth ramp, do not duplicate an existing one under a+ new name, and do not reach for `--accent-lavender` and friends: those are+ fixed hexes, not ramps.++3. **When a table needs more than four distinct hues, send the surplus rows to+ the neutral pair the table already defines** (`bg-surface-subtle+text-content-secondary`, or whatever that table's "unknown"/"other" row+ uses). Never let two rows collide on the same ramp: two domains rendering+ identically destroys the exact distinction the table exists to encode, which+ is strictly worse than rendering one of them in neutral.++4. **Decide which rows keep a hue by which distinction a reader acts on.** The+ badge almost always prints its own label, so colour is a scanning aid, not+ the information itself. Spend the four ramps on the readings that change what+ someone does, and let the rest go neutral. Keep the semantics honest while+ you are at it: `coral` reads as failure, so an ordinary row painted coral+ makes routine state look broken. Leaving a ramp unassigned is a legitimate+ outcome.++Worked examples in the tree:++| Table | Rows | Kept a hue | Why |+| --------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |+| `skills/skillIcons.tsx` `CATEGORY_META` | 9 | `Built-in` (primary), `Productivity` (sage), `Social` (coral), `Tools & Automation` (amber) | `Channels`, `Chat` and `Platform` share the neutral tone of `All` / `Other` |+| `skills/SkillsExplorerTab.tsx` `SOURCE_COLORS` | 6 | `built-in` (sage), `optional` (primary) | The four remote catalogues print their own name; provenance tier is the distinction that matters |+| `skills/SkillsExplorerTab.tsx` `FORMAT_MAP` | 5 rows, 3 tones | Hermes family (primary), ClawHub family (sage), `legacy` (amber) | Three tones fit under the ceiling, so nothing is lost |+| `settings/panels/EventLogPanel.tsx` `DOMAIN_BADGE_COLORS` | 11 | `tool` (primary), `agent` (sage), `approval` (amber) | Who acted, and what waits on a human. Coral stays unassigned; no domain means failure |+| `notifications/NotificationCard.tsx` provider badge | 6 | none | The importance badge in the same row already spends coral/amber/sage on high/medium/low; a coral provider would read as a failed notification |++### Brand tints are a separate question++A few plates are a third party's brand colour, not an app hue: Telegram's+`#249CD8`, Discord's `#5865F2`, iMessage's `#34C759` in+`skills/skillIcons.tsx`. Flattening those to `bg-surface-subtle` erases them+into the generic badge beside them, so they are deliberately left as hex.+Giving them a themeable home means **adding brand tokens**, which is a product+decision rather than a cleanup. The same applies to the provider badges in+`NotificationCard.tsx`: reaching back for a stock ramp is not the fix.++### Do not repaint a primitive's variant++`<Button variant="primary" className="bg-violet-500">` is the same bug wearing a+different hat: the variant already paints the accent ramp, and the override+both freezes the colour and desynchronises hover, focus and disabled states.+Retint the surface around it instead, and drop the override.++## The migration codemod++`scripts/theme-codemod/` collapses audited `light dark:` Tailwind pairings into+the semantic utilities. It is idempotent and dry-run by default:++```bash+node scripts/theme-codemod/migrate.mjs # dry-run + report+node scripts/theme-codemod/migrate.mjs --write # apply+node scripts/theme-codemod/migrate.mjs --selftest # fixture assertions+```++It only rewrites adjacent pairs and never touches opacity-suffixed utilities or+test files. Mapping table: `scripts/theme-codemod/map.mjs`.diff --git a/docs/gitbooks/docs/gitbooks/en/developing/tinyhumans-api-key.md b/docs/gitbooks/docs/gitbooks/en/developing/tinyhumans-api-key.mdnew file mode 100644index 0000000000..c796c74c12--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/developing/tinyhumans-api-key.md@@ -0,0 +1,77 @@+---+description: >-+ What a single TinyHumans API key unlocks, how it is resolved, and which+ seams read it.+icon: key+---++# One TinyHumans API key++One TinyHumans credential unlocks every managed backend surface: chat+inference over the OpenRouter model catalogue, web search, embeddings, media+generation, integrations, voice, and the Jev ranker. There's no separate key+per service. The desktop app gets this credential through sign-in; a library+host or a headless process supplies it directly.++## How to get one++Managed inference, search, and the rest of the backend surface all sit behind+one TinyHumans account. Sign in through the desktop app to get a session+credential, or generate an API key (`th_...`) for library and headless use.++## Using it++**Desktop app**: sign in with a TinyHumans account. The app stores a session+credential in the OS-backed auth-profile store and the core resolves it the+same way it resolves an API key, through `security::credentials::api_key` and+`session_support::resolve_backend_credential`.++**Library**: pass the key to `RuntimeBuilder` and it boots connected:++```rust+use openhuman_tinyhumans::{embed::Workspace, RuntimeBuilder};++let runtime = RuntimeBuilder::new()+ .workspace(Workspace::Ephemeral)+ .api_key("th_...")+ .build()+ .await?;+```++`openhuman_tinyhumans::RuntimeBuilder` mirrors `openhuman_embed::RuntimeBuilder`+method for method, then installs the SDK-backed transport and binds it to the+runtime on `build()`.++**Headless**: set `OPENHUMAN_BACKEND_API_KEY` before the core boots. The boot+sequence (`crates/openhuman-core/src/security/credentials/ops/boot_env.rs`)+installs it on a fresh credential store and never overwrites one that's+already there.++## Where it's stored and how it's sent++The key lives in the same auth-profile store as an app session, under its own+provider id (`api-key`), never in `config.toml` and never logged. It's the+only credential a library embedder holds: no login-token exchange, no session+JWT, no `/auth/me` round trip.++Two wire forms, chosen by endpoint:++- **Managed inference** (`{api_url}/openai/v1`): `Authorization: Bearer+ <key>`. `OpenHumanBackendModel::resolve_bearer` prefers the stored API key+ over an app session when both exist.+- **Backend REST** (`BackendClient`, `IntegrationClient`):+ `x-api-key: <key>`.++`crates/openhuman-core/src/security/credentials/api_key.rs` owns storage and+retrieval (`store_api_key`, `get_api_key`, `has_api_key`, `clear_api_key`);+`session_support::BackendCredential` is what resolves either credential form+into the right header at request time.++## BYOK stays available++The API key covers the managed path. Every workload can still be pointed at+your own provider instead, chat and reasoning at a BYOK LLM slug, embeddings+at Voyage or OpenAI or Cohere directly, search at Brave or Exa or Tavily+directly. See [Pluggable engines](engines.md) for the full list and the+config key for each. Running everything BYOK does not require a TinyHumans+key at all; running anything through the managed backend does.diff --git a/docs/gitbooks/docs/gitbooks/en/features/approval-gate.md b/docs/gitbooks/docs/gitbooks/en/features/approval-gate.mdnew file mode 100644index 0000000000..19df12a76f--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/approval-gate.md@@ -0,0 +1,177 @@+---+description: >-+ Human-in-the-loop consent for side-effecting tool calls. When the autonomy+ policy is on, the agent parks any risky action until you approve it, and fails+ closed if you don't.+icon: shield-check+---++# Approval Gate++The Approval Gate is the checkpoint between the agent and the outside world. It parks the calls your autonomy tier classifies **Prompt**, rather than every tool with a real-world effect: `SecurityPolicy::gate_decision` (`crates/openhuman-core/src/security/policy/command_checks.rs`) maps each call's command class against your tier, and only a `Prompt` becomes a gate round-trip. When one does, the gate intercepts the call before the tool runs, shows you what is about to happen, and waits for your decision. A class your tier already allows runs silently: on `full` a `Write` is never prompted, as the tier table below shows.++{% hint style="warning" %}+**The autonomy policy is off by default, and the gate is part of it.** `[autonomy] enabled` defaults to `false` (`crates/openhuman-core/src/config/schema/autonomy.rs`). Until you turn it on, command classification, the tier table, the allowlist, the hourly action budget, `workspace_only` and `forbidden_paths` are all inert, and an acting tool call runs without a prompt, apart from the forced approvals below.++That is deliberate rather than an oversight: these agents are expected to run inside a container, a platform jail or a Docker sandbox that already provides the isolation this in-process policy was approximating, and a shell that refuses ordinary shell syntax is not a usable shell. Set `[autonomy] enabled = true` in `config.toml` to turn on the autonomy policy described here. The floor in the next section, and the forced approvals below, hold either way.+{% endhint %}++## What still holds with the policy off++Three things do not depend on `[autonomy] enabled`:++* **Credential stores and system roots stay unreachable.** `SecurityPolicy::is_always_forbidden` refuses `~/.ssh`, `~/.gnupg`, `~/.aws` and system roots, along with `..` traversal and null bytes in a path, on every code path. It is a floor, not a tier.+* **Hard tool-level blocks are independent.** The checks inside the tool implementations themselves, including the tool-policy middleware, run regardless.+* **Sandboxing is a separate mechanism.** The platform jail and the Docker backend are chosen by `[runtime]` and the session's origin, not by the autonomy tier. See [sandboxing](privacy-and-security/).++Everything below describes the policy with `[autonomy] enabled = true`.++***++## What triggers a prompt++Every acting tool call is classified into a **command class**, and your **autonomy tier** decides whether that class runs silently, prompts, or is blocked.++| Command class | What it covers |+| ------------- | ----------------------------------------------------------------- |+| Read | Provably read-only or observational (curated allowlist) |+| Write | State-changing; the fail-closed default for anything unrecognized |+| Network | Reaches the network (curl, wget, ssh, scp, …) |+| Install | Installs an OS or global language package |+| Destructive | Catastrophic, irreversible or privilege-escalating |++The tier comes from **Settings → Permissions** (`[autonomy].level`, `AutonomyLevel` in `crates/openhuman-core/src/security/policy/types.rs`):++| Tier | Read | Write | Network / Install / Destructive |+| ---------------------------------------------- | ----- | ------ | ------------------------------- |+| `readonly` | Allow | Block | Block |+| `supervised` _(default when the policy is on)_ | Allow | Prompt | Prompt |+| `full` | Allow | Allow | Prompt |++Anything that lands on **Prompt** is parked at the gate. `Block` is refused outright: no in-tier approval can authorize it. Classification is fail-closed. A command that is not provably read-only is treated as at least `Write`, and across a piped command the highest class wins, so `ls | curl …` is `Network`.++A quoted heredoc body (`<< 'EOF' … EOF`) is data, not shell: it is blanked before any structural scan. An unquoted delimiter (`<< EOF`) is still expanded and still scanned.++***++## The flow++```+agent wants to act+ │+ ▼+ classify command ──► Block ──► refused+ │+ Prompt+ │+ ▼+ on "Always allow" list? ──► yes ──► run immediately+ │ no+ ▼+ park call · persist pending row · emit approval_request+ │+ ▼+ ┌──────────────┬───────────────┬────────────┐+ ▼ ▼ ▼ ▼+Approve Always allow Deny 10-min TTL+(once) (+ allowlist) │+ │ │ │ ▼+ ▼ ▼ ▼ Deny+ run run refused (fail closed)+```++When a call is parked, an **Approval Request card** appears above the chat composer. It shows the tool name, a safe one-line summary of the action, and the redacted command. Three choices:++* **Approve**: run this one call.+* **Always allow**: run it, and add the tool to your `auto_approve` list so it skips the prompt next time.+* **Deny**: refuse this call.++You can also type **yes** or **no** in chat. The reply is routed back to the parked request.++***++## Always allow++Approving with **Always allow** persists the tool name onto `[autonomy].auto_approve` (config save plus a live policy reload), so the gate short-circuits to allow for that tool on later turns. Remove an entry in **Settings → Agent access** to start being prompted again.++The shipped default list is `file_read`, `memory_search`, `memory_list`, `get_time`, `list_dir`, `glob`, `grep`. Four of those names no longer match a registered tool: the memory surface is one tool called `memory`, the clock is `current_time`, and the directory listing is `list`. Those four entries are therefore inert, and `file_read`, `glob` and `grep` are the three that do anything. Checked against `app/src/features/conversations/tools/__fixtures__/coreToolNames.json`. That fixture is the catalogue the core's drift test compares against, though it is not exhaustive: a few credential-gated and env-gated tools are registered without appearing in it.++***++## `auto_approve_all`++Separately from the per-tool list, `[autonomy].auto_approve_all` approves **every** call without prompting. Three things are worth knowing before enabling it:++* An unlabelled call site is still hard-denied, and the hard security blocks inside the tool implementations are unaffected.+* It bypasses **parking**, not just the prompt. A remote-origin triage dispatch (a connector or webhook payload reaching `triage.escalate`) normally parks and writes an audit row; with this flag on it is allowed immediately and **no audit row is written**, so those dispatches leave no approval trail.+* It does not reach a **forced** approval, below.++***++## Forced approvals++Browser page interactions are the one surface that cannot be pre-authorized. Every `click`, `double_click`, `fill`, `type`, `press`, `select` and `check` is routed through `ApprovalGate::intercept_forced` (`crates/openhuman-core/src/security/approval/gate_setup.rs`) rather than the ordinary entry point, which changes three things:++* **Every shortcut is skipped.** `auto_approve_all`, the `auto_approve` allowlist and the per-flow tool trust are all ignored, and the forced park does not consult the autonomy tier, so the call parks even with `[autonomy] enabled = false`.+* **The decision is one-time.** **Always allow** is refused on a forced request: only approve-once or deny can resolve it.+* **It needs a live chat.** A turn whose origin is not a web-chat turn carrying both a thread id and a client id is denied instead of parked, so a cron, channel or flow turn cannot drive the browser.++The card names the action kind, the page origin and a SHA-256 digest binding that action to that URL. If the page navigates while you are deciding, the approved action is refused rather than replayed against the new page.++***++## Fail-closed behavior++Every non-approve path resolves to **Deny**:++* **Timeout**: a parked request lives for 10 minutes; if undecided it transitions to a terminal `deny`.+* **Persist failure** or a dropped channel: denied.+* The timeout path re-reads the stored decision first, so an approval that committed in the race still wins.++Pending requests are stored in SQLite (`{workspace_dir}/approval/approval.db`) and **survive a core restart**. After an approved tool finishes, the gate records a write-once execution outcome (success or error, with the error text sanitized and capped) as a durable audit trail. Everything persisted or broadcast is redacted first: PII and chat content are scrubbed and home paths stripped.++***++## What the turn's origin decides++The gate is **interactive-only**: a parked call needs a surface that can answer it. Which turns it parks, and which pass straight through, is decided by the turn's origin, in `crates/openhuman-core/src/security/approval/gate_intercept.rs`, not by the tool:++| Turn origin | At the gate |+| ------------------------------------------------------------------------------------------------ | ------------------------------------------ |+| Cron and internal background jobs (`TrustedAutomation` → `Cron` / `Background`) | Allowed, no row, no event |+| A saved flow's pre-declared action (`Workflow { require_approval: false }`) | Allowed, no row, no event |+| CLI, a delegated sub-agent, and a **locally initiated** triage dispatch, which is labelled `Cli` | Allowed, no row, no event |+| Web chat | Parks for your decision |+| A **remote-origin** triage dispatch: a connector or webhook payload reaching `triage.escalate` | Parks and writes a `pending_approvals` row |+| An external channel turn (Telegram, Slack, …) | Parks and writes a row |+| An unlabelled call site (`Unknown`) | Denied outright |++Triage is therefore two cases rather than one. A dispatch your own machine started keeps the authority its caller already had and is allowed silently. A dispatch steered by a payload from outside carries `TrustedAutomation { Workflow { require_approval: true } }`, so it parks and leaves an audit row even though no surface can decide a background park yet and it expires at the TTL. That buys the audit trail, not a working escalation, and `auto_approve_all` gives even that up. The two triage cases are pinned apart in `gate_triage_tests.rs`.++An external channel turn parks for the same reason: remote input is untrusted, so the row is written and a decision can still arrive on the thread card before the TTL.++***++## Configuration and RPC++* **`[autonomy].enabled`**: the master switch for the policy. `false` by default; the command classes, the tier table, the allowlist and the hourly budget all need it `true`. Forced approvals and the always-forbidden floor do not.+* **`OPENHUMAN_APPROVAL_GATE`**: set to `0` or `false` to skip installing the gate even with the policy on. With no gate, `Prompt`-class calls run unprompted.+* **`[autonomy].level`** and **`[autonomy].auto_approve`**: tier and allowlist, via the `config.update_autonomy_settings` RPC or the settings panels.++The `approval` controller exposes three JSON-RPC methods:++| Method | Purpose |+| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |+| `openhuman.approval_list_pending` | The live queue of parked requests. |+| `openhuman.approval_list_recent_decisions` | Decided and executed audit rows (`limit` 1 to 500, default 50). Surfaced in **Settings → Approval history**. |+| `openhuman.approval_decide` | Apply a decision (`approve_once` / `approve_always_for_tool` / `deny`). |++`list_pending` and `list_recent_decisions` return empty rather than an error when no gate is installed; `decide` errors when the gate is absent or the request is unknown or already decided.++***++## See also++* [Privacy & Security](privacy-and-security/): what leaves the machine, and the layers underneath this one.+* [Security architecture](../developing/architecture/security.md): command classification and policy internals.+* [Agent access settings](settings.md): where the tier, the trusted roots and the allowlist are edited.diff --git a/docs/gitbooks/docs/gitbooks/en/features/billing-and-usage.md b/docs/gitbooks/docs/gitbooks/en/features/billing-and-usage.mdnew file mode 100644index 0000000000..de04fcdbdc--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/billing-and-usage.md@@ -0,0 +1,110 @@+---+description: >-+ Plans, credits and saved cards over Stripe and Coinbase, plus a local+ dashboard for token usage and cost estimates.+icon: credit-card+---++# Billing, Cost & Usage++OpenHuman keeps two related but separate ledgers. **Billing** is what you pay the hosted backend: plans, credit top-ups, saved cards and coupons, all settled through Stripe or Coinbase. **Cost & Usage** is what the agent spends on your behalf, tracked locally per provider call so you can inspect estimated token costs.++The first lives in the cloud; the second never leaves your workspace.++***++## Part 1: Billing & Payments++The `billing` domain is a thin RPC adapter. It holds **no payment logic or state of its own**. Every operation forwards an authenticated HTTPS call to the hosted backend (`/payments/*`, `/coupons/*`) using your stored app-session JWT, and surfaces the JSON response verbatim. Authorization, plan ownership and payment policy are all enforced backend-side. A missing or invalid session yields the backend's `401`/`403` directly; JWTs and card data are never logged.++Pre-HTTP, the adapter does light input validation only: non-empty plan/coupon/payment-method ids, a finite positive `amountUsd`, and a gateway whitelist of `stripe` / `coinbase`.++### Plans++Three tiers are offered, each with a monthly and annual interval:++| Tier | Monthly | Annual | Per-call discount vs pay-as-you-go |+| --------- | ------- | --------- | ---------------------------------- |+| **Free** | $0 | $0 | None (pay-as-you-go baseline) |+| **Basic** | $19.99 | $199 | 50% cheaper per call |+| **Pro** | $199.99 | $1,799.99 | 90% cheaper per call |++Higher tiers do not unlock features so much as lower the **per-call margin** over the pay-as-you-go baseline. All tiers have "access to everything"; you are buying cheaper inference, not gated capabilities.++### Payment providers++Two gateways are wired, and only two:++* **Stripe**: plan purchases (Checkout sessions), the customer billing portal, credit top-ups, saved-card management (SetupIntents) and auto-recharge.+* **Coinbase Commerce**: crypto charges, used for credit top-ups and annual billing.++`top_up_credits` and `create_coinbase_charge` default to the `stripe` gateway and `annual` interval; an empty or whitespace gateway normalises to Stripe.++### Credits, top-ups & auto-recharge++Beyond a subscription you hold a **USD credit balance**. You can read the balance, page through transaction history, and top up via either gateway. **Auto-recharge** (Stripe only) re-fills credits from a saved card when the balance runs low; you can read and update its settings, and list / add / update / delete saved cards. Adding a card creates a Stripe SetupIntent; deleting one is treated as a dangerous operation.++### Coupons++Coupon codes are redeemed against the backend (`POST /coupons/redeem`), and you can list the coupons currently redeemed on your account (`GET /coupons/me`).++### Where billing lives in the app++The **Billing** button on the desktop Accounts page opens the hosted web billing dashboard, where you can manage plans, top-ups, coupons, cards, and invoices. The former desktop Billing summary page has been removed. Other clients can reach the same hosted billing operations through the authenticated RPC controllers described below; they are not exposed as agent tools.++### RPC surface++Namespace `billing`, exposed as `openhuman.billing_*`. The registered set is `all_billing_registered_controllers` in `crates/openhuman-tinyhumans/src/hosted/billing/schemas.rs`:++| Area | Methods |+| ---------------- | ----------------------------------------------------------------------------------------------------------- |+| Plan and summary | `billing_get_summary`, `billing_get_current_plan`, `billing_purchase_plan`, `billing_create_portal_session` |+| Credits | `billing_get_balance`, `billing_top_up`, `billing_create_coinbase_charge`, `billing_get_transactions` |+| Auto-recharge | `billing_get_auto_recharge`, `billing_update_auto_recharge` |+| Saved cards | `billing_get_cards`, `billing_create_setup_intent`, `billing_update_card`, `billing_delete_card` |+| Coupons | `billing_redeem_coupon`, `billing_get_coupons` |++***++## Part 2: Cost & Usage Dashboard++The `cost` domain is entirely local. It records every provider call's token usage and computed USD cost to an append-only JSONL file (`<workspace>/state/costs.jsonl`), keeps in-memory daily/monthly aggregates and serves a 7-day dashboard over JSON-RPC. A process-global singleton tracker is shared by the agent turn loop (which logs telemetry after each provider call) and the dashboard handlers, so each call is persisted exactly once.++### Real-time token & cost tracking++For each call, per-call cost is computed from token counts and per-million-token prices (clamping non-finite or negative prices to `0.0`). When the provider echoes an authoritative `charged_amount_usd` that value wins; otherwise OpenHuman falls back to a static pricing catalog of known models. Usage is bucketed in UTC, keyed by model, with the **provider** derived from the `provider/model` prefix. All-zero usage payloads are skipped so providers that don't report usage don't inflate the request count.++### Local tracking and usage view++The local `[cost] monthly_limit_usd` setting is a legacy display target, not an enforced cap. The core no longer refuses requests when estimated cost passes it. Hosted credit exhaustion is enforced by the backend and is separate from the local usage ledger. The Usage view therefore does not show a budget gauge, limit status, or daily threshold colors.++Settings → **Usage** shows the last seven UTC calendar days of recorded cost and token activity, a monthly pace projection, and a per-model breakdown. Costs can be estimates when the provider did not return a charged amount. The dashboard refreshes about every 10 seconds.++The **Usage log** tab shows local provider-call records in a selected rolling period. It fetches at most 1,000 newest rows and supports category, provider, cost-source, and model/session filters over those loaded rows. The displayed row count and cost are for the filtered loaded set, not a complete billing total.++### RPC surface++Namespace `cost`, exposed as `openhuman.cost_*`:++| Method | Inputs | Output |+| ------------------------ | ------------------------------------- | ----------------------------------------------------------------------------- |+| `cost_get_dashboard` | none | 7-day buckets, summary metrics, legacy budget fields, per-model breakdown |+| `cost_get_daily_history` | `days?` (default 7, clamped 1 to 366) | Ordered daily entries, oldest first, gaps zero-filled |+| `cost_get_summary` | none | Live session / daily / monthly cost summary |+| `cost_get_usage_log` | `days?`, `limit?` | Newest local provider-call records and category totals, bounded to 1,000 rows |++These are also exposed as read-only, default-ON agent tools so the agent can inspect its own spend.++***++## Cost & token compression++Because cost tracks **real token counts**, anything that shrinks the prompt directly lowers spend. OpenHuman's [TokenJuice token compression](token-compression.md) reduces the tokens sent on each call, and [model routing](model-routing/) sends work to the cheapest model that can handle it. Both can show up as lower recorded costs in the dashboard.++***++## See also++* [Smart Token Compression](token-compression.md): fewer tokens on each call, so a lower recorded cost.+* [Automatic Model Routing](model-routing/): sends work to the cheapest model that can handle it.+* [Privacy & Security](privacy-and-security/): what is logged, and what never is.diff --git a/docs/gitbooks/docs/gitbooks/en/features/channels.md b/docs/gitbooks/docs/gitbooks/en/features/channels.mdnew file mode 100644index 0000000000..cc7919b941--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/channels.md@@ -0,0 +1,93 @@+---+description: >-+ Messaging platforms OpenHuman talks back to you on: inbound dispatch into the+ agent loop, outbound replies and proactive delivery, and per-channel+ credentials.+---++# Messaging Channels++A **channel** is a messaging platform OpenHuman uses to _talk back_ to you. This is the mirror image of an [integration](integrations/): an integration is mostly a source the agent _reads from_ (your inbox, your calendar, your CRM), while a channel is a two-way conversation surface. You message the agent on a platform you already use, and the agent replies there.++Under the hood every channel implements one small Rust contract (a `send` path for outbound messages and a `listen` path for inbound ones), so the same agent loop serves Telegram, Discord, the built-in web chat, and a dozen others without per-platform branching in the core.++***++## What a channel does++Each channel does two things:++* **Inbound**: when a message arrives, the channel normalizes it into a `ChannelMessage` (sender, reply target, content, optional thread id) and hands it to the dispatch loop. Dispatch spawns or resumes an agent run, scopes its tools, and the agent works the request. Some platforms support a `/models` and `/model` command to switch the model for that sender's session; Telegram additionally supports remote-control commands.+* **Outbound**: the agent's response is sent back through the same channel to your `reply_target`, threaded when the platform supports it. Channels can also deliver **proactively** (no incoming message to reply to) when fired by a [trigger](integrations/triggers.md) or a cron job. A channel only receives proactive sends if it advertises a default delivery target; channels without one are skipped rather than posted to an empty recipient.++Channels that support it can show a typing indicator, stream progressive **draft updates**, post **threaded replies**, and add **emoji reactions**. Capabilities are declared per channel, not assumed.++***++## Supported channels++OpenHuman ships **15 channel provider modules**, of which **14 compile into the shipped desktop build**: WhatsApp Web sits behind the `whatsapp-web` Cargo feature, which is in neither the contributor default set nor the shipped product set, so it is an opt-in build rather than something you can switch on. Alongside them, the in-app **Web** chat is built into the app rather than being a provider module, and a separate `cli` channel serves the `openhuman-core` terminal binary. **Eight** channels have a setup flow in the app (Telegram, Discord, Web, iMessage, Lark/Feishu, DingTalk, Email, 元宝); the rest are enabled by hand in `config.toml`.++Matrix is the one to know about: a `[channels.matrix]` stanza is still accepted by the config parser, but the provider was removed from the build. It is logged and skipped, so a Matrix config does nothing.++| Channel | Direction | Inbound transport | Credential mode | In Settings UI |+| ----------------- | ------------- | ---------------------------- | ------------------------------------------------------------------ | -------------- |+| **Telegram** | Two-way | Bot API long-poll | Connect via OpenHuman (managed DM) **or** your own BotFather token | Yes |+| **Discord** | Two-way | Gateway | Your own bot token, OAuth install, **or** managed account link | Yes |+| **Web** | Two-way | In-app | Built-in, no setup (local) | Yes |+| **iMessage** | Two-way | macOS Messages (AppleScript) | Local-only, no credentials (needs Full Disk Access) | Yes |+| **Lark / Feishu** | Two-way | WebSocket or webhook | Your own app id + secret | Yes |+| **DingTalk** | Two-way | Stream Mode WebSocket | Your own client id + secret | Yes |+| **元宝 (Yuanbao)** | Two-way | WebSocket | Your own AppID + AppSecret | Yes |+| **Slack** | Two-way | Events/socket | Your own bot token | `config.toml` |+| **WhatsApp** | Two-way | Meta Cloud webhook | Your own access token | `config.toml` |+| **IRC** | Two-way | Persistent socket | Your own server/nick | `config.toml` |+| **Signal** | Two-way | signal-cli REST events | Your own linked signal-cli account | `config.toml` |+| **Mattermost** | Two-way | WebSocket | Your own bot token | `config.toml` |+| **QQ** | Two-way | WebSocket | Your own bot credentials | `config.toml` |+| **Linq** | Two-way (SMS) | Webhook | Your own API token | `config.toml` |+| **Email** | Two-way | IMAP IDLE + SMTP | Your own mailbox credentials | `config.toml` |++WhatsApp also has an experimental peer-to-peer variant behind the `whatsapp-web` feature flag. Channels marked "webhook" keep a live connection alive but receive inbound messages by HTTP push, so they need a reachable HTTPS endpoint configured on the provider's side.++Telegram is the most fully featured channel. It supports typing indicators and live draft updates, and is currently the only channel wired to a per-channel approval surface, so `Prompt`-class tool calls can be answered inline rather than parked. Discord adds native threaded replies; Lark also threads. Web supports rich text and stays entirely local.++**Email deserves a special mention**: it is a fully **native, self-hosted connector**, with no third-party broker in the loop. Inbound mail arrives over IMAP with **IMAP IDLE** push (new mail reaches the agent in seconds, with the connection refreshed every \~29 minutes per the RFC), and replies go out over SMTP with full attachment/multipart support, from your own address on any provider you configure. An `allowed_senders` allowlist is the inbound security gate. Set it explicitly to the addresses you trust. (In `config.toml` an empty list means deny-all, but the Connections UI defaults a blank field to `["*"]`, which allows **any** sender. So don't leave it blank if strangers shouldn't be able to prompt your agent by email.)++***++## Credential modes++Channels authenticate one of a few ways:++* **Connect via OpenHuman (managed)**: a one-click, encrypted connection brokered through the OpenHuman backend. Today this covers Telegram (message the managed bot directly) and Discord (link your account or install via OAuth). No tokens live on your machine.+* **Your own credentials**: you supply a bot token, API key/secret, or app credentials. Telegram (BotFather token), Discord (bot token), Slack, WhatsApp, Lark/Feishu, DingTalk, Yuanbao, Signal, Mattermost, QQ, Linq, IRC, and Email all support this. Maximum control; you own the platform account, rate limits, and any webhook endpoint.+* **Local, no credentials**: the **Web** chat and **iMessage** need no tokens at all. Web runs inside the desktop app; iMessage drives the local macOS Messages app over an AppleScript bridge (grant Full Disk Access). Both keep messages on your machine.++Secrets supplied for any mode are stored through OpenHuman's credential layer and protected at rest by the [encryption layer](privacy-and-security/). They are never written to `config.toml` in plaintext for the UI-managed channels.++***++## Where to connect a channel++Channels are set up under **Connections → Channels** in the left sidebar, **not** under Settings, and not under any "Automation & Channels" menu (no such menu exists). Open that tab, pick a platform tile, and follow its setup card:++* **Discord**: choose _Connect via OpenHuman_ (link your account or install the bot via OAuth), or paste your own Discord bot token.+* **Telegram**: message the managed OpenHuman bot to link, or paste a BotFather bot token.++Slack is connected as an **app** under **Connections → OAuth** (Composio) so the agent can read and act in Slack; it is not set up as a talk-back channel in the Channels tab.++***++## Choosing the default channel++Open **Connections → Channels** to pick which channel is the **active route**: the one OpenHuman uses for proactive, recipient-less delivery (cron, triggers). The default is the in-app **Web** chat until you change it. Setting a new default takes effect immediately, without restarting the channel runtime, and the panel shows which channel is currently active. Inbound messages always get answered on whatever channel they arrived on, regardless of the default route.++***++## See also++* [Integrations](integrations/): the read-side catalog the agent pulls context from.+* [Triggers](integrations/triggers.md): live events that fire proactive channel delivery.+* [Privacy & Security](privacy-and-security/): where credentials live and the backend boundary.+* [OS Keyring & Secret Storage](privacy-and-security/os-keyring-and-secret-storage.md): at-rest protection for channel secrets.diff --git a/docs/gitbooks/docs/gitbooks/en/features/chat.md b/docs/gitbooks/docs/gitbooks/en/features/chat.mdnew file mode 100644index 0000000000..ab3e14aec1--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/chat.md@@ -0,0 +1,97 @@+---+description: >-+ The chat surface: composer, slash commands, mentions, model and effort+ pickers, the context ring, the tool timeline, approvals, sub-agent cards,+ artifacts and threads.+icon: comments+---++# Chat++Chat is where almost everything happens. It is not a text box with a send button: a turn here can call tools, spawn sub-agents, stop to ask you something, park an action for approval, produce files, and bill itself, and the transcript shows all of it in order.++Open it at **Chat** in the sidebar, or `⌘N` for a new conversation.++## The composer++The input is a rich text field rather than a plain one, which is what lets a `/` become a command chip and a popover anchor to the caret as you type. Alongside it:++* **Attach** files. An image, a PDF, an Office document or an archive is preserved in the working folder and offered to the model natively when the model and the route both support that type; otherwise it degrades to extracted text, a bounded readout, or an archive listing with accessible paths.+* **Model**, and a separate **thinking effort**. Both apply to this conversation, not globally.+* **Context ring**, which shows how full the context window is for this thread and opens a breakdown with per-sub-agent cost.+* **Voice**: tap to speak, or hand the turn to the live voice agent. See [Voice](native-tools/voice.md).+* When the box is empty, the mascot button takes you to the full-screen [mascot](mascot.md) stage.++### Slash commands++Typing `/` offers three sources at once: the built-ins (`/new`, `/clear`, `/stop`, `/plan`, `/build`), the core's own command list, and your installed skills and workflows.++### Mentions++Typing `@` offers two sources: **memory**, searched as you type, and **files**, meaning the artifacts this thread has already produced. A mention becomes a chip, so the agent gets the reference rather than a guess at what you meant.++## Reading a turn++Each assistant turn groups its reasoning and its tool calls into one chronological block, so you can see what it thought and what it did in the order it happened rather than in two separate panes.++* **Tool calls** render per tool: a search shows its queries and sources, a shell call shows its command and exit, a failed call shows a failure card with the reason rather than a stack trace. Every tool runs in the core; nothing executes in the browser.+* **Sources** appear as badges under an answer, up to four inline and then a count.+* **Timing and cost** are on the turn, and the context ring's breakdown attributes spend to the sub-agents that caused it.+* **Find in conversation** (`⌘F`) searches this thread only, and the right-edge rail jumps between turns.++The action bar on an assistant turn has copy, regenerate, a thumbs up or down that is remembered, read-aloud, and export as Markdown. On your own turns you can edit and resend, which branches the conversation: the branch picker moves between versions.++## When the agent needs you++Four different kinds of stop, all inline:++| Stop | What it looks like |+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Approval** | A card naming the tool and a redacted one-line summary of the action. Approve once, always allow that tool, or deny. See [Approval Gate](approval-gate.md). |+| **Permission** | A connector or provider needs authorizing; the card collects exactly the fields that provider needs. |+| **Clarification** | The agent asks a direct question and waits. |+| **Plan review** | A proposed plan with approve, reject, or revise-with-feedback. |++A background or scheduled turn has nobody to ask, so an approval raised outside a live chat collects in a deck you can decide later. Undecided requests deny themselves after ten minutes.++## Sub-agents++When a turn delegates, each child appears as its own card: a nested transcript, its own status, a reply box when it is waiting on you, and a cancel button. Delegation is asynchronous, so the parent keeps working and the card fills in as the child reports. Detached background agents, scheduled runs and memory syncs collect in a separate inbox card rather than interrupting the thread.++## Files the agent makes++Anything the agent produces that is meant for you, a document, a deck, an image, a render, becomes an artifact: a chip above the composer opens a panel with download, reveal in folder, and delete. Only finished artifacts persist across a restart; a failed one offers a retry.++## Workflow proposals++Ask for an automation and the agent proposes a graph. The proposal is validate-only: it arrives as a card with the node list and three choices, save and enable, dismiss, or open it on the canvas. That card is the only path from a proposal to a saved automation, which is deliberate. See [Workflows](workflows.md).++## Threads++The sidebar lists your conversations. You can create, select, rename inline, and delete behind a confirmation. Turns on different threads run **concurrently**, so starting something slow in one conversation does not block another.++Threads carry a goal and a to-do list when the agent sets them, shown as a pinned list and a banner with its token budget. Both are read-only in the UI today: the agent maintains them, you do not edit them there.++A long conversation is compacted rather than truncated. The compaction seals what came before and opens a new generation that records the sealed one as its parent, so nothing is deleted on disk even though the model only reads the head. There is no UI for browsing those generations yet.++## Keyboard++| Shortcut | Action |+| ----------- | ------------------------- |+| `⌘K` / `⌘P` | Command palette |+| `⌘N` | New conversation |+| `⌘F` | Find in this conversation |+| `⌘B` | Toggle the sidebar |+| `⌘,` | Settings |+| `⌘/` or `?` | Shortcut sheet |++## Not here yet++Stated so you don't go looking: there is no thread search, pinning, folders or archiving in the sidebar; no UI for setting a thread goal or ticking a to-do; no browser for compaction generations; and follow-up suggestion chips are built but have no producer, so the row stays empty.++## See also++* [Memory](memory.md): what the agent recalls before it answers, and what it writes after.+* [The Orchestrator](orchestration.md): how delegation is planned.+* [Available Tools](native-tools/): what those tool cards are calling.+* [Notifications & Activity](notifications-and-activity.md): what happens when a turn finishes while you are elsewhere.diff --git a/docs/gitbooks/docs/gitbooks/en/features/cloud-deploy.md b/docs/gitbooks/docs/gitbooks/en/features/cloud-deploy.mdnew file mode 100644index 0000000000..17b0fd3034--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/cloud-deploy.md@@ -0,0 +1,690 @@+---+description: >-+ Hosting the headless openhuman-core on a server: DigitalOcean App Platform,+ Fly.io, Docker Compose on any VPS, or an Oracle Cloud Terraform stack, plus+ the bearer token, workspace volume, and secret-s+icon: cloud+---++# Cloud Deploy++**Who this page is for:** an operator running the core as a server process. A desktop user never needs any of it; the shell already runs a core in-process.++OpenHuman is a desktop app, but its **Rust core** (`openhuman-core`) is a headless JSON-RPC server that can be hosted in the cloud. Deploying the core separately is useful for:++* Multi-device access, point several desktop clients at the same hosted core+* Internal testers without local Rust toolchains+* Long-running cron jobs / webhooks that should outlive a laptop session++This guide covers five deploy paths, easiest first:++1. [DigitalOcean App Platform: one-click](cloud-deploy.md#1-digitalocean-app-platform-one-click)+2. [DigitalOcean App Platform: manual via doctl](cloud-deploy.md#2-digitalocean-app-platform-manual-via-doctl)+3. [Any VPS via Docker Compose](cloud-deploy.md#3-any-vps-via-docker-compose)+4. [Fly.io](cloud-deploy.md#4-flyio)+5. [Oracle Cloud Infrastructure: Terraform on Always Free](cloud-deploy.md#5-oracle-cloud-infrastructure-terraform-on-always-free)++What gets deployed in every path: a single container running `openhuman-core serve` on port `7788`. Public hosts should sit behind the provider's TLS, for example `https://core.example.com/rpc`. Private-only hosts on localhost, RFC1918 networks, or tailnets such as Tailscale can use plain HTTP, for example `http://100.x.x.x:7788/rpc`, when the core is not reachable from the public internet. The desktop app already knows how to talk to a remote core: it has a first-class **Settings → Core connection** panel that persists the RPC URL and bearer token, so nothing has to be put in an environment file.++***++## Remote UI choices++OpenHuman's supported remote deployment is **core remote, UI local**: run `openhuman-core` on a Linux server and point a desktop client at that RPC URL. The deployed core does not serve the full React/Tauri UI as a production web app yet. Desktop-only features still need the Tauri shell, including tray controls, native deep links, the native iMessage scanner, OS keychain integration, and window/screen affordances.++For a browser-accessible UI on a private server today, use the Vite web build as a development/preview surface against the remote core:++```bash+# On the server, run the core with an explicit token.+export OPENHUMAN_CORE_HOST=0.0.0.0+export OPENHUMAN_CORE_PORT=7788+export OPENHUMAN_CORE_TOKEN="$(openssl rand -hex 32)"+openhuman-core serve++# In another shell on the server, serve the UI only on loopback.+pnpm --dir app dev -- --host 127.0.0.1 --port 1420+```++Then tunnel both ports from your workstation:++```bash+ssh -L 1420:127.0.0.1:1420 -L 7788:127.0.0.1:7788 user@server+```++Open `http://127.0.0.1:1420`, choose the remote/core option on the first-run screen, and enter `http://127.0.0.1:7788/rpc` plus the `OPENHUMAN_CORE_TOKEN` value from the server.++If you serve the browser UI from a non-loopback origin, add that exact origin to the core's CORS allowlist:++```bash+export OPENHUMAN_CORE_ALLOWED_ORIGINS="https://openhuman-ui.example.com"+```++Loopback Vite origins such as `http://127.0.0.1:1420` and `http://localhost:1420` are allowed automatically. Public `http://` origins are not recommended because every RPC call carries the bearer token.++***++## Single source of truth for the bearer token++Every `/rpc` call carries `Authorization: Bearer <token>`. The core has two ways to load that token at startup ([`crates/openhuman-core/src/core/auth.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/core/auth.rs)):++1. **`OPENHUMAN_CORE_TOKEN` environment variable**: pre-seeded by the caller (Tauri shell, Docker, App Platform, systemd unit, …). The core uses this value as-is and **never** writes a file.+2. **`{workspace}/core.token` file**: generated by the core on first boot _only when `OPENHUMAN_CORE_TOKEN` is unset_. Standalone `openhuman-core run` uses this so CLI clients can `cat` the file.++**Rule of thumb for any remote / dockerized deploy: always set `OPENHUMAN_CORE_TOKEN`.** Do not rely on `core.token` in a container. Ephemeral filesystems lose it on redeploy, and any client trying to read the file from outside the container will get a stale or empty value. The two paths are deliberately mutually exclusive at startup; mixing them is the most common reason behind "the dashboard gets 401 after I redeployed".++To check what the _running_ core is using, run [`scripts/print-core-token.sh`](https://github.com/tinyhumansai/openhuman/blob/main/scripts/print-core-token.sh) on the host (or inside the container with `docker compose exec`):++```bash+scripts/print-core-token.sh --where # prints 'env' or 'file:/path'+scripts/print-core-token.sh --redact # first 8 hex chars + '…' (safe for logs)+scripts/print-core-token.sh # full value (pipe straight into a client)+```++The desktop app's first-run picker and **Settings → Core connection** both expose a **Test connection** button next to the Core RPC URL and token fields. It fires `core.ping` against the typed URL with the typed token and reports one of three outcomes inline, connected, auth failed or unreachable, before anything is persisted.++***++## What you need before you start++| Setting | Required | Notes |+| ----------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `OPENHUMAN_CORE_TOKEN` | yes | Bearer token clients send to `/rpc`. Generate with `openssl rand -hex 32`. **Anyone with this token can drive the core.** |+| `BACKEND_URL` | yes | Tinyhumans backend the core talks to (`https://api.tinyhumans.ai` for prod). |+| `OPENHUMAN_APP_ENV` | no | `production` or `staging`. Defaults to `production`. |+| `OPENHUMAN_KEYRING_MASTER_KEY` | no | 64 hex characters (`openssl rand -hex 32`). Master key for the staging/production `encrypted_file` keyring, so a container with no OS keychain can store provider keys encrypted. Inject it from your secret manager like the bearer token; **losing it orphans every stored secret.** |+| `OPENHUMAN_KEYRING_MASTER_KEY_FILE` | no | Path to a file holding the same value, for Docker/Kubernetes secret mounts. Set one of the two, not both. Without either, `encrypted_file` needs an OS keychain. |+| `OPENHUMAN_CORE_HOST` | no | Defaults to `0.0.0.0` in the container. |+| `OPENHUMAN_CORE_PORT` | no | Defaults to `7788`. |+| `RUST_LOG` | no | `info` is fine; `debug` for triage. |++Endpoints exposed by the running container, with the route policy from [`crates/openhuman-rpc/src/server/auth.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-rpc/src/server/auth.rs):++| Endpoint | Auth |+| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `GET /health` | None. The liveness probe every deploy path's healthcheck uses. |+| `GET /` | None. Info page naming the other routes. |+| `GET /schema` | None. Read-only schema discovery. |+| `POST /rpc` | The bearer token. This is the executable surface. |+| `GET /events` | Exempt from the header check, because a browser `EventSource` cannot set headers, but the handler enforces its own credential. Not an open stream. |+| `GET /ws/dictation` | The bearer token, as a header or `?token=`, checked before the WebSocket upgrade. |+| `GET /oauth/mcp/callback` | Exempt from the bearer middleware: an external authorization server posts back here with no bearer. The one-time `state`, minted in `oauth_begin`, is the guard. |+| `GET /dev/connect` | Exempt from the middleware, guarded in the handler instead: a debug build or an explicit opt-in, a loopback `app` origin and `Host`, and no cross-site navigation. It should not be reachable on a deployed core. |+| `POST /v1/chat/completions`, `GET /v1/models` | The OpenAI-compatible surface, behind core's `http-server` gate. These accept the core bearer or an external provider key, so they are executable too, not just `/rpc`. |++Treat only `/health`, `/` and `/schema` as genuinely unauthenticated. `/events`, `/oauth/mcp/callback` and `/dev/connect` are exempt from the _header_ check but each carries its own guard; the two executable surfaces are `/rpc` and `/v1/*`.++The `OPENHUMAN_WORKSPACE` directory (`/home/openhuman/.openhuman` inside the container) holds the core's config, sqlite databases, and skill state. **Mount it on a persistent volume** in every production deploy or you will lose data on restart.++***++## 1. DigitalOcean App Platform: one-click++Click the button below to create a new App Platform application from this repository's [`.do/app.yaml`](https://github.com/tinyhumansai/openhuman/blob/main/.do/app.yaml):++[](https://cloud.digitalocean.com/apps/new?repo=https://github.com/tinyhumansai/openhuman/tree/main)++Then, in the App Platform UI, **before the first deploy completes**:++1. Open the **Settings → App-Level Environment Variables** tab.+2. Replace the placeholder `OPENHUMAN_CORE_TOKEN` value with a strong secret (`openssl rand -hex 32`). Mark it encrypted.+3. If you are deploying staging, change `OPENHUMAN_APP_ENV` to `staging` and `BACKEND_URL` to `https://staging-api.tinyhumans.ai`.+4. Hit **Save**. App Platform redeploys with the new secret.++App Platform handles TLS, restart-on-crash, log streaming, and rolling redeploys on `git push` (set `deploy_on_push: true` in `.do/app.yaml` to opt-in).++> **Persistence note:** App Platform Basic does not provide block storage. The core's workspace lives in the container's ephemeral filesystem and is lost on redeploy. For durable storage, attach a managed database or upgrade to a tier that supports volumes. See the [Compose path](cloud-deploy.md#3-any-vps-via-docker-compose) for a self-host alternative with persistent volumes out of the box.++***++## 2. DigitalOcean App Platform: manual via doctl++If you'd rather not click through the UI:++```bash+# One-time: install doctl and authenticate.+doctl auth init++# Edit .do/app.yaml - set OPENHUMAN_CORE_TOKEN to a real value (or pass it in+# at create time via --spec with envsubst). Then:+doctl apps create --spec .do/app.yaml++# Watch the build:+doctl apps list+doctl apps logs <app-id> --type build --follow+```++Update an existing app after editing the spec:++```bash+doctl apps update <app-id> --spec .do/app.yaml+```++***++## 3. Any VPS via Docker Compose++Works on any host with Docker Engine ≥ 24 and the Compose plugin. DigitalOcean Droplet, Hetzner, Linode, EC2, a home server.++Each production release publishes a multi-tagged image to GHCR:++```bash+docker pull ghcr.io/tinyhumansai/openhuman-core:latest # tracks the latest prod cut+docker pull ghcr.io/tinyhumansai/openhuman-core:v<version> # pinned by GitHub Release tag+docker pull ghcr.io/tinyhumansai/openhuman-core:<version> # pinned by SemVer+```++Take `<version>` from the [latest release](https://github.com/tinyhumansai/openhuman/releases/latest). The two pinned tags are immutable and pushed per release; `:latest` is promoted only after the release publishes, so it never points at a cut that was rolled back (`.github/workflows/release-production.yml`).++The image is `linux/amd64`. arm64 hosts pull the standalone tarball attached to the same GitHub Release (`openhuman-core-<version>-aarch64-unknown-linux-gnu.tar.gz`) or build the image from source on an arm64 builder.++If you wrap a release tarball in your own image, match the builder it came from. The release matrix builds `aarch64` on `ubuntu-24.04-arm` and `x86_64` on `ubuntu-22.04` (`.github/workflows/release-production.yml`), so the `aarch64` binary needs glibc 2.39 or newer: `ubuntu:24.04` works, while `debian:bookworm-slim` ships 2.36 and fails at exec with `GLIBC_2.39' not found`. For `x86_64`, Ubuntu 22.04 or Debian 12 and newer.++Quick run with a published image:++```bash+docker run -d --name openhuman-core -p 7788:7788 \+ -e OPENHUMAN_CORE_TOKEN="$(openssl rand -hex 32)" \+ -e BACKEND_URL=https://api.tinyhumans.ai \+ -e OPENHUMAN_APP_ENV=production \+ -v openhuman-workspace:/home/openhuman/.openhuman \+ ghcr.io/tinyhumansai/openhuman-core:latest+```++Or use the in-repo Compose file, which builds the image locally from `Dockerfile`. To consume the published image instead, replace the service's `build:` block in `docker-compose.yml` with `image: ghcr.io/tinyhumansai/openhuman-core:latest`; leaving `build:` in place keeps building from source and merely retags the result.++```bash+# On the server:+git clone https://github.com/tinyhumansai/openhuman.git+cd openhuman++# Configure secrets:+cp .env.example .env+# Edit .env - at minimum:+# BACKEND_URL=https://api.tinyhumans.ai+# OPENHUMAN_CORE_TOKEN=<openssl rand -hex 32>+# OPENHUMAN_APP_ENV=production++# Build and start:+docker compose up -d++# Verify:+docker compose ps+curl -fsS http://localhost:7788/health+```++### Headless install without Docker++If you can't run Docker on the host, grab the standalone CLI tarball attached to the latest [GitHub Release](https://github.com/tinyhumansai/openhuman/releases/latest):++```bash+# Pick the tarball that matches your host arch.+ARCH="$(uname -m)"+case "$ARCH" in+ x86_64) TARGET=x86_64-unknown-linux-gnu ;;+ aarch64) TARGET=aarch64-unknown-linux-gnu ;;+ *) echo "Unsupported arch: $ARCH"; exit 1 ;;+esac+VERSION=<version> # the release you want, from the Releases page+curl -fsSL "https://github.com/tinyhumansai/openhuman/releases/download/v${VERSION}/openhuman-core-${VERSION}-${TARGET}.tar.gz" \+ | tar -xz -C /usr/local/bin+openhuman-core --version+```++Then run `openhuman-core serve` under your service manager of choice (systemd, supervisord, …) with the same environment variables documented above.++The tarballs are dynamically linked, so the host's glibc has to be at least as new as the builder's: `aarch64` needs 2.39 or newer (Ubuntu 24.04, Debian 13), `x86_64` wants Ubuntu 22.04 or Debian 12 and newer. Check with `ldd --version` on the host.++### Headless self-update contract++Headless deployments should treat `openhuman.update_apply` as the safe primitive: it downloads the release asset, writes it atomically next to the current binary, and returns. Nothing exits automatically.++`openhuman.update_run` follows `config.update.restart_strategy`:++* `self_replace` (default): stage the binary, publish an in-process restart request, and let the running core respawn itself.+* `supervisor`: stage the binary and return `restart_requested=false`. Your outer service manager must restart the process.++For long-running Linux services, set:++```toml+[update]+restart_strategy = "supervisor"+rpc_mutations_enabled = false+```++or the equivalent env vars:++```bash+OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY=supervisor+OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED=false+```++Recommended `systemd` stance:++```ini+Restart=always+ExecReload=/bin/kill -HUP $MAINPID+```++Operator flow:++1. Call `openhuman.update_check` to discover a release.+2. Configure `restart_strategy = "supervisor"` under `[update]` in the core's `config.toml` (or set `OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY=supervisor`) so the core stages the new binary without trying to re-exec itself, then call `openhuman.update_apply` or `openhuman.update_run`. `restart_strategy` is a configuration setting, not an RPC parameter.+3. Restart the unit explicitly: `systemctl restart openhuman`.++If download or staging fails, the running binary is left in place and no restart is requested. If a staged binary proves bad after restart, roll back by restoring the previous binary from your package manager, image tag, or release artifact and restarting the supervisor again.++The Compose file ([`docker-compose.yml`](https://github.com/tinyhumansai/openhuman/blob/main/docker-compose.yml)) maps the core on `:7788`, mounts a named volume `openhuman-workspace` for persistence, and sets `restart: unless-stopped` so the core comes back after host reboots.++### Updating++```bash+git pull+docker compose build+docker compose up -d+```++For RPC-exposed production deployments, prefer leaving mutating update RPCs disabled (`OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED=false`) and perform rollouts through your existing image tag or package-management flow instead.++### Logs++```bash+docker compose logs -f openhuman-core+```++### Rotating the bearer token++`OPENHUMAN_CORE_TOKEN` is the only thing standing between the public internet and full RPC access. Rotate it on a schedule and after any suspected leak:++```bash+# 1. Generate a new token and update the server-side .env.+openssl rand -hex 32 > /tmp/new-token+sed -i.bak "s|^OPENHUMAN_CORE_TOKEN=.*|OPENHUMAN_CORE_TOKEN=$(cat /tmp/new-token)|" .env+rm /tmp/new-token .env.bak++# 2. Restart the container so the new value reaches the core process.+docker compose up -d --force-recreate openhuman-core++# 3. Confirm the running container is using the new token (redacted).+docker compose exec openhuman-core /bin/sh -c \+ 'echo -n "$OPENHUMAN_CORE_TOKEN" | head -c 8; echo "…"'++# 4. Re-paste the new token on every desktop client, in+# Settings -> Core connection. Clients that still hold the old token get+# HTTP 401 on the next /rpc call, which is expected rather than a regression.+```++For App Platform, do the same in **Settings → App-Level Environment Variables**: edit the `OPENHUMAN_CORE_TOKEN` secret and let App Platform redeploy. There is no separate token file to delete; the env var is the only state.++### Putting it behind TLS++Use Caddy, nginx, or Traefik as a reverse proxy in front of `:7788`. A minimal `Caddyfile`:++```caddy+core.example.com {+ reverse_proxy localhost:7788+}+```++***++## Pointing the desktop app at a hosted core++Configure this in the app, not in a file. **Settings → Core connection** (`app/src/components/settings/panels/CoreConnectionPanel.tsx`) takes the core's RPC URL and bearer token, offers a **Test connection** button that fires `core.ping` against the typed values, and shows live reachability for the active core. The pre-router first-run picker accepts the same two fields.++Enter the server's URL and the token you set on it:++| Deployment | URL to enter |+| ----------------------- | ------------------------------ |+| Public host behind TLS | `https://core.example.com/rpc` |+| Private tailnet-only VM | `http://100.x.x.x:7788/rpc` |++Saving persists the choice and restarts the app, so the normal boot gate re-runs against the new mode. A URL with no path is treated as the core's base and `/rpc` is appended for you, and a `user:pass@host` URL is rejected because the token field is the only credential path.++Plain `http://` is accepted without complaint only for loopback and private-network hosts, which includes RFC1918 ranges and the Tailscale `100.64.0.0/10` range (`isLocalOrPrivateNetworkHost` in `app/src/utils/configPersistence.ts`). A public `http://` host still saves, but the panel warns.++{% hint style="warning" %}+**A private address is not encryption.** Over plain `http://`, every `/rpc` request carries the bearer token in cleartext, and that token is the only credential the core checks. Anyone who can observe the link can read it and replay it, and "private" covers a shared office LAN, a hotel network and a coffee-shop Wi-Fi subnet as readily as it covers your own machine. Treat plain HTTP as safe only on a link you control end to end, such as loopback or an encrypted overlay like Tailscale or WireGuard. Use HTTPS for anything else.+{% endhint %}++`VITE_OPENHUMAN_CORE_RPC_URL` in `app/.env.local` is a build-time fallback only. The saved panel value outranks it, as does the shell's own `core_rpc_url` command, so setting it will not move a desktop client onto a remote core.++### Troubleshooting: sign-in fails after OAuth on a cloud runtime++Symptom: OAuth in the browser completes ("close this and return to the app"), but the desktop then shows a sign-in error, while the **same** account signs in fine on the local (embedded) runtime (issue #3025).++The desktop shell validates the fresh session token against the backend (`GET /auth/me`) itself and only then hands the credential to the core (`auth.set_credential`). On a cloud runtime that handoff travels to your server, so the usual causes are:++* **Wrong RPC token or URL.** A token mismatch surfaces as HTTP 401 on `/rpc`; re-paste the token (see "Rotating the bearer token") and check the URL.+* **Outdated core.** Older cores predate `auth.set_credential`; the desktop still sends the legacy `auth_store_session` name through an alias, but a core older than that alias rejects the call. Update the server to a current release.+* **`BACKEND_URL` unset or wrong on the server.** The remote core does not validate the session any more, but every backend call it makes on your behalf (billing, teams, managed inference) still goes there. It must be `https://api.tinyhumans.ai` for prod (or the staging URL).++Check the desktop log for the shell's session-owner lines (`[session]`) and the remote core log for `[credentials][set-credential]`. The desktop reports a cloud-specific, actionable message for these instead of a generic "try again" (issue #3025).++### Headless sign-in++A cloud core has no browser to complete OAuth in. Obtain a credential elsewhere and hand it to the core at boot:++* `OPENHUMAN_BACKEND_API_KEY=<key>`: a TinyHumans API key (recommended; no user identity, nothing to expire).+* `OPENHUMAN_BACKEND_SESSION_TOKEN=<jwt>`: a session JWT with a subject claim.++Either installs the credential only when the store has none of that kind; to rotate, clear first (`openhuman-core auth clear_credential --kind api-key`). The same operation is available over RPC as `openhuman.auth_clear_credential`.++### Headless without a TinyHumans account++Custom cloud providers (`inference_url` + `api_key`, or an entry in `cloud_providers`) are only built when a backend session or TinyHumans API key exists. Without one, every turn fails with `SESSION_EXPIRED: backend session not active — sign in to use custom providers`. Caller-owned runtimes are exempt from that gate, and `local-openai` is one of them, so any hosted OpenAI-compatible endpoint can run a headless core with no account:++1. Set `LOCAL_OPENAI_URL=https://<your endpoint>/v1` in the core's environment (`OPENHUMAN_LOCAL_INFERENCE_URL` also works and overrides it).+2. Store the endpoint's bearer key with `openhuman.config_update_local_ai_settings` (`runtime_enabled: true`, `opt_in_confirmed: true`, `api_key: "<key>"`).+3. Pin the workloads with `openhuman.config_update_model_settings`: `chat_provider`, `reasoning_provider`, `agentic_provider`, `coding_provider` (and `vision_provider`, `memory_provider`, `embeddings_provider` if you want them off the managed route) to `local-openai:<model-id>`, plus `default_model: "<model-id>"`. Those are the whole set the controller accepts; see `crates/openhuman-core/src/config/ops/model.rs`.++`openhuman.inference_agent_chat_simple` is the quickest end-to-end check. Managed features (integrations, teams, hosted voice) still need a TinyHumans credential; see [Local models and bring your own key](model-routing/local-and-byok-models.md).++### Secret storage in containers++In `production` and `staging` the keyring backend is `encrypted_file`, and its master key is loaded from the OS keychain. A container has no keychain, so the first write that stores a provider key fails with `Failed to encrypt api_key` (`[keyring] set error ... master key unavailable`). Supply the master key from the environment instead: `OPENHUMAN_KEYRING_MASTER_KEY` (64 hex characters) or `OPENHUMAN_KEYRING_MASTER_KEY_FILE` (a secret mount), described in "What you need before you start" (#6926). On a release that predates those variables, set `OPENHUMAN_KEYRING_BACKEND=file`, which keeps secrets in `$OPENHUMAN_WORKSPACE/dev-keychain.json` (plaintext, `0600`); put the workspace volume on encrypted storage and treat the host as the secret boundary.++Mount the key file without group- or world-write permissions. The core rejects group- or world-writable files, while read-only group/world access may be accepted for container secret mounts; any process able to read the file can decrypt the entire keyring. Restrict the mode where the mount is declared:++* Kubernetes: Secret volumes are root-owned, and `runAsUser` does not change the owner of a projected Secret. For a non-root core, use an init container running as root to copy the Secret into an `emptyDir`, `chown` the copy to the core UID, and `chmod 0400` it before the core starts. Mount the original Secret read-only in the init container and the `emptyDir` read-only in the core container. For example:++ ```yaml+ volumes:+ - name: master-key-secret+ secret:+ secretName: openhuman-master-key+ defaultMode: 0400+ - name: master-key+ emptyDir: {}+ initContainers:+ - name: prepare-master-key+ image: busybox:1.36+ command: ["sh", "-c", "cp /source/master.key /target/master.key && chown 10001:10001 /target/master.key && chmod 0400 /target/master.key"]+ volumeMounts:+ - name: master-key-secret+ mountPath: /source+ readOnly: true+ - name: master-key+ mountPath: /target+ containers:+ - name: openhuman+ securityContext:+ runAsUser: 10001+ runAsGroup: 10001+ runAsNonRoot: true+ env:+ - name: OPENHUMAN_KEYRING_MASTER_KEY_FILE+ value: /run/openhuman-master-key/master.key+ volumeMounts:+ - name: master-key+ mountPath: /run/openhuman-master-key+ readOnly: true+ ```++ Set the `emptyDir` medium and the core UID/GID to match the ownership applied by the init container. The `defaultMode: 0400` setting is important. For a direct non-root mount, also provide `fsGroup` (or equivalent group access) matching the core's group so kubelet can make the file readable; the resulting read-only `0440` mode is accepted. The init-container recipe above instead grants access by changing the copied file's owner. An equivalent setup is a secret volume whose `defaultMode` is `0400` and whose file is mounted with ownership matching the core's `runAsUser`/`runAsGroup`.+* Docker Swarm: set `mode: 0400` (with `uid`/`gid` for a non-root user) on the service's secret.+* A plain file: `chmod 600` it, owned by the user the core runs as.++***++## Named-volume ownership and the Docker entrypoint++Docker creates named volumes owned `root:root` by default. Because the core runs as the non-root `openhuman` user (UID 10001), the first write after the banner (`init_rpc_token → write_token_file` into `$OPENHUMAN_WORKSPACE`) would raise `Permission denied (os error 13)` if nothing fixes the ownership first.++The image ships a dedicated entrypoint at `/usr/local/bin/docker-entrypoint-core.sh` that:++1. Starts as `root`.+2. Runs `mkdir -p` + `chown openhuman:openhuman` on both `$OPENHUMAN_WORKSPACE` and `$HOME/.openhuman` (the directory `core.token` is written to when `OPENHUMAN_CORE_TOKEN` is unset).+3. Calls `exec gosu openhuman openhuman-core "$@"` to drop privileges and hand off to the binary.++This is **idempotent**: on a freshly-created volume the chown heals the root-owned directory; on a volume that was already healed the chown is a no-op. No manual `docker volume rm` is required when upgrading from images predating this fix.++The entrypoint is named `docker-entrypoint-core.sh` and wired **only** into the root `Dockerfile`. The E2E image (`e2e/docker-entrypoint.sh`) is unaffected.++***++## 4. Fly.io++[Fly.io](https://fly.io) is a good fit for `openhuman-core`: it handles TLS automatically, supports persistent volumes on all tiers, and can auto-stop idle machines to cut costs.++### Prerequisites++* [flyctl](https://fly.io/docs/flyctl/install/) installed and authenticated (`fly auth login`)+* A Fly.io account++### Step 1: Launch the app++```bash+fly launch --no-deploy --config .fly/fly.toml+```++Fly.io detects the `Dockerfile` automatically. Choose a region close to your users and skip the first deploy when prompted. This generates a config file.++### Step 2: Configure `.fly/fly.toml`++The repo ships a template at [`.fly/fly.toml`](https://github.com/tinyhumansai/openhuman/blob/main/.fly/fly.toml). Fill in `<your-app-name>` and `<your-region>` with the values you chose during `fly launch`:++```toml+app = '<your-app-name>'+primary_region = '<your-region>'++[build]+ dockerfile = "Dockerfile"++[env]+ OPENHUMAN_CORE_HOST = "0.0.0.0"+ OPENHUMAN_CORE_PORT = "7788"+ OPENHUMAN_WORKSPACE = "/home/openhuman/.openhuman"+ RUST_LOG = "info"++[[mounts]]+ source = "openhuman_workspace"+ destination = "/home/openhuman/.openhuman"++[http_service]+ internal_port = 7788+ force_https = true+ auto_stop_machines = 'stop'+ auto_start_machines = true+ # min_machines_running = 0 fully stops the machine when idle (cheapest), but+ # the first request after idle pays a cold-start penalty (container boot ++ # Rust binary init — several seconds). Set to 1 to keep one machine warm.+ min_machines_running = 0+ processes = ['app']++ [[http_service.checks]]+ interval = "30s"+ timeout = "5s"+ grace_period = "10s"+ method = "GET"+ path = "/health"++[[vm]]+ memory = '1gb'+ cpus = 1+```++### Step 3: Create a persistent volume++```bash+fly volumes create openhuman_workspace --size 5 --region <your-region> --config .fly/fly.toml+```++**Mount the workspace on a persistent volume** or data is lost on every redeploy.++### Step 4: Set secrets++```bash+# Required+fly secrets set OPENHUMAN_CORE_TOKEN="$(openssl rand -hex 32)"+fly secrets set BACKEND_URL="https://api.tinyhumans.ai"+fly secrets set OPENHUMAN_APP_ENV="production"++# Recommended for any publicly-reachable deployment:+fly secrets set OPENHUMAN_AUTO_UPDATE_RPC_MUTATIONS_ENABLED="false"+fly secrets set OPENHUMAN_AUTO_UPDATE_RESTART_STRATEGY="supervisor"++# Optional — error reporting and analytics:+fly secrets set OPENHUMAN_CORE_SENTRY_DSN="https://<key>@o<org>.ingest.sentry.io/<project>"+fly secrets set OPENHUMAN_ANALYTICS_ENABLED="true"+```++Save the value of `OPENHUMAN_CORE_TOKEN`. You will need it to connect the desktop app later. **Anyone with this token can drive the core**; treat it like a password and rotate it with `fly secrets set OPENHUMAN_CORE_TOKEN="$(openssl rand -hex 32)"` after any suspected leak.++### Step 5: Deploy++```bash+fly deploy --config .fly/fly.toml+```++Verify the core is healthy:++```bash+curl -fsS https://<your-app-name>.fly.dev/health+```++### Step 6: Point the desktop app at the hosted core++In the desktop app, open **Settings → Core connection**, switch it to the remote core, and enter:++* URL: `https://<your-app-name>.fly.dev/rpc`+* Token: the value you set in Step 4++Press **Test connection** to confirm before saving. The first-run picker takes the same two fields. See [Pointing the desktop app at a hosted core](cloud-deploy.md#pointing-the-desktop-app-at-a-hosted-core).++### Continuous deployment++To redeploy automatically on every push to `main`, add a workflow file at `.github/workflows/fly-deploy.yml`:++```yaml+name: Fly Deploy+on:+ push:+ branches:+ - main+ paths:+ - "src/**"+ - "Cargo.toml"+ - "Cargo.lock"+ - "Dockerfile"+ - ".fly/fly.toml"+ - "scripts/docker-entrypoint-core.sh"+jobs:+ deploy:+ name: Deploy openhuman-core+ runs-on: ubuntu-latest+ concurrency: deploy-group+ steps:+ - uses: actions/checkout@v4+ # Pin the Fly action to a tagged release (or a full commit SHA) rather+ # than `@master` — tracking a moving branch trusts every future commit+ # pushed there, including any made by a compromised maintainer account.+ - uses: superfly/flyctl-actions/[email protected]+ - run: flyctl deploy --remote-only --config .fly/fly.toml+ env:+ FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}+```++Generate a deploy token with `fly tokens create deploy` and add it as a repository secret named `FLY_API_TOKEN`.++### Updating++```bash+fly deploy --config .fly/fly.toml+```++For version-pinned deployments, update the image tag in `.fly/fly.toml` and redeploy:++```toml+[build]+ image = "ghcr.io/tinyhumansai/openhuman-core:v<version>"+```++### Logs++```bash+fly logs --config .fly/fly.toml+```++### Known gotcha: UID mismatch on volumes++If you switch between building from `Dockerfile` (which creates the `openhuman` user at UID 10001) and pulling the pre-built GHCR image (which uses UID 1000), files already written to the persistent volume will be owned by the old UID and produce `Permission denied (os error 13)` on startup.++The same thing happens to a Docker named volume that outlives an image upgrade, and to any workspace a **root** `docker exec` wrote into. `docker exec` does not run the entrypoint, so it lands as root and leaves a `root:root` `config.toml` behind (the core writes it at mode 0600, so the runtime user then cannot open it at all).++`scripts/docker-entrypoint-core.sh` now repairs this automatically: it chowns the workspace **recursively** on every start, skipping entries already owned correctly. If the repair cannot run, for example `cap_drop: ALL` without `cap_add: CHOWN`, the entrypoint refuses to start rather than booting a container that answers `/health` with 200 while every config RPC returns `Permission denied (os error 13)`, and prints the exact `chown` to run. Look for `[docker-entrypoint] pre-heal` / `FATAL` lines in the container log.++Fix an older container by SSH-ing in and re-owning the workspace:++```bash+fly ssh console --config .fly/fly.toml+chown -R openhuman:openhuman /home/openhuman/.openhuman/+exit+fly machine restart --config .fly/fly.toml+```++The Docker equivalent. Derive the ids from the container rather than hard-coding them, so this stays correct whichever image you are running:++```bash+docker exec -u 0 openhuman-core sh -c \+ 'chown -Rh "$(id -u openhuman):$(id -g openhuman)" /home/openhuman/.openhuman'+docker restart openhuman-core+```++To see which UID owns what before repairing. Note `docker exec` defaults to **root**, so ask about the runtime user explicitly rather than trusting a bare `id`:++```bash+docker exec openhuman-core sh -c 'id openhuman; ls -ln /home/openhuman/.openhuman/config.toml'+```++***++## Smoke test++Two failure modes guard the cloud deploy path:++* **`docker-image`**: sets `OPENHUMAN_CORE_TOKEN` and mounts no volume. Protects the DigitalOcean App Platform path (`.do/app.yaml`) where the token is always pre-set and no persistent volume is used.+* **`docker-volume-permissions`**: omits `OPENHUMAN_CORE_TOKEN` and mounts a fresh anonymous volume at `/home/openhuman/.openhuman`. Reproduces the exact failure mode of issue #2065 and asserts that `/health` returns 200 and that `Permission denied (os error 13)` is absent from the logs.++Run the smoke check locally:++```bash+docker build -t openhuman-core:smoke .++# Optional: tune build profile and Cargo parallelism.+# Keep CARGO_BUILD_JOBS=1 on constrained builders; raise it on larger machines.+docker build --build-arg CARGO_PROFILE=release --build-arg CARGO_BUILD_JOBS=4 -t openhuman-core:release .++# Token-set path (App Platform):+docker run -d --name oh-smoke -p 7788:7788 \+ -e OPENHUMAN_CORE_TOKEN=smoke-test-token \+ openhuman-core:smoke+curl -fsS http://localhost:7788/health+docker rm -f oh-smoke++# Fresh-volume / no-token path (Docker Compose, VPS):+docker volume create oh-vol-test+docker run -d --name oh-vol-smoke -p 7789:7788 \+ -v oh-vol-test:/home/openhuman/.openhuman \+ openhuman-core:smoke+curl -fsS http://localhost:7789/health+docker rm -f oh-vol-smoke+docker volume rm oh-vol-test+```++***++## 5. Oracle Cloud Infrastructure: Terraform on Always Free++A community-maintained Terraform stack runs the headless core on OCI's Always Free tier: an Ampere A1 VM in a private subnet running the release binary in a container, a flexible load balancer that forwards only `/rpc`, `/health` and `/events`, secrets in OCI Vault read by the VM's instance principal, OCI Generative AI as the model provider through the `local-openai` route above, and an Autonomous Database that agents reach through Oracle's managed Database Tools MCP Server once an operator registers a user access token for that server (the stack's post-apply step; the MCP server authenticates users, not the VM's instance principal).++Repository and run book: [https://github.com/kamelhar/openhuman-oci](https://github.com/kamelhar/openhuman-oci). Like the Fly and DigitalOcean recipes, it sets `OPENHUMAN_CORE_TOKEN`, mounts the workspace on persistent storage, and keeps the core off the public internet except through the load balancer.++***++## See also++* [Privacy & Security](privacy-and-security/): the trust model a server-hosted core inherits.+* [OS Keyring & Secret Storage](privacy-and-security/os-keyring-and-secret-storage.md): why a container needs a keyring master key.+* [Local models and bring your own key](model-routing/local-and-byok-models.md): running a headless core with no TinyHumans account.+* [Building the Rust Core](../developing/building-rust-core.md): compiling the binary a non-Docker host runs.+* [Architecture](../developing/architecture/architecture.md): what the core owns versus the shell.diff --git a/docs/gitbooks/docs/gitbooks/en/features/connections.md b/docs/gitbooks/docs/gitbooks/en/features/connections.mdnew file mode 100644index 0000000000..0d8a8e7ef3--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/connections.md@@ -0,0 +1,50 @@+---+description: >-+ One page for everything the agent plugs into: apps, channels, MCP servers,+ skills, memory, tools, the computer, the wallet, and every API key.+icon: plug+---++# Connections++**Connections** is the hub. Almost everything you would call a setting that changes what the agent _can do_, rather than how it looks, lives here, split into two groups in the left rail.++Most of the older addresses redirect here, so a bookmark to `/skills` or `/channels` still lands in the right place.++## Integrations++| Tab | What it holds |+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **OAuth** | The OAuth connectors. Pick a toolkit, authorize it in a browser window, and choose its scope (read, write or admin) and which triggers may fire. See [Third-party Integrations](integrations/). |+| **Channels** | The channels the agent talks to you on: Telegram, Discord, the in-app web chat, Lark/Feishu, DingTalk, iMessage, email over IMAP and SMTP, and 元宝. See [Messaging Channels](channels.md). |+| **MCP Servers** | Model Context Protocol servers, in four views: your servers, client config, the raw `mcp.json` (which is the only place a server is actually added), and a browsable registry. Includes a playground for calling one tool by hand. |+| **Skills** | Installed skill bundles, a registry to browse and install from, and a runner. See [MCP Servers & Skills](integrations/mcp-and-skills.md). |+| **Brain** | [Memory](memory.md): the engine, ask, explorer, learnings, conversations, the shared brain, background jobs and recall settings. |+| **Agent tools** | Which tools the agent may use, and the per-tool policy. |+| **Browser Control** | Desktop and browser control, the decision model, and the planner. See [Browser & Computer Control](native-tools/browser-and-computer.md). |+| **Wallet** | Balances, send and receive, and the recovery phrase. See [Wallet](wallet.md). |++## API keys++The second group is mostly one tab per engine family, each the same shape: use the managed TinyHumans route, or paste your own key. **Usage** is the exception, and reports spending and background activity rather than configuring anything.++| Tab | Covers |+| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **LLM** | Model providers: the managed route, your own keys for 26 built-in providers, and local servers (Ollama, LM Studio, MLX, any OpenAI-compatible endpoint). See [Automatic Model Routing](model-routing/). |+| **Composio** | Your own connector-platform key, if you would rather not use the managed route. |+| **Voice agents** | Speech-to-text and text-to-speech providers, per-workload routing, and the dictation hotkey. |+| **Embeddings** | The embedding provider behind memory and tool search. |+| **Search** | Web-search providers. Two have a managed route; the rest are bring-your-own-key. See [Web Search](native-tools/web-search.md). |+| **Usage** | What you have spent, by day and by model, plus the background-activity log. See [Billing, Cost & Usage](billing-and-usage.md). |++## Why one page++These used to be a dozen separate settings screens, and the split never held: connecting Gmail is an integration, a memory source, a trigger source and a set of agent tools at once, and so is connecting GitHub. Keeping them on one page with one rail means the thing you are setting up stays in front of you while you set up the parts of it that live in other systems.++Settings that change how the app _behaves_ rather than what it reaches, appearance, personality, security, keychain, autonomy, stay in [Settings](settings.md).++## See also++* [Getting Started](../overview/getting-started.md): the first-run path through this page.+* [Memory](memory.md), [Messaging Channels](channels.md), [Third-party Integrations](integrations/): the three tabs with the most behind them.+* [Privacy & Security](privacy-and-security/): what each connection means for what leaves your machine.diff --git a/docs/gitbooks/docs/gitbooks/en/features/goals-and-todos.md b/docs/gitbooks/docs/gitbooks/en/features/goals-and-todos.mdnew file mode 100644index 0000000000..54eb4ea132--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/goals-and-todos.md@@ -0,0 +1,52 @@+---+description: >-+ The agent's session todo list and its per-thread goals: in-session work+ state the chat pane reflects, rather than a task board you manage.+icon: target+---++# Goals & Todos++The agent tracks its own work in two places: a session todo list for the steps+of the request it is handling, and a per-thread goal for the objective that+thread is trying to finish.++---++## Agent work state++While it works on a multi-step request the agent keeps a session todo list,+the same shape Claude Code and Codex use: one `todo` tool call writes the whole+list (`content` + `pending` / `in_progress` / `completed`), scoped to the agent+session and held in memory for the life of the process. Thread goals are the+per-thread completion contract (`goal_set` / `goal_get` / `goal_complete`).++Neither is a kanban board. There is no per-thread task board, no card CRUD,+no approval gate, and no `thread_goals`, `todos`, or `threads_task_board` RPC+endpoint. Conversation threads remain the chat/session container.++---++## In the chat pane++Both show above the composer while the agent works, read-only: the agent+owns them, the pane reflects them.++- The **todo checklist** lists every step with its state: completed items+ strike through and stay, the one `in_progress` item is marked, and the+ header counts how many are done. It collapses to that header.+- The **goal banner** shows the objective, its status (active, paused, budget+ reached, complete) and tokens used against the budget when one was set.++Neither has an RPC of its own. Each tool call answers with its state as JSON,+so the pane reads the newest `todo` / `goal_*` tool result in the thread,+across the live turn and the thread's persisted turns, which is what keeps a+goal on screen for the many turns after the one that set it.++---++## See also++- [Memory](memory.md): durable preferences and facts live there as learnings; goals and todos are in-session only.+- [Native Tools](native-tools/README.md): where the `todo` and `goal_*` tool calls sit among the rest.+- [Agent Harness](../developing/architecture/agent-harness.md): the crate-backed stores behind both.diff --git a/docs/gitbooks/docs/gitbooks/en/features/hosting.md b/docs/gitbooks/docs/gitbooks/en/features/hosting.mdnew file mode 100644index 0000000000..f02fbbae3d--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/hosting.md@@ -0,0 +1,58 @@+---+description: >-+ Put a workspace folder on the internet: deploy a site, provision and wire a+ database, set environment variables, attach a domain, roll back.+icon: cloud-arrow-up+---++# Hosting++The agent can take a folder in your workspace and make it a live site, with a database behind it if the app needs one. Ask for it in chat; the deploy itself is a tool call like any other, and an irreversible one goes through the [Approval Gate](approval-gate.md).++{% hint style="info" %}+**Vercel is the only provider today.** The model underneath is provider-neutral, and Railway, Cloudflare and a self-hosted target are the named next steps, but nothing else is wired yet.+{% endhint %}++## What the agent can do++| Tool | Effect |+| --- | --- |+| `hosting_launch_site` | Deploy a workspace directory as a live site, optionally provisioning a database and wiring it in, setting environment variables, and attaching domains. |+| `hosting_deployment_status` | Whether a build has finished. |+| `hosting_list_deployments` | A site's recent deployments, newest first, with status and target. |+| `hosting_deployment_logs` | A deployment's build and runtime log events. |+| `hosting_rollback` | Point production back at an earlier deployment that already built. |+| `hosting_list_sites` | The sites on the account. |+| `hosting_set_env` | Set environment variables on an existing site. |+| `hosting_add_domain` | Attach a custom domain. |+| `hosting_domain_status` | Whether a site's domains are verified and serving. |+| `hosting_analytics` | Traffic over the last N days. |++A launch runs its five steps in the one order that works: create the site, provision the database, **connect the database before the build**, set the environment, then build. A framework that reads its environment at build time gets a broken build in any other order. The call returns while the build is still running, so the agent polls `hosting_deployment_status` rather than blocking.++There is a rollback and no separate promote, because a rollback *is* promoting an older deployment. It refuses a deployment that never finished building, since promoting a failed build would take the site down during an attempt to bring it back up.++## Two things it will not do++- **Read a secret.** A managed database's connection string is injected by the provider into the site's environment. OpenHuman learns the variable *names* and never their values, which is why a launch reports `DATABASE_URL` rather than a URL.+- **Deploy something you did not name.** The directory resolver refuses an absolute path, a `..` escape and anything that is not a directory. It is the one place that decides what may leave the machine, and a deployment uploads every byte under the folder it is given.++## Setting it up++```toml+[hosting]+enabled = true+provider = "vercel"+api_key = "" # leave blank to read the provider's own env var+team = "" # blank means your personal account+```++With `api_key` blank the credential comes from `TINYHOSTS_VERCEL_TOKEN`, falling back to `VERCEL_TOKEN`; a team account also reads `TINYHOSTS_VERCEL_TEAM_ID` or `VERCEL_TEAM_ID`.++`[hosting] enabled` is `false` by default. With it off, or with no credential resolvable anywhere, **the ten tools are not registered at all** rather than registered and failing. That is deliberate: a tool that is present and cannot work is worse than one that is absent, because a model retries it. A *misconfigured* section is an error and is logged rather than silently skipped: an unknown provider slug, or a key that is present but blank after trimming. Leaving `api_key = ""` out entirely, or set to the empty string, is the documented way to defer to the provider's environment variable and is not a misconfiguration.++## See also++- [Cloud Deploy](cloud-deploy.md): hosting the OpenHuman core itself, which is a different thing.+- [Approval Gate](approval-gate.md): how a deploy gets your yes.+- [Coder](native-tools/coder.md): building the thing before you ship it.diff --git a/docs/gitbooks/docs/gitbooks/en/features/integrations/README.md b/docs/gitbooks/docs/gitbooks/en/features/integrations/README.mdnew file mode 100644index 0000000000..7fa7f53aaf--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/integrations/README.md@@ -0,0 +1,93 @@+---+description: >-+ Managed OAuth into Gmail, Notion, GitHub, Slack, Stripe, Calendar and more -+ with one-click OAuth and zero API keys.+icon: plug+---++# Third-party Integrations++OpenHuman ships with backend-proxied access to the connector platform's managed-auth catalog, **119 toolkits** as the app knows them. Connecting one through the managed path is a one-click OAuth flow inside the app: no API keys to wire by hand, and no plugin marketplace to navigate.++That figure is the catalog the app ships (`KNOWN_COMPOSIO_TOOLKITS` in [`app/src/components/composio/toolkitMeta.tsx`](https://github.com/tinyhumansai/openhuman/blob/main/app/src/components/composio/toolkitMeta.tsx), pinned at 119 by [`toolkitMeta.test.tsx`](https://github.com/tinyhumansai/openhuman/blob/main/app/src/components/composio/toolkitMeta.test.tsx)). What you can actually connect is whatever the backend's allowlist returns when the page loads, and the per-toolkit action schemas are fetched live, so no number in this repository bounds the total actions reachable.++Under the hood, the connector layer is powered by [Composio](https://composio.dev) (the module is [`tinyconnectors`](https://github.com/tinyhumansai/tinyconnectors)). In the default managed mode, OpenHuman's backend owns the Composio API key, OAuth token brokering, rate limits, and trigger webhook fan-out. If you switch to direct mode, the core talks to Composio with your own Composio API key; synchronous tool calls work, but real-time trigger webhooks must be configured on your own webhook infrastructure.++Once a service is connected, it shows up in four places at once:++1. As an **agent tool**, the model can call it directly.+2. As a **profile signal**, your activity across services feeds your personalization.+3. As a **trigger source**, live events (a new email, a new charge, an inbound DM) flow into the [Triggers](triggers.md) pipeline and can fire off agent actions automatically.++## Some of what's in the catalog++The catalog spans productivity, business, social, messaging and Google. A non-exhaustive sample:++| Category | Examples |+| ----------------------- | ---------------------------------------------------- |+| **Email & calendar** | Gmail, Outlook, Google Calendar, Apple Calendar |+| **Docs & storage** | Google Docs, Google Drive, Notion, Dropbox, Airtable |+| **Code & dev** | GitHub, Linear, Jira, Figma |+| **Comms** | Slack, Discord, Microsoft Teams, Telegram, WhatsApp |+| **CRM & sales** | Salesforce, HubSpot |+| **Commerce & payments** | Stripe, Shopify |+| **Project management** | Asana, Trello |+| **Social** | Twitter / X, Spotify, YouTube |++## Native vs proxied++Some services have **native providers**. Rust modules that know how to ingest the service into memory directly (e.g. Gmail's native ingest path). Others are exposed as **proxied tools** only: the agent can call them, but there's no automatic ingest yet. New native providers are added as features land.++## How connections work++Click **Connect** on any integration. A browser window opens for OAuth. Once you sign in, the connection becomes active and you can add it as a [memory source](../memory.md) to sync it on a schedule.++Each integration shows its current status:++* **Not connected**: the integration has not been set up.+* **Connected**: the integration is active and being synced.+* **Manage**: an active integration, with options to reconfigure or disconnect.++You can revoke any connection at any time from the **Connections** page.++## Messaging channels++Some integrations are not just something to read from: OpenHuman uses them to _talk back_ to you. Eight channels have a setup flow in the app, and more are available by hand in `config.toml`. The three you are most likely to start with:++* **Telegram**: the usual first choice. Two-way, with a managed one-click connection or your own bot token.+* **Discord**: two-way, by OAuth or your own bot token, with a server and channel picker.+* **Web**: the chat inside the desktop app itself. Messages stay entirely local.++Set your default under **Connections → Channels**. [Messaging Channels](../channels.md) has the full list and what each one can do.++## Beyond the curated catalog: MCP & Skills++The managed OAuth connectors are the curated path. Beyond them, OpenHuman opens up the wider open-tooling ecosystem:++* **MCP servers**: a built-in registry browses thousands of [Model Context Protocol](https://modelcontextprotocol.io) servers (Smithery + the official registry) that install locally as new agent tools.+* **Skills**: a browsable catalog of `SKILL.md` capability bundles aggregated from several public registries, installed from the **Connections → Skills** tab. The old in-app JavaScript sandbox is gone; a skill runs as its own agent session with the interpreters it declares, not as code inside the app.++See [MCP Servers & Skills](mcp-and-skills.md) for the full picture.++## Native voice and tools++Two capabilities ship native rather than as integrations because they're load-bearing for the desktop experience:++* [**Voice**](../native-tools/voice.md): STT in, TTS out, and a live voice agent you can interrupt mid-sentence.+* [**Native tools**](../native-tools/): built-in web search, a web-fetch scraper, and a full filesystem, git, lint, test and grep coder toolset the agent has out of the box.++## Privacy boundary++OpenHuman's core never calls any third-party API directly. All requests go through the OpenHuman backend, which handles OAuth tokens and rate limiting. Your tokens never sit on disk in plaintext on your machine, and the agent only sees the _results_ of tool calls, not the credentials.++If you opt into direct Composio mode, that boundary changes: your local core uses your own Composio API key and you are responsible for the Composio account, rate limits, billing relationship, and any webhook endpoint needed for trigger delivery.++See [Privacy & Security](../privacy-and-security/) for the full boundary.++## See also++* [Triggers](triggers.md), live events from connected integrations and how they fire agent actions.+* [Memory](../memory.md)+* [MCP Servers & Skills](mcp-and-skills.md), the open-tooling path beyond the curated catalog.+* [`integrations` domain](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/integrations/README.md), the Rust side of this page.+* [Architecture](../../developing/architecture/), for how the backend proxy fits the core.diff --git a/docs/gitbooks/docs/gitbooks/en/features/integrations/mcp-and-skills.md b/docs/gitbooks/docs/gitbooks/en/features/integrations/mcp-and-skills.mdnew file mode 100644index 0000000000..93cb8872cc--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/integrations/mcp-and-skills.md@@ -0,0 +1,46 @@+---+description: >-+ Beyond the curated OAuth connectors - browse thousands of MCP servers and a+ 90,000-entry Skills catalog, and let OpenHuman act as an MCP server itself.+icon: blocks+---++# MCP Servers & Skills++The [one-click OAuth integrations](README.md) are the curated path. Beyond them, OpenHuman opens up the wider open-tooling ecosystem in two ways: the **Model Context Protocol (MCP)** registry and the **Skills** catalog. OpenHuman can also expose _itself_ as an MCP server to other clients.++---++## MCP servers (thousands)++OpenHuman has a built-in **MCP registry** that browses the open MCP ecosystem and lets you install servers locally as new typed tools for the agent.++- **Two upstream registries, merged.** Discovery fans out in parallel to [Smithery.ai](https://smithery.ai) and the official [`registry.modelcontextprotocol.io`](https://registry.modelcontextprotocol.io), then merges the results: thousands of servers across both.+- **Search → install → connect.** Search the catalog, view a server's details, and install it. A local install spawns the server as a stdio subprocess; deployed servers connect over HTTP.+- **Supervised connections.** Installed servers are persisted in a local SQLite store (`mcp_clients/mcp_clients.db`) with their command, args, and transport. A supervisor loop keeps enabled servers connected, probing every ~60s with per-server exponential backoff. Each non-nominal probe outcome (a slow answer, a dropped transport, a reconnect that succeeded or failed) shows up in **Settings → Developer → Event Log** under the `mcp` badge. An answered probe does not, so a healthy server stays silent. A server that stays down, comes back after failing, or cannot start because its launcher runtime is missing raises a notification.++Once connected, an MCP server's tools are available to the agent exactly like native tools.++> The catalogs are open-ended and grow on their own. The "5,000+" figure reflects the combined Smithery + official ecosystem size, not a fixed list baked into OpenHuman.++### OpenHuman as an MCP server++OpenHuman can run the other way around, too. `openhuman-core mcp` exposes OpenHuman over stdio as an MCP server, offering memory tools (recall with citations, fetch, list, learn and forget) and optional web search to clients like Claude Desktop. See [MCP Server](../../developing/mcp-server.md) for setup.++---++## Skills (90,000-entry catalog)++**Skills** are a large, browsable catalog of agent skills (`SKILL.md`-style capability bundles) aggregated from multiple upstream sources (HermesHub, ClawHub, LobeHub, and more).++- **One aggregated catalog.** Sourced from HermesHub (configurable via `OPENHUMAN_SKILL_REGISTRY_CATALOG_URL`), the catalog runs to roughly **90,000 entries**. Each entry carries id, name, description, source, author, version, tags, platforms, a download URL, and license.+- **Cached and fast.** The catalog is fetched on boot in the background (without blocking startup), cached locally at `~/.openhuman/skill-registry/cache.json` with a ~1-hour TTL and served stale-while-revalidate. A single-flight gate prevents duplicate downloads of the large catalog.+- **Metadata-first.** OpenHuman's in-app skills runtime (the old QuickJS sandbox) has been **removed**. Skills are now a metadata catalog you browse and install from the **Connections → Skills** tab, not code executing inside the app. Availability varies per entry: some expose a direct `SKILL.md` download, others point to external hosting.++---++## See also++- [Third-party Integrations](README.md): the curated managed-auth OAuth connectors.+- [MCP Server](../../developing/mcp-server.md): running OpenHuman as an MCP server.+- [Available Tools](../native-tools/README.md): the native tools that ship by default.diff --git a/docs/gitbooks/docs/gitbooks/en/features/integrations/triggers.md b/docs/gitbooks/docs/gitbooks/en/features/integrations/triggers.mdnew file mode 100644index 0000000000..fb1db15355--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/integrations/triggers.md@@ -0,0 +1,135 @@+---+description: >-+ Live events from connected integrations (a new Gmail message, a Notion edit, a+ Stripe charge) arrive as triggers, get classified by a triage agent, and can+ fire agent actions automatically.+icon: bolt+---++# Triggers++A connected integration is not just a place the agent can read from on demand. It is also a **source of live events**. When someone sends you an email, edits a Notion page, opens a GitHub issue on one of your repos, charges a card on Stripe, or DMs you on Slack, OpenHuman receives that event in near-real-time and can decide whether to do something about it.++This page is about that pipeline: how triggers arrive, how they get classified, and how a trigger can turn into a full agent action without you typing a thing.++## What a trigger is++A trigger is an external event published by an integration you've connected. Common shapes:++| Integration | Example trigger |+| ------------ | ----------------------------------------------------------------- |+| **Gmail** | `GMAIL_NEW_GMAIL_MESSAGE`, new mail in inbox |+| **Slack** | `SLACK_NEW_MESSAGE`, channel/DM message you were mentioned in |+| **Notion** | `NOTION_PAGE_UPDATED`, a tracked page changed |+| **GitHub** | `GITHUB_ISSUE_OPENED`, `GITHUB_PULL_REQUEST_OPENED` on your repos |+| **Stripe** | `STRIPE_CHARGE_SUCCEEDED`, a successful charge on your account |+| **Calendar** | `GOOGLE_CALENDAR_EVENT_CREATED`, a new event on your calendar |++The full set comes from the [Composio](https://composio.dev) connector layer that powers [third-party integrations](./). When a connection is active, the relevant trigger subscriptions are wired up automatically.++### Gmail OAuth scopes++Gmail trigger subscriptions require message-read access on the connected Google account. Fresh OpenHuman Gmail authorizations request `https://www.googleapis.com/auth/gmail.readonly` so `GMAIL_NEW_GMAIL_MESSAGE` can be enabled and the native Gmail sync path can read the new message metadata.++If an older Gmail connection was created before this scope was requested, reconnect Gmail from Settings before enabling Gmail triggers.++## Where triggers come from, end to end++```+┌────────────────────┐+│ third-party API │ Gmail / Slack / Notion / GitHub / ...+└─────────┬──────────┘+ │ webhook+ ▼+┌────────────────────┐+│ OpenHuman backend │ HMAC-verifies the webhook, normalises the payload+└─────────┬──────────┘+ │ Socket.IO event ("composio:trigger")+ ▼+┌────────────────────┐+│ Rust core │ publishes DomainEvent::ComposioTriggerReceived+│ (your laptop) │ on the in-process event bus+└─────────┬──────────┘+ │+ ▼+┌────────────────────┐+│ Trigger Triage │ classifies: drop / acknowledge / react / escalate+└─────────┬──────────┘+ │+ ▼+┌────────────────────┐+│ One of: │+│ - nothing │ ← drop+│ - memory note │ ← acknowledge+│ - Trigger Reactor │ ← react (1-2 tool calls)+│ - Orchestrator │ ← escalate (full multi-step planning)+└────────────────────┘+```++The webhook never reaches your machine raw. The backend is what holds the OAuth token and what receives the webhook directly from the third-party. It does HMAC verification, normalises the payload, and forwards it to your Rust core over the existing authenticated socket. Your laptop sees a clean, validated `ComposioTriggerReceived` event on the bus, nothing else.++## The triage step++Before any action runs, every trigger goes through the [`trigger_triage`](../../../../../../../crates/openhuman-core/src/agent/registry/agents/trigger_triage/) agent. Its only job is to decide what the rest of the system should do.++It picks exactly one of four actions:++| Action | What happens | When to use |+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| **`drop`** | Nothing. Trigger is silently logged and discarded. | Spam, duplicates, irrelevant noise. The default for things you don't care about. |+| **`acknowledge`** | A short memory note is persisted, no agent runs. | Passive notifications worth remembering ("a new page was created in archive"). |+| **`react`** | The [`trigger_reactor`](../../../../../../../crates/openhuman-core/src/agent/registry/agents/trigger_reactor/) agent runs with one or two tool calls. | A small, single-step side effect: store a memory entry, post a quick acknowledgement, mark a thread read. |+| **`escalate`** | The full **orchestrator** agent takes over with planning capability. | Anything that needs reasoning, multiple steps, or multiple skills: drafting a reply, updating several Notion pages, deciding how to triage an inbound issue. |++The triage agent has the same memory and workspace context the rest of the agent has. It can tell whether a trigger is relevant to something you're currently working on, who the people involved are, and whether it's the kind of thing you've asked OpenHuman to act on before.++## When a trigger turns into an agent action++This is the part that distinguishes "OpenHuman has a Gmail integration" from "OpenHuman is on call for your inbox":++* **`react`** is the cheap path. The Trigger Reactor is a narrow specialist with a hard budget of a couple of tool calls. It's perfect for: writing a one-line memory note that says "saw a new charge from Stripe for $84, customer X, merchant Y", silently marking a Slack message as handled because it's the same automated alert you've already triaged twice this week, or storing a structured record of an event the user might want to look up later.+* **`escalate`** is the heavy path. When the Triage agent decides the trigger needs real work, it hands off to the Orchestrator with a self-contained task description. The orchestrator has access to your full skill surface, tools, and memory. From there it might:+ * Draft a reply to an important email and queue it for your approval.+ * Pull up the relevant Notion / Linear / Drive context for an inbound issue and write a structured comment.+ * Update three connected systems based on a single inbound event ("this customer's plan changed in Stripe, update HubSpot, post in #revenue, and add a note to their Notion file").++In both cases the action runs on your machine, against your configured memory engine, with the same model-routing and tool surface the rest of the agent uses.++## Why a triage step at all++It's tempting to skip the classifier and just pipe every trigger straight into the orchestrator. That's a bad idea for two reasons:++1. **Most triggers are noise.** A connected Gmail account fires dozens of triggers an hour, the vast majority of which the user doesn't care about. Running the orchestrator on each would burn budget and produce a constant stream of background activity.+2. **Different triggers deserve different ceilings.** An automated Stripe receipt and a personal Slack DM should not cost the same number of tokens to handle. Triage lets the cheap path be cheap and reserves the orchestrator for things that earn it.++Triage runs on the fast model tier (see [Automatic Model Routing](../model-routing/)) so the classification itself is sub-second.++## Configuration and opt-out++* **On by default.** Once an integration is connected, its triggers feed into the pipeline automatically.+* **Opt-out.** The triage path is gated on the `OPENHUMAN_TRIGGER_TRIAGE_DISABLED` environment variable. Setting it to `1` / `true` / `yes` turns off agent classification and falls back to passive logging only. The integration itself stays connected; only the auto-action behaviour is suppressed.+* **Per-trigger settings.** Trigger settings (which integrations and event types should be evaluated) are managed under **Settings**; the underlying RPC methods are `update_composio_trigger_settings` / `get_composio_trigger_settings`.+* **Audit log.** Every trigger, regardless of decision, is written to the trigger history so you can see what arrived, what the classifier decided, and what (if anything) ran. Decisions and escalations are also published as `TriggerEvaluated` / `TriggerEscalated` events on the in-process bus, which means anything inside the core can subscribe to them.++## Privacy boundary++Triggers follow the same boundary as the rest of the product (see [Privacy & Security](../privacy-and-security/)):++* The third-party token lives on the backend, never on your laptop.+* The webhook is HMAC-verified by the backend before it reaches your machine.+* The trigger payload is processed by your local core; classification and any reaction run on your machine, against your configured memory engine.+* Memory notes written by `acknowledge` / `react` / `escalate` paths are stored as learnings in your memory engine when memory is on.++## Implementation pointers (for developers)++* Triage agent: `crates/openhuman-core/src/agent/registry/agents/trigger_triage/`+* Reactor agent: `crates/openhuman-core/src/agent/registry/agents/trigger_reactor/`+* Composio bus subscriber: `crates/openhuman-core/src/integrations/composio/bus.rs` (`ComposioTriggerSubscriber`)+* Trigger history persistence: `crates/openhuman-core/src/integrations/composio/trigger_history.rs`+* Domain events: `DomainEvent::ComposioTriggerReceived`, `DomainEvent::TriggerEscalated` in `crates/openhuman-core/src/core/events.rs`+* Trigger settings RPC: `update_composio_trigger_settings` / `get_composio_trigger_settings` in `crates/openhuman-core/src/config/`++## See also++* [Third-party Integrations](./), the catalog of services triggers come from.+* [Memory sources](../memory.md), the polling counterpart, periodic ingest of source data into memory.diff --git a/docs/gitbooks/docs/gitbooks/en/features/ios-companion.md b/docs/gitbooks/docs/gitbooks/en/features/ios-companion.mdnew file mode 100644index 0000000000..38cfc4f18a--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/ios-companion.md@@ -0,0 +1,101 @@+---+description: >-+ Pair an iOS companion app to your desktop OpenHuman over an end-to-end+ encrypted tunnel, scanned from a QR code.+icon: mobile-screen+---++# iOS Companion++The iOS Companion lets you reach your desktop OpenHuman from your phone: you scan a QR code shown on the desktop, the two devices agree on a shared key, and from then on the phone talks to the desktop core over an encrypted channel.++{% hint style="warning" %}+**Experimental / non-shipping.** The iOS client is in-progress and is **not** part of the shipped desktop product. APIs, wire formats, and the pairing flow can change without notice, and an upgrade may force you to re-pair. Treat everything below as a developer preview.+{% endhint %}++The desktop core is always the source of truth. The phone is a thin client. It does not run its own agent, it relays requests to the core and renders the results.++What is experimental here is the **client**, not the core. The core's pairing domain is complete and wired into the controller registry (`crates/openhuman-core/src/security/devices/`): it registers the channel, derives the keys, persists the device, and tracks peer status. Earlier contributor notes described pairing as blocked on an unmerged backend change; that is no longer the case. Two real gaps remain, both noted below: there is no desktop screen for managing paired devices, and revocation is local-side only.++***++## What it is++Pairing is brokered by the Rust `devices` domain in the core. The core registers a pairing channel with the tinyhumans backend's `tunnel:*` Socket.IO relay, generates a fresh X25519 keypair, and renders a QR code. The phone scans it, generates **its own** X25519 keypair, and connects back over the same relay. The backend is a **blind forwarder**: it relays opaque frames and never sees plaintext.++Pairing and revocation are core RPCs, not a desktop screen. The old **Settings → Devices** page was removed and its slug now redirects to **Settings → Account** (`app/src/components/settings/settingsRouteRegistry.ts`), and nothing in the desktop frontend calls the `devices_*` methods. Listing and revoking a paired device means calling the core directly for now.++***++## Pairing via QR code++```+Desktop core Backend relay iOS app+ | | |+ |-- devices_create_pairing RPC | |+ |-- tunnel:register ----------------->| |+ |<-- channel_id, expires_at ----------| |+ |-- generate X25519 keypair | |+ |-- tunnel:connect (role: core) ----->| |+ | | |+ | shows QR: | |+ | cid, pt, cpk, rpc?, exp | |+ |.................. scan QR ......................> |+ | | generate device |+ | | X25519 keypair |+ | |<-- tunnel:connect ------|+ | | (role: client) |+ |<------ tunnel:frame (handshake) ----|------------------------|+ |-- X25519 DH + derive session keys | |+ |-- persist PairedDevice | |+ |-- publish DevicePaired event | |+ | devices_list now returns it | |+```++The QR payload (carried as an `openhuman://pair?...` deep link) contains the channel id (`cid`), a single-use pairing token (`pt`), the core's public key (`cpk`), an optional LAN URL (`rpc`), and an expiry (`exp`). The pairing token is single-use and the QR is rejected client-side once `exp` has passed. The core does not choose that expiry: it stores and republishes whatever `pairingExpiresAt` the backend returns in its `tunnel:register` ACK, so the real TTL is the backend's.++***++## The end-to-end tunnel++Confidentiality and integrity live entirely on the two endpoints. The exact primitives, from `crates/openhuman-core/src/security/devices/crypto.rs`:++* **Key agreement:** X25519 Diffie-Hellman. Each side has a long-term static keypair (the core's is in the QR; the device's is minted at scan time) plus an ephemeral keypair minted per session for forward secrecy.+* **Session-key derivation:** HKDF-SHA256 over `ikm = static_dh || eph_dh`, salted with `client_eph_pub || server_eph_pub`. Two **directional** 32-byte subkeys are expanded with distinct info tags (`openhuman-tunnel/v1/c2s` and `openhuman-tunnel/v1/s2c`), so a frame one side seals can never decrypt under its own opener (closes the cross-direction reflection attack class).+* **Frame cipher:** XChaCha20-Poly1305 (AEAD, 192-bit nonce). Wire format is `version(0x02) || nonce(24) || ciphertext+tag`, with a random nonce per frame.+* **Replay protection:** a sliding window over the last 128 nonces seen per opener.++Static DH authenticates the peer via the QR-code provenance; ephemeral DH means a later static-key leak cannot decrypt past traffic. The legacy single-key `version=0x01` frame shape is rejected with an explicit "re-pair required" error, so peers must re-pair after an upgrade. Outbound frames are capped at 64 KB.++***++## Transport strategies++The phone may reach the core three ways. `TransportManager` (`app/src/services/transport/`) picks one from the saved `ConnectionProfile`; for a paired device it **races LAN against the tunnel** (2 s LAN timeout) and uses whichever answers `openhuman.ping` first.++| Strategy | Class | When it's used | Trade-offs |+| ------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |+| **LAN HTTP** (`LanHttpTransport`) | Direct HTTP to the core's LAN `rpc_url` | Phone and desktop on the same network | Fastest, lowest latency. Requires same LAN; not encrypted by this layer (relies on local network trust). |+| **Tunnel** (`TunnelTransport`) | E2E encrypted frames over the backend Socket.IO relay | Anywhere with internet; default fallback | Works across networks; X25519 + XChaCha20-Poly1305 end to end. Higher latency (relayed); depends on backend availability. |+| **Cloud HTTP** (`CloudHttpTransport`) | HTTP to a cloud-hosted core endpoint | Profile `kind: "cloud"`, when LAN and tunnel are unreachable | Reachable from anywhere; depends on a hosted core and its own auth. |++***++## Device management & revocation++Paired devices are persisted by the core in SQLite (`{workspace_dir}/devices/devices.db`, table `paired_devices`): channel id, label, the device's public key, a SHA-256 hash of the core session token, and timestamps. The core's X25519 private key is stored encrypted at rest (via the OS keyring `SecretStore`) so handshakes survive a restart.++* **Create**: `devices_create_pairing` registers the channel, mints and persists the keypair, and returns the QR fields.+* **List**: `devices_list` returns non-revoked devices, overlaying a live `peer_online` flag sourced from `tunnel:peer-status` (online status is never persisted).+* **Revoke**: `devices_revoke` soft-deletes the device, tears down all in-memory and tunnel state for the channel, and publishes a `DeviceRevoked` event. Today revocation is local-side: the backend channel is left to expire via its pairing-token TTL (a backend revoke endpoint is a follow-up).++All three are reachable over JSON-RPC as `openhuman.devices_create_pairing`, `openhuman.devices_list` and `openhuman.devices_revoke`, and on the CLI through the generic namespace dispatcher: `openhuman-core devices create_pairing`, `openhuman-core devices list`, `openhuman-core devices revoke --channel_id <id>`.++***++## See also++* [Privacy & Security](privacy-and-security/): how OpenHuman handles your data and keys.+* [Voice](native-tools/voice.md): push-to-talk and dictation, the headline use case for a phone companion.+* [Architecture](../developing/architecture/architecture.md): where the iOS client sits relative to the core.+* [OS Keyring & Secret Storage](privacy-and-security/os-keyring-and-secret-storage.md): where the core's X25519 private key is kept.diff --git a/docs/gitbooks/docs/gitbooks/en/features/mascot.md b/docs/gitbooks/docs/gitbooks/en/features/mascot.mdnew file mode 100644index 0000000000..e85ff1d57f--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/mascot.md@@ -0,0 +1,56 @@+---+description: >-+ The on-screen face of OpenHuman: a desktop mascot that speaks, reacts, and+ keeps working in the background even when you aren't looking at it.+icon: face-smile+---++# The Mascot++OpenHuman has a face. The mascot is an animated character that lives on your desktop and acts as the visible surface of the agent, what it's saying, what it's thinking about, when it's idle, when it's busy, when it has something to tell you.++It is not a chrome ornament. The mascot is wired into the same pieces as the rest of the agent: [voice](native-tools/voice.md), [memory](memory.md) and [scheduled runs](native-tools/cron.md). When the agent talks, the mascot is the one talking; when the agent is thinking, the mascot is the one thinking.++## What it does++### It speaks, and lip-syncs to its own voice++When the agent replies, the audio is generated through a hosted TTS model and streamed to your speakers. At the same time, the mascot drives a viseme map against the audio so its mouth shapes match the words coming out. There's no separate "talking head" video, the same audio stream that you hear is the one driving the animation.++See [Native Voice](native-tools/voice.md) for the speech-to-text and text-to-speech plumbing the mascot rides on top of.++### It moves and reacts to its surroundings++The mascot has mood states (idle, thinking, listening, talking, surprised) and it transitions between them based on what the agent is doing. When you start typing it shifts into a listening pose. When the model is reasoning, it shows that. When a tool call returns something noteworthy, it reacts. When you stop interacting for a while, it drifts into idle.++After a turn finishes, the desktop mascot also reads the conversation-level cue that arrives with the chat result. A success cue produces a short happy acknowledgement, uncertainty produces a confused acknowledgement, and warnings or failed outcomes produce a concerned acknowledgement. If no strong cue is present, it keeps the existing calm post-turn acknowledgement and falls back to idle.++It is meant to feel alive, not animated-on-rails.++### It remembers you++The mascot is the visible part of an agent that has [memory](memory.md) underneath it. It remembers what you've talked about, what you prefer, what's in your documents and what's been decided, across the sources you've added. When it greets you in the morning, it isn't starting from zero.++That memory is what makes the personality consistent over weeks and months. The mascot you talk to today knows what the mascot you talked to last Tuesday knows.++### It works while you're away++Even when you've stopped typing, work can keep happening on your behalf: [scheduled routines](native-tools/cron.md) run on a cron expression, [triggers](integrations/triggers.md) fire on inbound events, and [workflows](workflows.md) execute durable, approval-gated graphs. So when you come back to the desk, the mascot may have already drafted the email, refreshed the dashboard, or queued the question it needs to ask you. The face on the screen is the one that did the work.++## Why have a mascot at all?++Most assistants are a blinking text input. That's fine for a tool. It's not fine for something that's meant to be alongside you all day, with persistent memory of your life, taking actions on your behalf.++The mascot exists because:++* **Presence beats panels.** A face you can glance at tells you, in one frame, whether the agent is busy, idle, or trying to get your attention.+* **It makes talking feel like a conversation.** An animated character lip-syncing to its own speech is a different experience from a robotic voice and a blank panel.+* **Personality is a UX surface.** A consistent character on screen is easier to trust, talk to, and forgive when it makes a mistake than a faceless API.++## See also++* [Native Voice](native-tools/voice.md), the STT / TTS plumbing the mascot rides on.+* [Memory](memory.md), what the mascot remembers, and how.+* [Themes & Theme Studio](theming.md), where the mascot's colour, shape and voice are set.+* [Chat](chat.md) and [Notifications & Activity](notifications-and-activity.md), where the mascot's cues surface.+* [`voice` domain](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/voice/README.md), the Rust side of speech.diff --git a/docs/gitbooks/docs/gitbooks/en/features/memory.md b/docs/gitbooks/docs/gitbooks/en/features/memory.mdnew file mode 100644index 0000000000..b3e0de0301--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/memory.md@@ -0,0 +1,113 @@+---+description: >-+ Memory: a pluggable engine that stores your documents, conversations and+ learnings, recalls what matters before every turn, and answers questions with+ citations.+icon: brain+---++# Memory++OpenHuman's memory lets the agent remember you across chats: what you are working on, what you prefer, what is in your documents. Memory is a feature of the app, not a hidden database. You pick who stores it, see what is stored, and delete anything.++Open it from **Connections → Memory**. It has eight tabs (chips): **Engine**, **Ask**, **Explorer**, **Learnings**, **Conversations**, **Brain**, **Background** and **Settings**. The old `/brain` and `/settings/memory-engine` addresses redirect there.++## How the agent uses memory++Memory works around every turn, without the agent having to ask:++* **Before the model answers**, OpenHuman logs what you said and recalls a short, token-budgeted _memory pack_ for the turn: relevant learnings (and beliefs the engine has built from them), documents from your brain, this agent's earlier conversations and, briefly, other agents'. The pack is added to the model request for that turn only. It is never written into the chat, so the conversation itself stays exactly as you had it.+* **After the answer**, the reply is logged together with a one-line result for each tool it used.+* **When a long chat is compacted**, OpenHuman recalls what the folded-away turns covered and adds it to the summary that replaces them.+* **In the background**, every few minutes, the engine builds beliefs from what was stored ("the user prefers short answers", "deploys happen on Fridays").++The answer's memory chips show which stored items the pack cited. To see what a turn would get, open **Ask → Pack preview**.++## Engines++An engine stores your memory and answers questions about it. There are two:++| Engine | What it is | Needs |+| -------------- | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |+| **TinyHumans** | Hosted CortexDB run by TinyHumans, reached through the TinyHumans backend | You are signed in, or the host supplies a TinyHumans API key (headless and library hosts) |+| **CortexDB** | Your own CortexDB, called directly (managed `api-v1.cortexdb.ai` or self-hosted) | A CortexDB API key (kept in the OS keychain), and an endpoint if not the managed one |++Either way your memory items are stored in CortexDB, not on your computer; OpenHuman keeps only bookkeeping (queued jobs, sync and import progress) locally. See [Where your memory is stored](privacy-and-security/#where-your-memory-is-stored).++Pick one on the **Engine** tab. If you are signed out and have neither a CortexDB key nor a host-supplied TinyHumans API key, memory is **off**: the agent has no memory tool, nothing is stored, and the Memory page tells you why.++## What the engine does++* **Recall** answers a question in plain language and cites the stored items it relied on. The engine implements it.+* **Fetch** is raw search over stored items with metadata filters (folder, repo, thread, source, time window). Both launch engines support hybrid search only.+* **Store** takes three kinds of items: documents, conversations and learnings.++## What gets stored++### The brain: documents++The **Brain** tab holds documents every agent shares, filed by source type: `pdf`, `markdown`, `notion`, `github`, `web`, and one per other source (`gmail`, `docx`, …). It shows how many documents each source holds, lets you search them, add one (pasted text or a file on your computer), and forget a whole source.++Below that, **Synced sources** keep the brain up to date. A source is one of:++| Kind | Target | Filed under |+| -------- | --------------------------- | ---------------------------------------------- |+| `folder` | A folder on your computer | `pdf`, `web` (HTML) or `markdown` by file type |+| `file` | A single file | as for a folder |+| `link` | A web page | `web` |+| `github` | A repository (`owner/repo`) | `github` |+| `rss` | A feed URL | `web` |++Sources sync when you press sync and on a schedule you set per source. An unchanged file that syncs again is not stored twice. Removing a source can also forget the items it produced.++### Conversations++Every turn is logged as it happens: your message before the model runs, the reply after. Each agent's turns are kept apart. Tool calls are stored by name and id with a one-line result, never their arguments. Turn logging can be switched off on the **Conversations** tab, which also lists each agent's stored turns.++### Learnings++A learning is one durable statement: a preference, fact, procedure or correction. The agent saves them with its `memory` tool (`learn` action), and you can add or delete them on the **Learnings** tab. Beliefs the engine built are listed there too, marked **Built belief**.++Everything is scrubbed for secrets and personal identifiers before it leaves your machine.++### Past conversations++Chats from before turn logging are not in memory until you sync them. The **Conversations** tab shows how many chats and turns are still unsynced; **Sync past conversations** uploads them (after you confirm) in the same form as new turns, without tool arguments. You can close the page while it runs, and syncing again later only sends what is new.++## Exploring what memory holds++The **Explorer** tab shows everything your memory holds, grouped by one property at a time: type, memory node, source, workspace, folder, file, language, repository, link, thread, agent, tool or tag. Each value shows how many items carry it. Click one to narrow to those items, then group again by another property; the breadcrumb at the top takes you back up. The items at each step are listed below, and **Open** shows one in full with all its details and a **Forget** button.++On a very large memory the counts may cover only the items scanned so far; the tab says so when that happens.++## Each agent's own memory++Memory is organised the way a team works:++* **Shared by every agent:** learnings and the brain.+* **Each agent's own:** its conversations. The pack an agent gets leads with its own history; other agents' turns appear only briefly.+* **Teams and tenants:** an agent team gets a memory of its own, below its own root (`team:<id>`), apart from everyone else's.++By default an agent's memory id is its definition id. In `config.toml`, `[memory.agents.<id>]` can give a definition another memory id (`agent_id`), another root (`root`), or switch its per-turn pack off (`recall = false`). A host that runs OpenHuman agents as part of something larger (an AI company, a multi-agent product) binds each agent to its own memory: `[memory] agent_id` and `root` on that agent's config, or `AgentSpec::memory(MemoryBinding::new("employee-7").root("team:acme"))` through the [embedding library](../developing/embedding.md).++## The agent's memory tool++The agent has one tool, `memory`, with four actions: `recall`, `fetch`, `learn` and `forget`. OpenHuman's own [MCP server](../developing/mcp-server.md) exposes the same abilities to other apps as `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn` and `memory.forget`.++## Settings and background work++The **Settings** tab sets the pack's shape: on or off, its size in tokens, how many learnings, documents and turns it holds, and how often beliefs are built. The **Background** tab lists queued belief builds and recent runs, with **Run now**. With the TinyHumans engine, beliefs are built on the service's own schedule.++## Importing your previous memory++If OpenHuman finds memory from the earlier (v1) version, the Memory page offers a one-time import. It uploads that data to the engine you selected, so it only starts after you explicitly consent. It resumes if interrupted.++## Removed++The memory tree, graph view, goals list, people and contacts, learning profile, `MEMORY.md` and `PROFILE.md`, the Obsidian vault, the local TinyCortex engine and the Supermemory, Mem0, Cognee and agentMemory engines are gone, as is engine migration. The compiled `context.md` brief is replaced by the per-turn memory pack. See the [spec](https://github.com/tinyhumansai/openhuman/blob/main/docs/specs/memory-v2.md).++## See also++* [Memory architecture](../developing/architecture/memory.md)+* [Pluggable engines](../developing/engines.md)+* [Privacy and security](privacy-and-security/)diff --git a/docs/gitbooks/docs/gitbooks/en/features/model-routing/README.md b/docs/gitbooks/docs/gitbooks/en/features/model-routing/README.mdnew file mode 100644index 0000000000..493b14d6e8--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/model-routing/README.md@@ -0,0 +1,101 @@+---+description: >-+ One subscription, many models. Tasks pick their model via hint prefixes:+ reasoning goes to a strong model, fast paths go to a fast one, vision to+ vision.+icon: route+---++# Automatic Model Routing++Different parts of an agent want different models. Long reasoning wants a frontier model. Quick "fix this typo" calls want a fast cheap one. Vision wants a vision model. OpenHuman handles this with a built-in **router provider** so you never have to think about it.++## How a request gets routed++The model parameter on any chat call can take one of two shapes:++* **Concrete model name**: for example `anthropic/claude-sonnet-4`. Routes to the default provider with that exact model.+* **Hint prefix**: for example `hint:reasoning`. Looks the hint up in the route table and resolves to a `(provider, model)` pair.++The rule is the whole of it: strip a `hint:` prefix, look the remainder up in the route table, and fall through to the default provider with the name unchanged if there is no entry. A name without the prefix is never rewritten.++The route table is `[[model_routes]]` in `config.toml`, one entry per hint (`ModelRouteConfig` in [`crates/openhuman-core/src/config/schema/routes.rs`](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/config/schema/routes.rs)), with `[[embedding_routes]]` doing the same for embeddings. Resolution and provider construction live in [`crates/openhuman-core/src/inference/`](../../../../../../../crates/openhuman-core/src/inference/) (see its [README](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/inference/README.md)). Hints can be remapped at runtime without restarting the core.++## Common hints++| Hint | Typical target | When it's used |+| ---------------- | --------------------------------- | ----------------------------------------------------- |+| `hint:reasoning` | A strong reasoning model | Multi-step planning, math, code-heavy turns |+| `hint:fast` | A fast/cheap model | UI helpers, autocompletes, small classification calls |+| `hint:vision` | A vision-capable model | Screenshots, image attachments, OCR |+| `hint:summarize` | A model good at compression | Background summarization |+| `hint:code` | A code-tuned model | Native coder turns |+| `hint:burst` | A high-throughput, low-cost model | Cheap, latency-tolerant work for high-fanout agents |++The exact mappings are configurable; the defaults ship sensible per-provider routes.++## One subscription, or your own++Routing happens behind a single OpenHuman subscription by default. You don't hold separate API keys for Anthropic, OpenAI, Google etc., the backend brokers access, and the router picks the right one per task. That's the "one subscription, many providers" promise from the README, made concrete.++The subscription is the default, not a requirement. The same router works against **your own provider key** or a **local model on a runtime you run yourself** (Ollama, LM Studio, MLX, or any OpenAI-compatible server), per workload, and you can mix all three. See [Local models & bring your own key](local-and-byok-models.md) for setup and for what each route supports for chat, vision, and embeddings.++## Overriding routes++* **Globally**: `[[model_routes]]` in `config.toml` supplies the route table at startup.+* **Per call**: pass a concrete model name with no `hint:` prefix and the router falls through to the default provider with that exact model.+* **For a skill**: a skill can pin a hint or a model in its manifest.+* **Per agent**: an agent definition can pin its own provider and model, which wins over the table.++## Default model++Settings → Connections → LLM → Routing has a **Default model** row: a model from the managed catalog that every managed chat turn runs on instead of the anonymous chat tier (it opens on DeepSeek V4 Flash). The composer's model pill can still override it for one conversation, and the specialised tiers (reasoning, coding, vision, summarisation) keep their own routing. The rows beneath it route each workload to Managed, a BYOK provider, a local runtime, or Claude Code.++## Per-agent model pins++Sub-agents can also pin an exact model without disabling automatic routing for the rest of the app. Use this when an orchestrator or team lead needs a stronger model, while high-volume leaf agents should stay on a cheaper one.++Inline calls win for one delegation:++```json+{+ "agent_id": "presentation_agent",+ "model": "anthropic/claude-sonnet-4",+ "prompt": "Build a five-slide deck from the Q3 report."+}+```++Persistent defaults live in `config.toml`:++```toml+[orchestrator]+model = "anthropic/claude-sonnet-4"++[teams.planner]+lead_model = "openai/gpt-5.1"+agent_model = "groq/llama-3.1-8b-instant"++[teams.image]+agent_model = "openai/gpt-5.1"+```++Resolution order:++1. Inline `model` on `spawn_subagent` or an archetype delegation call.+2. `[orchestrator].model`, or `[teams.<agent_id>]`, or the `_agent`-stripped alias (`[teams.image]` for `image_agent`).+3. The archetype's own model hint and the normal route table.++For `[teams.*]`, `lead_model` applies to agents that can delegate and `agent_model` applies to leaf workers. If only one is set, the harness falls back to it for both roles.++## Why this isn't just "model switcher"++Routing isn't a UI dropdown. The agent loop itself emits hints based on what it's about to do. You don't pick the model; the _task_ does. That's the difference between "multi-model" and "smart routing".++## See also++* [Smart Token Compression](../token-compression.md). what makes large reasoning calls affordable.+* [Native Tools](../native-tools/). different tool calls hint at different routes.+* [Local models & bring your own key](local-and-byok-models.md). run on your own key or fully on-device.+* [Local AI (optional)](local-ai.md). Add your own local runtime as a provider; lightweight chat hints can run on-device.+* [Pluggable engines](../../developing/engines.md). How the provider layers are chosen by config.+* [One TinyHumans API key](../../developing/tinyhumans-api-key.md). The single key behind managed routing.diff --git a/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-ai.md b/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-ai.mdnew file mode 100644index 0000000000..815b9b8826--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-ai.md@@ -0,0 +1,136 @@+---+description: >-+ Use a local model runtime you run yourself (Ollama, LM Studio, MLX, OMLX, or+ any OpenAI-compatible server) as an OpenHuman provider. OpenHuman does not+ install the runtime or download models.+icon: microchip+---++# Local AI (optional)++OpenHuman can send any workload to a model running on your own machine: chat, reasoning, agentic turns, coding, vision, and embeddings. Local AI is **opt-in** and **off** by default.++OpenHuman does not install, start, stop, or update a local runtime, and it does not download model weights. You:++1. install and run the runtime yourself (Ollama, LM Studio, MLX, OMLX, or another OpenAI-compatible server),+2. pull or load the models you want with that runtime's own tools (for example `ollama pull bge-m3`),+3. add the runtime's endpoint to OpenHuman as a provider and route workloads to it.++If a workload names a model the runtime does not have, the request fails with the runtime's error. Pull the model and retry; OpenHuman will not fetch it for you.++## Supported runtimes++Every local runtime is reached over its OpenAI-compatible HTTP API. The provider string prefix decides which runtime a workload uses (`crates/openhuman-core/src/inference/provider/factory/local_runtime.rs`):++| Runtime | Provider string | Default endpoint | Endpoint overrides (highest first) |+| -------------------------------- | ---------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------ |+| [Ollama](https://ollama.com) | `ollama:<model>` | `http://127.0.0.1:11434` | `local_ai.base_url`, then `OPENHUMAN_OLLAMA_BASE_URL`, then `OLLAMA_HOST`. OpenHuman appends `/v1` for chat. |+| [LM Studio](https://lmstudio.ai) | `lmstudio:<model>` | `http://localhost:1234/v1` | `OPENHUMAN_LM_STUDIO_BASE_URL`, then `LM_STUDIO_BASE_URL`, then `local_ai.base_url` |+| MLX (`mlx_lm.server`) | `mlx:<model>` | `http://127.0.0.1:8080/v1` | `OPENHUMAN_LOCAL_INFERENCE_URL`, then `MLX_SERVER_URL`, then `local_ai.base_url` |+| OMLX | `omlx:<model>` | `http://127.0.0.1:8000/v1` | `OPENHUMAN_LOCAL_INFERENCE_URL`, then `OMLX_SERVER_URL`, then `local_ai.base_url` |+| Any OpenAI-compatible server | `local-openai:<model>` | `http://127.0.0.1:8080/v1` | `OPENHUMAN_LOCAL_INFERENCE_URL`, then `LOCAL_OPENAI_URL`, then `local_ai.base_url` |++LM Studio, OMLX, and `local-openai` send `local_ai.api_key` as a Bearer token when one is set; Ollama and MLX send no auth. Local runtimes do not need an OpenHuman account.++The model part of the provider string is passed to the runtime unchanged, so it must match the runtime's own model id (for Ollama, the name you pulled, including the tag). An optional `@<temperature>` suffix pins a temperature, for example `ollama:qwen2.5:[email protected]`.++## Multiple self-hosted servers++If you run several OpenAI-compatible model servers, a gateway can expose one endpoint and use named model IDs to select the upstream. See [Use multiple local LLM servers](../../guides/guides/multiple-local-llm-servers.md) for an optional community Model Router example with a Mac mini and Linux GPU PC. OpenHuman does not bundle or supervise the gateway.++## Adding a local runtime in the app++1. Start the runtime and make sure its server is listening. For Ollama, `curl http://localhost:11434/api/tags` should return JSON.+2. Pull or load the models you plan to use (see [Use OpenHuman with a local model](../../guides/guides/local-model.md)).+3. Open **Connections → LLM**, choose **Add a provider**, and pick the runtime under **Local runtimes** (Ollama, LM Studio, OMLX). For MLX or another server, use **Add a custom provider** with its OpenAI-compatible endpoint.+4. Confirm or edit the endpoint. On save, OpenHuman writes `local_ai.base_url` and `local_ai.provider`, turns on `local_ai.runtime_enabled`, and lists the endpoint's models. If the runtime is not reachable, the provider is not saved.+5. Route workloads to it with **Custom routing**, choosing from the models the runtime reports.++The model list comes from the runtime. A model you have not pulled does not appear; pull it in the runtime and reopen the picker.++## Configuration++The same setup by hand, in `config.toml`:++```toml+[local_ai]+runtime_enabled = true # needed for the background local features below+provider = "ollama" # "ollama", "lm_studio", or "omlx"+base_url = "http://localhost:11434" # optional; omit to use the default+chat_model_id = "gemma3:4b-it-qat" # model used by local summary-tree building+embedding_model_id = "bge-m3"+vision_model_id = "gemma3:4b-it-qat" # leave empty for no local vision+```++Workload routing lives at the top level of `config.toml`; each field takes a provider string:++```toml+chat_provider = "ollama:gemma3:4b-it-qat"+reasoning_provider = "ollama:qwen2.5:14b"+embeddings_provider = "ollama:bge-m3"+```++The workload fields are `chat_provider`, `reasoning_provider`, `agentic_provider`, `coding_provider`, `vision_provider`, `memory_provider` and `embeddings_provider`. A field that is unset, blank, or `cloud` stays on the default route. For the background workloads, `Config::workload_local_model(...)` in `crates/openhuman-core/src/config/schema/types/resolvers.rs` treats a workload as local only when its field is `ollama:<model>`.++The legacy `local_ai.usage.*` booleans are kept only so older configs migrate. They do not override the workload fields.++## What the local runtime is used for++| Workload | Configured by | Notes |+| ------------------------------------ | --------------------------------------------- | ----------------------------------------------------------------------------- |+| **Chat, reasoning, coding, agentic** | `chat_provider`, `reasoning_provider`, ... | Any local prefix from the table above. |+| **Vision** | `vision_provider`, `local_ai.vision_model_id` | Must be a vision-capable model. See [Local vision](local-ai.md#local-vision). |++For lightweight chat hints (`hint:reaction`, `hint:classify`, `hint:format`, `hint:sentiment`, `hint:summarize`, `hint:medium`, `hint:tool_lite`), the [router](./) prefers the local provider when `local_ai.runtime_enabled = true` and it is reachable. Heavy hints (`hint:reasoning`, `hint:agentic`, `hint:coding`) stay on the default route unless the matching workload field points at a local provider.++## What stays in the cloud by default++| Workload | Why |+| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |+| **STT** | Backend-proxied transcription (`crates/openhuman-core/src/voice/cloud_transcribe.rs`) or a third-party key. There is no local STT engine. |+| **TTS** | Hosted [text-to-speech](../native-tools/voice.md) by default. Local Piper works if you install it yourself and set `PIPER_BIN`. |+| **Web search** | Backend proxy, or your own search provider key. |++Any workload you have not pointed at a local provider keeps using the default route.++### Local text-to-speech with Piper++Setting `local_ai.tts_provider = "piper"` runs [Piper](https://github.com/rhasspy/piper) for spoken replies. OpenHuman does not ship or install Piper or its voices: install the Piper binary and a voice model yourself and point the `PIPER_BIN` environment variable at the binary.++## Privacy++[Privacy Mode](../privacy-and-security/privacy-mode.md) set to `local_only` refuses every non-local chat provider at construction time and permits only the local prefixes above. It does not start a runtime or fetch models: with privacy mode on and no reachable local runtime, workloads fail rather than fall back to the cloud.++Without privacy mode, lightweight hints routed to a local provider that turns out to be unreachable fall back to the remote provider. Use privacy mode if strict locality matters.++The backend URL guard in `crates/openhuman-tinyhumans/src/backend/url.rs` keeps the two kinds of endpoint apart. If `api_url` is set to something that looks like a local model server (a loopback or private host on a common runner port such as 11434, 1234, 8000, or 8080, or a `/v1/chat/completions` path), backend requests ignore it and go to the hosted API. Configure local endpoints through a provider or `local_ai.base_url`, not `api_url`.++## Local vision++Vision is a separate capability from chat, and most small local models cannot do it. Ollama does not reject an image sent to a text-only model: it drops the image and answers from the prompt text, which produces a description of something the model never saw. OpenHuman resolves the vision model through a capability check and refuses to route a vision request at a known chat-only model.++* `vision_provider` and `local_ai.vision_model_id` must name a vision-capable model, and you must have pulled it. `moondream:1.8b-v2-q4_K_S` (about 1.7 GB) is a small option; `gemma3:4b-it-qat` handles chat and vision with one set of weights.+* Gemma 3 is text-only at 270M and 1B and multimodal from 4B up. Gemma 3n is a different model and is text-only at every size.+* Leaving `vision_model_id` empty is a valid "no local vision" setup.+* Attaching an image to a chat turn also needs the model's **vision** flag in the model registry. See [Local models & bring your own key](local-and-byok-models.md#attaching-images-in-chat-needs-one-more-flag).++## What you need++* The runtime installed and running. OpenHuman does not manage it.+* The models pulled or loaded in that runtime.+* Enough disk and RAM for the models you chose. As a rough guide, `bge-m3` is about 1.2 GB on disk and a 4B chat model about 4 GB; plan for 8 GB+ RAM, 16 GB+ for larger models.++### Troubleshooting++* **Provider will not save, or the model list is empty.** The runtime is not reachable at the endpoint. Start it and check the port. For Ollama, run `curl http://localhost:11434/api/tags`.+* **The runtime reports the model is missing.** The model is not pulled or loaded. Run `ollama pull <model>`, or load it in LM Studio, then retry.+* **LM Studio on a different port.** Set `local_ai.base_url` or `OPENHUMAN_LM_STUDIO_BASE_URL`. Load the model in LM Studio before OpenHuman calls it.+* **Ollama context too small for agent turns.** Set `local_ai.num_ctx` to send `options.num_ctx` with each Ollama chat request.++## See also++* [Use OpenHuman with a local model](../../guides/guides/local-model.md). Step-by-step setup.+* [Local models & bring your own key](local-and-byok-models.md). Per-model capability table and BYOK setup.+* [Memory](../memory.md). Memory is stored by its engine, not by a local model.+* [Automatic Model Routing](./). How lightweight chat hints prefer the local provider.+* [Privacy Mode](../privacy-and-security/privacy-mode.md). Enforcing local-only inference.diff --git a/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-and-byok-models.md b/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-and-byok-models.mdnew file mode 100644index 0000000000..d45bfb4c47--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/model-routing/local-and-byok-models.md@@ -0,0 +1,178 @@+---+description: >-+ Three ways to power OpenHuman: the managed subscription, your own provider key+ (BYOK), or fully local models on a runtime you run yourself. What each one+ supports for chat, vision, and embeddings, and+icon: sliders+---++# Local models & bring your own key++The OpenHuman subscription is the **default**, not a requirement. Inference can come from any of three places, and you can mix them per workload: run embeddings locally, chat on your own Anthropic key, and leave vision on the managed route, all at once.++This page covers how to set up the two self-owned options and, importantly, **what each one can actually do**. Not every local model can see images, and picking a chat-only model for vision work is the single most common way to end up with a setup that looks configured but quietly does the wrong thing.++## The three routes at a glance++| | **Managed (default)** | **BYOK cloud** | **Local (runtime you run)** |+| -------------------------------------- | ----------------------------- | ------------------------------------------- | ----------------------------------------- |+| **Chat & reasoning** | Included | Your key, your billing | Yes, quality scales with model size |+| **Vision** | Included | Your key, if the model supports images | Yes, but only with a vision-capable model |+| **Embeddings** | Included | Your key, if the provider serves embeddings | Yes, `bge-m3` recommended |+| **Speech to text** | Included | Your own key, via a voice provider slug | No local STT engine |+| **Text to speech** | Included | Your own key, via a voice provider slug | Piper, if you install it (`PIPER_BIN`) |+| **Web search** | Included, no key needed | Bring your own Exa key | Not applicable |+| **Inference data leaves your machine** | Yes, to the OpenHuman backend | Yes, to your chosen provider | No |+| **API keys to manage** | None | One per provider | None |++Speech is configured separately from the LLM workload fields, and the two halves are easy to confuse. `voice_providers` holds the third-party provider **definitions** (slug, endpoint, key, default model or voice); editing one does not change which provider is actually used. The **active route** is picked separately:++* STT reads `stt_provider`, falling back to the legacy `local_ai.stt_provider`, and finally to `voice_server.stt_engine` when neither names a provider.+* TTS reads `tts_provider`, falling back to the legacy `local_ai.tts_provider`, and finally to `cloud`.++There is no local STT engine: speech-to-text is either the hosted proxy or a third-party API you supply a key for, while TTS keeps a local option in Piper. OpenHuman does not install Piper: install the binary and a voice yourself, set `PIPER_BIN`, and set `tts_provider = "piper"`.++That last row is deliberately about **inference data only**. Sign-in, managed integration OAuth, billing, and hosted features such as media generation and managed web search still use the OpenHuman backend even when inference is entirely yours, so running local models is not by itself a guarantee that nothing leaves the machine. If you want a hard guarantee that no inference leaves the machine, use [Privacy Mode](../privacy-and-security/privacy-mode.md), which enforces the local-only path in the Rust core rather than relying on configuration alone.++## Route A: local models++OpenHuman does not install a runtime or download model weights. You run the runtime (Ollama, LM Studio, MLX, OMLX, or another OpenAI-compatible server), you pull the models, and OpenHuman calls the endpoint. The examples below use Ollama.++### 1. Install Ollama and pull a model++Install [Ollama](https://ollama.com), then pull what you need. Every model named on this page is pullable from the public Ollama library:++```bash+ollama pull gemma3:1b-it-qat # small chat model+ollama pull bge-m3 # embeddings+ollama pull moondream:1.8b-v2-q4_K_S # vision, small+```++### 2. Know what each model supports++This is the part that bites people. A model that only does text will still **accept** an image request on Ollama: it silently drops the image and answers from the prompt text alone, which reads as a confident but entirely invented description. OpenHuman guards against this by refusing to route a vision request at a chat-only model, but it is worth knowing which is which.++| Model | Size | Chat | Vision | Embeddings |+| -------------------------- | ------- | ------- | ------- | ----------------- |+| `gemma3:270m-it-qat` | 0.2 GB | Yes | No | No |+| `gemma3:1b-it-qat` | 1.0 GB | Yes | No | No |+| `gemma3:4b-it-qat` | 4.0 GB | Yes | **Yes** | No |+| `gemma3n:e4b-it-q8_0` | 9.5 GB | Yes | No | No |+| `gemma4:e4b-it-q8_0` | 11.6 GB | Yes | **Yes** | No |+| `moondream:1.8b-v2-q4_K_S` | 1.7 GB | Minimal | **Yes** | No |+| `llava:7b` | 4.7 GB | Minimal | **Yes** | No |+| `bge-m3` | 1.2 GB | No | No | **Yes**, 1024 dim |+| `all-minilm:latest` | 0.05 GB | No | No | 384 dim |++Two traps worth calling out:++* **Gemma 3 is split by size.** The 270M and 1B builds are text-only. Vision starts at 4B. Picking `gemma3:1b-it-qat` for vision gets you a text-only model.+* **`gemma3n` is not `gemma3`.** Despite the name, Gemma 3n is a separate, text-only model on Ollama. It is a fine chat model and a bad vision model.++For embeddings, prefer **`bge-m3`** (1024 dimensions). Note what that does and does not cover. An `embeddings_provider` of `ollama:bge-m3` routes OpenHuman's own embedding calls to your machine. It does not move memory: the engine embeds on its own side, so recall still runs wherever the engine runs. Those are three separate decisions, and no one switch covers all of them: this field routes OpenHuman's embeddings, [Privacy Mode](../privacy-and-security/privacy-mode.md) enforces where _inference_ may go, and the memory engine you choose decides where memory lives.++### 3. Point OpenHuman at it++In the desktop app, open **Connections → LLM → Add a provider** and pick Ollama (or LM Studio / OMLX) under **Local runtimes**, or add a custom OpenAI-compatible endpoint. OpenHuman saves the endpoint, enables the local runtime, and lists the models the runtime reports. Models you have not pulled do not appear. See [Local AI (optional)](local-ai.md#adding-a-local-runtime-in-the-app).++To configure by hand, the keys live under `[local_ai]` in `config.toml`:++```toml+[local_ai]+runtime_enabled = true+opt_in_confirmed = true+provider = "ollama" # or "lm_studio"+chat_model_id = "gemma3:4b-it-qat"+vision_model_id = "gemma3:4b-it-qat" # must be vision-capable+embedding_model_id = "bge-m3"+```++Every model you name here must already be pulled. Leaving `vision_model_id` empty means "no local vision", which is a valid setup.++### 4. Route workloads to it++Adding a local provider does not move everything on-device. You choose per workload with a provider string such as `ollama:<model>` (or `lmstudio:`, `mlx:`, `omlx:`, `local-openai:`):++```toml+chat_provider = "ollama:gemma3:4b-it-qat"+vision_provider = "ollama:gemma3:4b-it-qat"+embeddings_provider = "ollama:bge-m3"+```++The full set of workload fields is `chat_provider`, `reasoning_provider`, `agentic_provider`, `coding_provider`, `vision_provider`, `memory_provider`, `embeddings_provider`, and `learning_provider`. Any field left unset, blank, or set to `cloud` stays on the default route.++#### Attaching images in chat needs one more flag++`vision_provider` routes the **vision workload**: image summaries and the OCR/description path. It does not by itself let you attach an image to a chat or agent turn.++A turn only rehydrates image attachments when the resolved chat model is known to accept them, and for a local model that knowledge comes from the per-model registry, not from `vision_provider`. Set the model's **vision** flag in Settings → AI (the custom-model dialog), which records it in `model_registry`:++```toml+[[model_registry]]+id = "gemma3:4b-it-qat"+provider = "ollama"+vision = true+```++Without that flag the images are stripped before dispatch and the model answers from the text alone, fluently, and with no indication that it never saw the picture.++See [Local AI (optional)](local-ai.md) for endpoint overrides, the other runtimes, and troubleshooting.++## Route B: bring your own key++BYOK keeps the routing, memory, tools, and agent harness exactly as they are, and swaps out who serves the tokens. Your key, your account, your billing, no OpenHuman inference charges.++### 1. Add the provider++Add your key in the desktop app under the LLM settings, which stores it in the OS keyring rather than in plain config. OpenHuman ships presets for these slugs, so you do not need to supply an endpoint:++`openai`, `anthropic`, `google`, `openrouter`, `orcarouter`, `groq`, `mistral`, `deepseek`, `together`, `fireworks`, `cerebras`, `xai`, `moonshot`, `gmi`, `huggingface`, `nvidia`, `zai`, `minimax`, `stepfun`, `kilocode`, `deepinfra`, `novita`, `venice`, `vercel-ai-gateway`, `sumopod`, `modelscope`++Anything else that speaks the OpenAI-compatible API works too: register it with your own slug and endpoint, and it routes the same way.++On a headless core (`openhuman-core serve`) custom cloud providers are only built when a backend session or TinyHumans API key is present. If you run the core with no account, wire the endpoint as the `local-openai` runtime instead (`LOCAL_OPENAI_URL`, key in `local_ai.api_key`, workloads pinned to `local-openai:<model>`); see [Headless without a TinyHumans account](../cloud-deploy.md#headless-without-a-tinyhumans-account).++### 2. Route workloads to it++Provider strings follow `<slug>:<model>`, using the same workload fields as the local route:++```toml+chat_provider = "anthropic:claude-sonnet-4"+reasoning_provider = "openai:gpt-5.1"+coding_provider = "deepseek:deepseek-coder"+vision_provider = "openai:gpt-5.1"+```++To make one provider the default for everything that is not pinned, set `primary_cloud` to its slug. Every workload left on `cloud` then resolves to that provider instead of the OpenHuman backend.++### 3. Check the model supports the workload++BYOK inherits your provider's capabilities, not OpenHuman's. Before pinning `vision_provider`, confirm the model you named accepts image input, and before pinning `embeddings_provider`, confirm the provider serves an embeddings endpoint. Not every chat provider does.++## Mixing routes++The workload fields are independent, so a common privacy-conscious setup keeps recurring background work on-device and reserves a strong cloud model for the turns that need it:++```toml+# On-device: everything that runs constantly over personal data+embeddings_provider = "ollama:bge-m3"+memory_provider = "ollama:gemma3:1b-it-qat"+learning_provider = "ollama:gemma3:1b-it-qat"++# Your own key: the turns where quality matters+chat_provider = "anthropic:claude-sonnet-4"+reasoning_provider = "anthropic:claude-sonnet-4"+```++## Troubleshooting++**The model you want is not offered, or a request says the model is missing.** The runtime does not have it. Run `ollama pull <model>` (or load it in LM Studio), then retry. OpenHuman does not pull models.++**Vision answers look plausible but describe the wrong image.** You are almost certainly on a chat-only model. Check `vision_model_id` against the capability table above. Current builds refuse this routing and fall back to a vision-capable model, so this points at an older build or a provider outside the local path.++## See also++* [Local AI (optional)](local-ai.md). Supported runtimes, endpoints, and the opt-in flags.+* [Automatic Model Routing](./). How hints pick a model per task.+* [Privacy Mode](../privacy-and-security/privacy-mode.md). Enforcing local-only inference in the core.+* [Privacy & Security](../privacy-and-security/). What moves on-device when you opt in.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/README.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/README.mdnew file mode 100644index 0000000000..51a2c1172d--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/README.md@@ -0,0 +1,46 @@+---+description: >-+ The full toolset OpenHuman's agent has out of the box - research, code,+ control your machine, schedule jobs, talk back to you, and call into your+ connected services.+icon: toolbox+---++# Native Tools++OpenHuman's agent doesn't ship empty. Every model behind the agent has a curated set of tools available the moment you install - no plugin marketplace, no API keys to wire up, no MCP servers to register. The whole toolbelt is in the box.++This page is the index. Each subpage covers one family of tools.++## Why ship them natively++A plugin-only model means tools live in different processes, behind RPC, with their own auth and packaging stories. That's fine for open-ended extensibility, but for the **core** tools every agent needs (read a file, search the web, edit code, set a reminder, drive a browser), shipping them in-process means:++* Consistent error handling.+* Zero install friction.+* All output passes through [Smart Token Compression](../token-compression.md) for free.+* Predictable security boundary - filesystem tools respect workspace scoping, and network tools use the managed OpenHuman proxy by default unless you opt into a self-hosted path such as SearXNG.++## The toolbelt++| Family | What it covers |+| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |+| [Web Search](web-search.md) | Search the live web via the managed proxy (powered by Exa), backend-proxied Parallel, your own Exa/Brave/Querit/Tavily key, or self-hosted SearXNG. |+| [Web Scraper](web-scraper.md) | Pull clean text out of any URL - articles, docs, READMEs. |+| [Coder](coder.md) | Read/write/edit/patch files, glob, grep, git, lint, test. |+| [Documents](documents.md) | Write `.docx` and `.pptx`, and read PDF, Word, PowerPoint and Excel back in. |+| [Browser & Computer Control](browser-and-computer.md) | Open URLs, inspect DOM snapshots, click, type, move the mouse. |+| [Cron & Scheduling](cron.md) | Recurring jobs, one-off reminders, scheduled agent runs. |+| [Voice](voice.md) | Speech-to-text in, text-to-speech out, and a live voice agent you can interrupt. |+| [Memory Tools](memory-tools.md) | Recall, fetch, learn and forget through the single `memory` tool, over [memory](../memory.md). |+| [Third-party Integrations](../integrations/) | The agent's view of the [connected services](../integrations/). |+| [Agent Coordination](agent-coordination.md) | Spawn subagents, delegate to skills, plan, ask the user. |+| [System & Utilities](system-and-utilities.md) | Shell, node, SQL, current time, push notifications, LSP. |++## See also++* [Smart Token Compression](../token-compression.md) - what keeps tool output costs bounded.+* [Third-party Integrations](../integrations/) - the user-facing pitch and OAuth flow for the managed catalog.+* [Privacy & Security](../privacy-and-security/) - the boundary every tool runs inside.+* [Tools domain](https://github.com/tinyhumansai/openhuman/blob/main/crates/openhuman-core/src/tools/README.md) - the Rust module that registers these tools.+* [Agent harness](../../developing/architecture/agent-harness.md) - how tool calls run inside a turn.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/agent-coordination.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/agent-coordination.mdnew file mode 100644index 0000000000..3deb5bc5b8--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/agent-coordination.md@@ -0,0 +1,43 @@+---+description: Tools the agent uses to plan, delegate, and ask for help.+icon: sitemap+---++# Agent Coordination++Beyond doing the work, the agent has tools for _organising_ the work - planning multi-step jobs, delegating to specialists, spawning subagents, and pausing to ask the user when something is genuinely ambiguous.++## Tools in the family++| Tool | What it does |+| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |+| `todo` | Rewrite the session todo list across a long task; the chat shows it as a checklist that ticks off as work progresses. |+| `spawn_subagent` | Delegate to a reusable async specialist by default; creates a fresh worker only when incompatible or requested. |+| `spawn_async_subagent` | Lower-level reusable async delegation surface with the same durable session identity. |+| `steer_subagent` / `wait_subagent` | Message or collect a running worker by durable `subagent_session_id` or transient `task_id`. |+| `list_subagents` / `close_subagent` | Inspect reusable workers for the parent thread or explicitly retire one. |+| `spawn_worker_thread` | Explicit background work tracked as a separate worker thread. |+| `delegate` | Hand a task to a specialist (e.g. an archetype with different prompts/tools/permissions). |+| `spawn_parallel_agents` | Fan one task out to several specialists at once and merge what they return. |+| `use_skill` | Load an inline skill's playbook and tools (coding, web3, system, scheduling, docs, mcp) and call them directly. |+| `ask_user_clarification` | Pause and ask the user a precise question instead of guessing. |+| `plan_exit` | Exit a planning phase and start executing. |++`spawn_subagent` and archetype delegation calls accept an optional `model` field for a one-off exact model pin. If it is omitted, the harness uses config-level per-agent pins when present and otherwise falls back to the normal model-routing hints. Model, sandbox mode, parent thread, action root, and task key are part of reusable sub-agent compatibility, so materially different work gets a separate worker.++Reusable delegation returns both a transient `task_id` and a durable `subagent_session_id`. Prefer the durable id for cross-turn follow-ups. Pass `fresh: true` only when the user or task needs a clean worker; pass `blocking: true` only when the parent must wait inline for the child result.++## Why these are tools, not implicit behaviour++Long tasks fall apart when the agent tries to keep everything in one head. Splitting work via TODOs and subagents means:++- Each subagent keeps useful local context for the same logical job instead of being respawned every turn.+- The main thread keeps a high-level view of progress.+- Failures in one branch don't poison the rest.++Asking for clarification is a tool too, on purpose: it makes "I should ask the user" a _visible_ decision the agent can be steered toward, not an emergent behaviour.++## See also++- [Coder](coder.md) - the coding tools, most of them loaded through the `coding` skill.+- [Cron & Scheduling](cron.md) - how background agent runs get scheduled.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/browser-and-computer.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/browser-and-computer.mdnew file mode 100644index 0000000000..e6a5c356dc--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/browser-and-computer.md@@ -0,0 +1,103 @@+---+description: >-+ Read and drive a real browser and a real desktop: accessibility snapshots,+ element references, bounded tasks that stop at a payment page, and a small+ decision model picking each step.+icon: display+---++# Browser & Computer Control++When the agent needs to _use_ a machine the way a person would, open a page, read what is on screen, click a button, type a phrase, these tools are how it does it. Both surfaces come from one loadable module, **TinyComputer**, which serves desktop and browser control over a single interface and is downloaded on first use.++## Two surfaces, one model++Desktop and browser produce the same kind of "screen": a compact list of the things a person could interact with, each with a role, a name, a value, its states, the actions it supports, and the labels of the boxes it sits in, capped at 254 controls. Both offer the same short action list (click, type, check, uncheck, expand, collapse, scroll, wait, press), so the agent learns one vocabulary.++Elements are addressed by **reference**, never by coordinates or CSS selectors. A desktop reference like `@s8f3k2p9:e1` is bound to the snapshot that produced it: acting on it either reaches the element that was described, or fails with a stale-reference error telling the agent to look again. It never clicks whatever has since moved into that position. Browser references survive a redraw, because they are marks that last as long as the element is on the page.++## Browser++The browser is a real Chrome or Chromium, driven over the Chrome DevTools Protocol by a library linked into the module. Chrome is its own process, as it has to be, but nothing sits between it and the module: no driver binary, no local HTTP bridge, no second OpenHuman process.++- **Open** a session: launch a fresh browser (headless or headed), or **attach to the Chrome you already have running**. Attaching matters more than it sounds: plenty of sites turn away a fresh automated browser and serve a person's own. On task end an attached browser is only disconnected, never closed.+- **Snapshot** the page. The default perception mode, `sight`, runs a small in-page script that reads the page the way a person sees it: real links, buttons and fields, plus anything with a pointer cursor, a click handler or a tab stop. Hidden, zero-size, transparent and disabled things are dropped; things below the fold are marked offscreen and things behind a dialog are marked covered. It falls back to the accessibility tree when it cannot read a page, and `perception: "tree"` forces the tree.+- **Act**: click (optionally into a new tab), fill, type, press, select, check, hover, scroll, wait, read, go back.+- **Read** the page as text, Markdown or serialized DOM, and **evaluate** JavaScript.+- **Downloads**: list the browser's download events, and wait for a completed file. A page snapshot alone does not prove a file finished.++Screenshots are never returned inline. A reply carries a handle the agent reads in chunks and releases when done.++Sessions are bounded: the module allows up to 8 at once, and OpenHuman keeps at most 6 per conversation thread with a 30-minute idle timeout, so a long chat reuses one browser instead of opening a new one per turn. A session can be restricted to a set of origins.++## Desktop++Desktop control reads the operating system's **accessibility tree**, the same interface a screen reader uses: running apps, windows, displays, Notification Center entries, the clipboard, and screenshots.++Actions go through the accessibility API rather than synthesized input, so by default they do **not** steal focus, move your cursor or touch the pasteboard, and a run can proceed while you use the machine. A "headed" mode and real mouse and key events exist for apps that need them, and are the exception.++For dense apps, a skeleton snapshot caps the walk at three levels and returns structure without leaf detail, which is the difference between tens of thousands of tokens and a few hundred.++## Tasks++Above the primitives sits a bounded task loop. You describe the outcome; the module plans the steps and a small decision model ([Jev](../../developing/jev.md)) picks every click. A task starts and returns immediately with a status, which the agent polls and answers:++| Status | What it means |+| ----------------- | ----------------------------------------------------------------------- |+| `running` | Working. |+| `needs_input` | A field it cannot fill without you. |+| `needs_approval` | An irreversible step. Only an explicit approval releases it. |+| `needs_human` | A captcha, OTP, 2FA or login. No model can get past it. |+| `needs_plan` | Plain language with no planner configured. |+| `checkpoint` | Stopped on purpose, with the page left open. |+| `done` / `failed` / `cancelled` | Terminal. |++Two properties are worth stating plainly:++- **Reaching a payment page always stops the task.** It becomes a checkpoint that cannot be continued, with the page left open for a person. The agent does not pay.+- **Secret values never reach a model.** Facts you mark secret are shared as `${name}` templates; the planner, the decision model and the rescue model see the name, and the value is typed locally into the field.++Page and screen text is treated as data, never as instructions, and the safety rules are plain code rather than model judgement.++## Agent tools++| Tool | What it does |+| --- | --- |+| `browser` | Everything above on one `action` argument: `open`, `snapshot`, `read_page`, `click`, `fill`, `type`, `get_text`, `get_title`, `get_url`, `wait`, `press`, `hover`, `scroll`, `is_visible`, `find`, `task`, `task_continue`, `task_cancel`, `confirm_pending`, `list_downloads`, `wait_download`, `close`. |+| `browser_open` | Open a URL and get a session back. |+| `desktop_list_apps`, `desktop_list_windows` | What is running and where. |+| `desktop_launch` | Start an app. |+| `desktop_snapshot`, `desktop_find` | Read the screen, or look for one thing on it. |+| `desktop_goal`, `desktop_continue_goal` | Run a desktop task and answer its stops. |++Irreversible steps go through OpenHuman's [Approval Gate](../approval-gate.md), bound to a digest of the exact action and URL. If no approval gate is installed, the action is **denied**, not allowed.++## Platform support++| Platform | Desktop | Browser |+| --- | --- | --- |+| macOS | Yes. Needs **Accessibility** permission, plus **Screen Recording** for screenshots and **Automation** for the Notification Center opener. | Yes |+| Windows | Yes | Yes |+| Linux | No | No |++A permission check runs before the first read, because an accessibility API called by an unauthorized process usually returns an *empty tree* rather than an error, which is indistinguishable from an app with no buttons. A missing permission produces a named refusal that says which setting to change.++Linux is not in the shipped surface: the module registry publishes no Linux artifact, so neither desktop control nor browser automation is available there even though the browser engine itself would run.++## Settings++**Connections → Computer Control** holds all of it: the module's status and contract version, the decision model (Jev, OpenJEV or Levanto Sage) and which route it bills through, the planner and rescue models, and the browser section (executable path, perception mode, allowed domains).++`[desktop] approvals_enabled` defaults to `false`, and it governs one narrow thing: the module's own mid-goal confirmation stop on the **desktop** surface, which the core then auto-continues after the module re-observes and re-validates the exact target. Setting it `true` surfaces that stop as an approval card instead. It does not weaken the [Approval Gate](../approval-gate.md): an irreversible step still needs an approval, and with no gate installed it is denied. Desktop goal confirmations are single-use and expire after 10 minutes.++## What it's good for++- Driving sites that have no API and no [native integration](../integrations/README.md).+- Multi-step UI flows where each snapshot tells you the next actionable element.+- Automating a local app from inside a chat.++## See also++- [Web Scraper](web-scraper.md): when you only need the article, not the whole page.+- [Jev](../../developing/jev.md): the decision model that picks each step.+- [Approval Gate](../approval-gate.md): what gets parked, and what happens with no gate installed.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/coder.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/coder.mdnew file mode 100644index 0000000000..e90e661356--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/coder.md@@ -0,0 +1,43 @@+---+description: A complete toolset for working on real codebases - read, write, edit, search, git, lint, test.+icon: code+---++# Coder++The coder family is what makes OpenHuman a viable coding partner instead of a chat window that _pretends_ to know the codebase.++## Tools in the family++| Tool | What it does |+| ---------------- | ----------------------------------------------------------------- |+| `file_read` | Read a file (with line numbers, like `cat -n`). |+| `file_write` | Write a new file. |+| `edit` | Targeted edits - match-and-replace with strict uniqueness checks. |+| `apply_patch` | Apply a unified diff. |+| `glob` | Find files by glob pattern. |+| `grep` | Ripgrep-style search across the tree. |+| `list` | Walk a directory tree. |+| `read_diff` | Diff between two files or revisions. |+| `git_operations` | Status, diff, log, blame, branch, commit. |+| `run_linter` | Run the project's linter. |+| `run_tests` | Run the project's test command. |+| `csv_export` | Export query results as CSV. |++## Why these are native, not shell-only++A shell tool plus `cat`/`sed`/`awk` could _technically_ do all of this. The native tools exist because:++- Edits go through a uniqueness check, so the agent can't accidentally clobber the wrong line.+- Reads come back with line numbers the agent can refer to in follow-ups.+- Git operations parse output into structured data, instead of leaving the agent to scrape porcelain.+- Lint and test runs are wired to the project's actual commands, not generic guesses.++## Workspace scoping++Filesystem tools act inside the agent's **working folder** (`action_dir`), not the workspace directory, which holds internal state and is never a tool target. With the autonomy policy on, `workspace_only` confines them to that folder and anything outside it needs an explicit trusted root. With the policy off (the default) that confinement is not enforced, and the thing that still holds either way is the hard floor: credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and system roots are unreachable, as are `..` traversal and null bytes in a path. See [Approval Gate](../approval-gate.md).++## See also++- [System & Utilities](system-and-utilities.md) - `shell`, `node_exec`, `npm_exec`, `python_exec` for the rest of the dev loop.+- [Agent Coordination](agent-coordination.md) - `todo_write`, `spawn_subagent` for larger refactors.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/cron.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/cron.mdnew file mode 100644index 0000000000..fd3a7b41c7--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/cron.md@@ -0,0 +1,39 @@+---+description: Recurring jobs, one-off reminders, and scheduled agent runs - first-class.+icon: clock+---++# Cron & Scheduling++Scheduling is a first-class capability, not a workaround. The agent can set up recurring jobs ("every weekday at 9am, summarise my inbox"), one-off reminders ("nudge me about this in three hours"), and arbitrary agent runs on a cron schedule.++## Tools in the family++| Tool | What it does |+| ------------- | ------------------------------------------------------------------ |+| `cron_add` | Create a new scheduled job - cron expression + agent prompt. |+| `cron_list` | List existing jobs and their next-run times. |+| `cron_update` | Edit an existing job - change schedule, prompt, or enabled state. |+| `cron_remove` | Delete a job. |+| `cron_run` | Run a job once, immediately, regardless of its schedule. |+| `cron_runs` | Inspect the recent run history - when, how long, what it produced. |++There's also a one-shot `schedule` tool in [System & Utilities](system-and-utilities.md) for "do this once at time T" cases that don't need a recurring entry.++Agent jobs run a full model turn every time they fire, so they must be scheduled at least five minutes apart. `cron_add` and `cron_update` reject a tighter cron expression or `every_ms` for an agent job and say which two runs would be too close (`*/7 * * * *`, for instance, fires at :56 and again at :00). Shell jobs have no such floor.++## What it's good for++- Daily / weekly digests delivered to your messaging channel of choice.+- Polling a slow integration that doesn't push events.+- Reminders the agent itself owns ("remind me Thursday to follow up with Alice").+- Recurring research - "every Monday, check what's new on this topic and write me a brief".++## How it ties back to the rest++Every cron run is just a normal agent invocation, so it can use any other tool - search the web, query [memory](../memory.md), call a [third-party integration](../integrations/README.md), send a message. Run history is recorded so you can see what each tick produced.++## See also++- [System & Utilities](system-and-utilities.md) - the one-shot `schedule` tool.+- [Agent Coordination](agent-coordination.md) - for jobs that fan out into subagents.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/documents.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/documents.mdnew file mode 100644index 0000000000..1b14f613a7--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/documents.md@@ -0,0 +1,64 @@+---+description: >-+ Write .docx and .pptx files, and read PDF, Word, PowerPoint and Excel back+ in, with every limit stated up front.+icon: file-lines+---++# Documents++Two tools write files a person can open, and the ingest path reads the common office formats back in. Both run in a loadable module rather than in the app binary, which is why the writers' dependencies are in no OpenHuman build.++## Writing++| Tool | Produces |+| --- | --- |+| `generate_document` | A `.docx` from a structured spec: title, author, headings, paragraphs, bullet lists. |+| `generate_presentation` | A `.pptx` from slides: titles, bullets, images. |++The spec is validated before anything is written, and the limits are part of the contract rather than advice:++| `.docx` | Limit |+| --- | --- |+| Sections | 128 |+| Paragraphs per section | 200 |+| Bullets per section | 200 |+| Characters per title, author or heading | 2,000 |+| Characters per paragraph | 20,000 |+| Characters in total | 2,000,000 |++| `.pptx` | Limit |+| --- | --- |+| Slides | 64 |+| Bullets per slide | 32 |+| Characters per text field | 2,000 |+| Images per slide | 6 |+| Images per deck | 8 |+| Bytes per image | 5 MiB |++The aggregate character cap is the load-bearing one: sections times paragraphs times characters per paragraph would otherwise allow a spec that no reader could open.++The finished file arrives as an [artifact](../chat.md), so it shows up in the thread's files panel with download and reveal-in-folder.++## Reading++Attach a file, or point a [memory source](../memory.md) at one, and the ingest path extracts text with per-section provenance (a page number for a PDF, the part path for an Office file):++| Format | Notes |+| --- | --- |+| PDF | Up to 4,096 source pages. A page with no text layer is kept and flagged as a scan candidate, which is a suggestion for vision, not a claim that OCR is needed. |+| DOCX, PPTX, XLSX | Slide and sheet order comes from the file's own relationship manifest, so an unreferenced slide is excluded rather than guessed at by filename. Spreadsheets read shared and inline strings and use cached cell values; formulas are never evaluated. |++Bounds: 64 MiB in, 256 result sections, 200,000 bytes of text out, and the result says whether it was truncated. Text is never cut mid-character. Rendering PDF pages to images is opt-in per page, at most 8 pages per call and 2,048 pixels on the longest edge.++Nothing is written to disk during extraction, no office application is launched, and there is no network OCR.++## Where it runs++Document work happens in the `tinydocs` module: a signed native library downloaded on first use and verified against a SHA-256 pinned in the compiled registry. The consequence worth knowing is that the document writers and the PDF reader are **not** in OpenHuman's dependency graph in any build configuration, and with the `documents` feature off the two tools are simply absent from the agent's list rather than present and failing, while a PDF attachment degrades to a file reference instead of extracted text.++## See also++- [Image & Video Generation](media-generation.md): the other thing that produces a file.+- [Memory](../memory.md): where a read document ends up if you add it as a source.+- [Loadable modules](../../developing/loadable-modules.md): how a module is pinned and loaded.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/image-tools.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/image-tools.mdnew file mode 100644index 0000000000..94ee165e1f--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/image-tools.md@@ -0,0 +1,43 @@+---+description: >-+ The reading side of images: attachments the model can see natively, local+ image metadata, and which model handles vision.+icon: image+---++# Image Tools++Generating images is [Image & Video Generation](media-generation.md). This page is the other direction: getting an image *into* a turn so the model can look at it.++## Attaching an image++Attach a file in the composer, or point the agent at a path. What happens next depends on the model and the route, not on a setting:++- If the model's facts say it accepts that modality **and** the transport supports it, the image goes up natively as image content.+- If not, it degrades rather than failing: a bounded readout, or a reference to the file with its path and metadata, so the agent can still reason about it and tell you what it cannot see.++Uploads are preserved in the acting workspace across a restart, and the ordered references survive in the transcript, so a later turn can still refer to "the second screenshot".++## `image_info`++One tool, read-only: it reads a local image's metadata (format, dimensions, size) and can return its bytes as base64 text for a model that wants them inline. It is the tool to reach for when the question is "what *is* this file", and it does not need a vision model.++## Which model sees it++Vision is a workload with its own provider slot, so you can route it independently of chat:++```toml+vision_provider = "…" # a provider id, or leave unset to use the chat provider+```++If a configured vision model turns out to be chat-only, the call returns a named error rather than silently substituting another model. There is deliberately no default local vision model: a local setup has to name one. [Local models and BYOK](../model-routing/local-and-byok-models.md) lists the ones worth trying.++## Delegation++A turn that needs to look at several images, or to work through one carefully, is usually handed to the built-in vision sub-agent rather than done inline, so the main conversation does not carry every pixel of context. Delegation happens on the agent's own judgement; you do not have to ask for it.++## See also++- [Image & Video Generation](media-generation.md): making images and video rather than reading them.+- [Chat](../chat.md): where attachments live in the UI.+- [Automatic Model Routing](../model-routing/README.md): how the vision slot is resolved.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/integrations.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/integrations.mdnew file mode 100644index 0000000000..8bece0a361--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/integrations.md@@ -0,0 +1,35 @@+---+description: The agent's view of the connected third-party services.+icon: plug+---++# Third-party Integrations++OpenHuman's agent can call into [the connected third-party services](../integrations/), Gmail, Notion, GitHub, Slack, Lark/Feishu, Stripe, Calendar and the long tail, through a single proxied tool surface.++## How it shows up to the agent++Once you've connected a service via OAuth, its actions become callable tools. The agent doesn't need to know whether a tool talks to Gmail or to a local file - it just calls the tool, the proxy routes the request through the OpenHuman backend with your token, and the result comes back like any other tool output.++A few examples of what becomes available:++* "Send a message to #engineering on Slack."+* "Create an issue in the openhuman repo."+* "What's on my calendar tomorrow?"+* "Pull the last 20 Stripe charges over $1000."++## Native vs proxied++Some services have **native providers** - Rust modules that know how to ingest the service into [memory](../memory.md) directly (e.g. Gmail's native ingest path). Others are exposed as **proxied tools** only: the agent can call them, but there's no automatic ingest yet. New native providers are added as features land.++Lark / Feishu currently has two surfaces: a native real-time channel for message send/receive, and a Composio-proxied workspace toolkit entry for chat, docs, wiki, and meeting actions when the backend allowlist exposes it. Historical chat/doc backfill into memory is not yet a native provider; track that separately from the live channel connector.++## Privacy boundary++For Composio-proxied integrations, OpenHuman's core never calls any third-party API directly. Requests go through the OpenHuman backend, which handles OAuth tokens and rate limiting. Your tokens never sit on disk in plaintext on your machine, and the agent only sees the _results_ of tool calls, not the credentials. Native channels such as Lark / Feishu use their own local configuration and should be reviewed separately from the Composio OAuth boundary.++## See also++* [Third-party Integrations (catalog)](../integrations/) - the user-facing pitch, OAuth flow, and connection management.+* [Memory](../memory.md) - how connected services become memory sources (Composio kind).+* [Privacy & Security](../privacy-and-security/) - the full boundary.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/media-generation.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/media-generation.mdnew file mode 100644index 0000000000..6485228802--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/media-generation.md@@ -0,0 +1,33 @@+---+description: >-+ Ask for an image or a video and dedicated media agents generate it: image+ generation and editing (Seedream / SeedEdit), plus text-to-video and+ animate-a-reference-image (Seedance / Veo), saved straigh+icon: clapperboard+---++# Image & Video Generation++OpenHuman can _make_ media, not just read it. Ask the assistant to "generate an image of…", "edit this screenshot to…", or "animate this photo into a short clip" and a dedicated media sub-agent takes over. No plugin, no API key, no separate billing.++## What it can do++* **Image generation & editing.** Text-to-image and image editing through hosted GMI models (**Seedream** for generation, **SeedEdit** for edits).+* **Video generation.** Text-to-video, or animate a reference image into a clip (**Seedance** / **Veo**). Video is asynchronous: the agent kicks off the render and collects the clip when it's done.+* **Model discovery.** The agent can list the currently available media models and pick the right one for the job.++## How it works++The `media_generation` domain (`crates/openhuman-core/src/media/generation/`) exposes three agent tools (generate image, generate video, list models) backed by the OpenHuman backend's media-generation provider. The backend owns the provider keys, billing, and rate limiting; your subscription covers it like any other model call.++The tools submit the job and then poll on a 4-second cadence (up to 180 s for images, 420 s for video), so the agent, and you, get live progress instead of a hung call. Finished artifacts are downloaded into the agent's `generated-media/` folder in your workspace and returned as local file paths, ready to attach, post, or edit further.++## Privacy++Prompts and reference media for these tools are sent to the OpenHuman backend and on to the hosted media provider. This is disclosed in the in-app capability catalog (`intelligence.image_generation` / `intelligence.video_generation`, both Beta). Note that [Privacy Mode](../privacy-and-security/privacy-mode.md)'s local-only enforcement currently covers **inference providers only**. The media tools still call the backend, so avoid using them if you need strict no-egress today. Extending enforcement to integrations and network tools is a planned later slice.++## See also++* [Image Tools](image-tools.md) covers the reading side: attachments, image metadata, and the vision model slot.+* [Available Tools](./) lists the full native toolbelt.+* [Billing, Cost & Usage](../billing-and-usage.md) explains how media jobs are metered.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/memory-tools.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/memory-tools.mdnew file mode 100644index 0000000000..137a1ebf79--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/memory-tools.md@@ -0,0 +1,27 @@+---+description: How the agent recalls, fetches, learns and forgets with its single memory tool.+icon: brain+---++# Memory Tools++[Memory](../memory.md) is OpenHuman's knowledge base. The agent talks to it through one tool, `memory`, whose `action` is one of:++| Action | What it does |+| --- | --- |+| `recall` | Ask a question; returns an answer and the citations it rests on. |+| `fetch` | Raw search (hybrid) over stored items, optionally filtered by metadata. Returns hits. |+| `learn` | Save one durable learning (a preference, fact, procedure or correction). |+| `forget` | Remove items by id. |++The tool is only registered when a memory engine is usable. With none selected, memory is off and the agent never sees it. Each learning is shared with every agent under the same memory root and tagged with the workspace, thread, agent and tool call that produced it.++## The tool and the per-turn pack++Every turn already arrives with a small [memory pack](../memory.md#how-the-agent-uses-memory) (`<memory-context>`): the learnings, documents and history most relevant to what you just said. The tool is for going further than the pack: asking a question the pack does not cover ("what do I know about the Stripe webhook?"), searching with metadata filters, or saving something worth remembering next time.++External MCP clients get the same abilities from OpenHuman's [MCP server](../../developing/mcp-server.md) as `memory.recall`, `memory.fetch`, `memory.list`, `memory.learn` and `memory.forget`.++## See also++- [Memory](../memory.md)diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/system-and-utilities.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/system-and-utilities.mdnew file mode 100644index 0000000000..a50b7926dd--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/system-and-utilities.md@@ -0,0 +1,36 @@+---+description: Shell, node, SQL, current time, push notifications - the small tools that round out the toolbelt.+icon: gear+---++# System & Utilities++The catch-all family. Small, sharp tools the agent reaches for to round out a task.++## Tools in the family++| Tool | What it does |+| ------------------- | --------------------------------------------------------------------------- |+| `shell` | Run a shell command. Bounded output, captured exit code. |+| `node_exec` | Run a Node.js snippet - useful for one-off scripting. |+| `npm_exec` | Run an `npm`/`pnpm`/`yarn` script. |+| `python_exec` | Run a Python 3 snippet or `.py` script - one-off scripting in Python. |+| `current_time` | Get the current time in any timezone, with formatting options. |+| `schedule` | One-shot "do this once at time T" - for recurring jobs see [Cron](cron.md). |+| `pushover` | Send a push notification to your devices. |+| `lsp` | Query a language server (definitions, references, diagnostics). |+| `read_workspace_state` | Inspect the current working folder: open files, recent edits, environment. |+| `proxy_config` | Read or change proxy configuration for outbound requests. |+| `tool_stats` | Self-reflection - what tools have been used in this session and how often. |++## What it's good for++- The bits of a workflow that don't fit a richer tool family.+- "Just run this command and tell me what it printed."+- Time-aware behaviour ("what time is it for the user right now?") without baking timezone assumptions into prompts.+- Letting the agent _notify you_ when it's done with a long-running job.++## See also++- [Coder](coder.md) - for filesystem-heavy work, prefer the dedicated tools over `shell`.+- [Cron & Scheduling](cron.md) - for anything recurring.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/voice.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/voice.mdnew file mode 100644index 0000000000..c9e73c2334--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/voice.md@@ -0,0 +1,57 @@+---+description: >-+ Native voice: speech-to-text in, text-to-speech out, mascot lip-sync, and a+ live voice agent you can interrupt mid-sentence.+icon: microphone+---++# Voice++OpenHuman is voice-first when you want it to be. Dictation, reply speech and the live voice agent are part of the core, not a third-party plugin.++## Speech-to-text++* **Hotkey** - push-to-talk and toggle modes.+* **Audio capture** - cross-platform mic capture with voice-activity detection.+* **Streaming transcription** - words appear as you speak.+* **Hallucination filter** - strips well-known artefacts ("Thanks for watching", silence-induced phrases).+* **Postprocess** - punctuation, capitalisation, dictation cleanup.++Dictation can replace the active text input on your desktop, or be sent straight into a chat with the agent.++## Text-to-speech++Reply speech routes through a hosted TTS model. The agent's responses can be spoken back in a voice you pick, with natural timing and prosody. Voice selection is configurable per user, and the mascot avatar lip-syncs to the audio stream via a viseme map.++## Talk to Tiny live++Click Tiny, the mascot in the chat composer, and just talk. Tiny listens and answers out loud in real time, and you can cut in mid-sentence. It uses the same tools as typed chat, under the same tool policy, and anything that needs your approval asks in the conversation. What you both say is saved to the conversation you have open, and Tiny knows what you were just typing about.++Choose how Tiny's voice runs under **Connections → Voice agents**:++| Provider | Setup | Notes |+| ----------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |+| Gemini Live (TinyHumans) | None (default) | One model that hears and speaks. Billed through your TinyHumans balance. |+| ElevenLabs Agent (TinyHumans) | None | Hosted ElevenLabs voice with OpenHuman as its brain. |+| Gemini Live (Google API key) | Your Google AI Studio key | Talks to Google directly. |+| Sarvam AI | Your Sarvam key | Indian languages (Hindi, Tamil, Bengali and more, or automatic detection). Sarvam's speech recognition, chat model and voices work together. |++Each card has a **Test** button that opens a short session to check the provider. You can also pick the voice, and the language where the provider supports it.++## Privacy++* Audio capture is local. Where the audio goes next depends on the provider you picked: the managed routes send it to the OpenHuman backend, and a bring-your-own-key provider such as Gemini Live on a Google API key talks to that vendor directly. Either way no recording is retained beyond the live transcript.+* TTS audio is streamed and discarded: nothing stored.+* What you and the agent say in a live session is saved to the open conversation, and so reaches your memory engine on the same terms as typed chat, when memory is on.++There is no local speech-to-text engine. The bundled whisper build was removed; STT is either the hosted route or a third-party API you bring a key for. Text-to-speech still has a local option (Piper).++## Removed++The **live Google Meet agent** is gone. It joined a call through the old embedded Chromium webview, transcribed it into memory and spoke back as an outbound camera stream. The frontend surface, the `agent_meetings` domain and the join path were all removed; nothing in the shipped build joins a meeting. The second mascot and its per-mascot voice (the "meeting duo") survive as [mascot](../mascot.md) settings.++## See also++* [The Mascot](../mascot.md): the face that lip-syncs to this audio.+* [Memory](../memory.md): where a spoken conversation ends up.+* [Automatic Model Routing](../model-routing/): live turns want `hint:fast`.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-scraper.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-scraper.mdnew file mode 100644index 0000000000..3d6c693cd0--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-scraper.md@@ -0,0 +1,78 @@+---+description: >-+ The `web_fetch` tool: a single-purpose GET-and-read primitive that returns a+ page as Markdown rather than raw HTML, behind an allowlist and an SSRF guard.+icon: globe+---++# Web Scraper++`web_fetch` is the agent's GET-and-read primitive, deliberately separate from `http_request` and `curl`. It exists because the agent rarely wants the markup: it wants the page. HTML comes back converted to Markdown, with links kept and scripts dropped.++Reach for `http_request` instead when you need POST, custom headers or richer HTTP semantics, and for `curl` when the point is to stream a file to disk.++***++## Arguments++| Argument | Required | Effect |+| --------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `url` | Yes | An absolute `http` or `https` URL. |+| `max_bytes` | No | Truncate the body at this many bytes instead of the configured cap. |+| `raw` | No | Skip the Markdown conversion and return the body as served. It is not a way around the limits: the response cap and any `max_bytes` still truncate, and the result still carries the truncation marker. |+| `summary_focus` | No | An OpenHuman addition that steers the [TokenJuice](../token-compression.md) summary toward a topic. |++The tool is read-only and never prompts for approval. Parallel `web_fetch` calls are safe, since a GET is idempotent.++Conversion is driven by the response `Content-Type`, falling back to content sniffing when the header is absent. A response that is explicitly not HTML is returned verbatim.++***++## Limits++| Limit | Value | Where it comes from |+| -------------------------------------- | ----------------- | ----------------------------------------- |+| Body cap | 1,000,000 bytes | `[http_request].max_response_size` |+| Request timeout | 30 seconds | `[http_request].timeout_secs` |+| Text handed to the model in one result | 24,000 characters | `max_result_size_chars` in `web_fetch.rs` |+| Redirects followed | None | `redirect::Policy::none()` |++The first two are the shipped defaults in `crates/openhuman-core/src/config/schema/tools/http.rs` and are shared with `http_request`. A `0` in either key is treated as unset and falls back to the default, so a stale zero cannot disable every fetch.++Two behaviours are worth knowing:++* **Oversize pages are truncated, not dropped.** The body is cut at a character boundary, never mid-character, and the result header records `download_capped_at=<N>B` so the agent knows it is looking at a partial page. The cap bounds what reaches the model rather than what is downloaded, since the response is read before it is trimmed. Streaming with a hard download ceiling is `curl`'s job, not this tool's.+* **Past 24,000 characters the remainder is not discarded.** The full extracted page is spilled to an artifact and the result carries the `file_read` call that pages through it.++**Redirects are never followed.** A redirect target can sit on a host the allowlist would refuse, so a 3xx returns as a result naming its `Location` and leaves the decision to the agent. Re-calling `web_fetch` with that URL runs the whole guard again from scratch rather than inheriting the first call's approval.++***++## The allowlist and the URL guard++Every fetch passes `tinytools-std`'s URL guard (`vendor/tinyagents/vendor/tinytools/crates/tinytools-std/src/url_guard/`) before any connection is made. It is the same gate `http_request` and `curl` use.++**Shape.** Only `http` and `https` are accepted. URLs carrying whitespace, a backslash, userinfo (`user:pass@`), a percent-encoded authority, or an IPv6 literal host are rejected outright.++**Allowed websites.** `[http_request].allowed_domains` ships as `["*"]`, so research works out of the box. An exact host also matches its subdomains, `"*"` allows all public sites, and an empty list blocks all web access. If every entry is malformed the list fails closed rather than open. Narrow it from the allowed-websites setting described in [Web Search](web-search.md#settings), which writes the same key.++**Address checks.** The guard resolves the hostname and refuses the fetch if any resolved address is non-global: loopback, RFC1918 private, link-local (which covers the cloud metadata address `169.254.169.254`), CGNAT, the unspecified and broadcast ranges, and the IPv6 equivalents including unique-local, link-local and IPv4-mapped forms. Hostnames such as `localhost`, anything ending in `.localhost`, and anything under a `.local` TLD are refused by name. These checks apply even under `"*"`, so the wildcard opens public hosts and never the private network.++Under privacy mode's local-only setting the fetch is refused before validation or DNS, so a blocked destination is never even looked up. Rate limiting applies, and the egress disclosure spine records the destination host before the request leaves.++***++## What it's good for++* Reading articles, documentation pages and GitHub READMEs without the surrounding noise.+* Following up on a [Web Search](web-search.md) result.+* Summarising a single known page on demand.++***++## See also++* [Web Search](web-search.md): finds the URLs to feed this tool, and owns the allowed-websites list.+* [Smart Token Compression](../token-compression.md): what trims a long page before it reaches the model.+* [Browser & Computer Control](browser-and-computer.md): for pages that need clicking rather than reading.+* [Privacy & Security](../privacy-and-security/): the local-only mode and egress disclosure behind the guard.diff --git a/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-search.md b/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-search.mdnew file mode 100644index 0000000000..fa9ee981ed--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/native-tools/web-search.md@@ -0,0 +1,131 @@+---+description: >-+ Native web search, grounded answers and page reading for the agent. Exa and+ Gemini are included with TinyHumans; more providers work with your own key.+icon: magnifying-glass+---++# Web Search++The agent can search the live web, get a grounded answer with citations, and read pages on its own. Out of the box this runs on providers **included with TinyHumans**: [Exa](https://exa.ai) for search and page contents, and [Gemini](https://ai.google.dev) with Google Search grounding for answers. You don't need a search API key for either. You can add more providers with your own key, and several providers can be on at the same time.++## What it's good for++- Research: "what's the latest on X".+- Citation hunting: "find me three sources for Y".+- Fact-checking before answering: the agent runs a quick search if it isn't confident.+- Reading a page the agent or you already found.++## Roles: one tool per job++The agent sees one tool per **capability role**, whichever providers are on:++| Role | Agent tool | What it returns |+| ------------ | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Search** | `web_search_tool` | Ranked results: title, URL, publish date and an excerpt. |+| **Answer** | `web_answer_tool` | A written answer grounded in web sources, with citations. With `depth: "deep"` it runs Gemini Deep Research instead, which needs your own Gemini key. |+| **Contents** | `web_contents_tool` | The extracted text of the URLs it is given. |++Each role has an ordered provider list. The first **usable** provider serves the call; if it fails, the next one is tried, and so on. The result says which provider answered and which were skipped, for example `Answer for: … (via Gemini, after Exa)`, and the chat card shows the same "via Gemini, after Exa" note under the answer and its sources. A role with no usable provider has no tool at all, so the agent never sees a tool that can't run.++The default order is:++| Role | Default providers, in order |+| -------- | ------------------------------------------------------------------ |+| Search | Exa, Brave, Tavily, Parallel, Querit, Seltz, SearXNG, TinyFish |+| Answer | Gemini, Exa, Parallel |+| Contents | Exa, Tavily, Parallel, TinyFish |++Providers that are off are skipped, so with the defaults only Exa and Gemini serve.++## Providers and routes++Every provider has a **route**:++- **Included with TinyHumans** (`managed`): the call goes through the TinyHumans backend and is billed to your TinyHumans balance. It needs a signed-in session. No key is stored on your machine.+- **Own key** (`direct`): the call goes straight from your machine to the provider with your API key.++| Provider | Routes | Roles | Notes |+| -------- | ------------------ | ------------------------- | ----------------------------------------------------------------------------------------------------- |+| Exa | Included, own key | Search, answer, contents | On by default (included). |+| Gemini | Included, own key | Answer | On by default (included). A key of your own also unlocks Deep Research, even on the included route. |+| TinyFish | Own key | Search, contents | Off by default. There is no included TinyFish route; the managed backend does not proxy it. |+| Parallel | Own key | Search, answer, contents | Off by default. There is no included Parallel route; bring your own [Parallel](https://parallel.ai) key. Deep answers never use Parallel. |+| Brave | Own key | Search | Off by default. |+| Tavily | Own key | Search, contents | Off by default. |+| Querit | Own key | Search | Off by default. |+| Seltz | Own key | Search | Off by default. |+| SearXNG | Own instance | Search | Off by default. Uses the URL of your own [SearXNG](https://docs.searxng.org/) instance, not a key. |++A provider is **usable** when it is on, its route is available (you are signed in for the included route, or a key is saved for the own-key route), and search as a whole is on. The settings page shows this as a badge on each provider: **Ready**, **Needs key**, **Sign in required**, or **Off**.++If you use OpenHuman without signing in (a local session), the included route is unavailable. Turn on a provider with your own key to keep web search working.++When your TinyHumans balance runs out, included providers stop answering and the failed tool call in chat says so. Top up, or switch a provider to your own key.++## Settings++Everything is under **Connections → Search**:++- **Web search**: one switch turns every search tool on or off.+- **Providers**: one card per provider with an on/off switch, the route choice (for providers that support both), the API key field for the own-key route, and the instance URL for SearXNG. Gemini always shows its key field, since the key is what enables Deep Research.+- **Roles**: the provider order for Search, Answer and Contents, with which provider currently serves each role. Move providers up or down, remove fallbacks, add a provider back, or reset a role to its default order.+- **Allowed websites**: which sites the assistant may open and read through web fetch and the browser tool. This list does not restrict web search.+- **Advanced → Expose each provider's own tools**: gives the agent each usable provider's own tools (for example Brave news or image search, or Exa's find-similar) rather than one tool per role. This uses more of the context window.++Keys are stored in `config.toml`. When secret encryption is on, OpenHuman stores them as ciphertext; the OS keyring protects the master encryption key, not the provider keys themselves.++### Configuration file and environment++The same settings live under `[search]` in `config.toml`:++```toml+[search]+enabled = true++[search.providers.exa]+enabled = true+route = "managed"++[search.providers.brave]+enabled = true+route = "direct"++[search.roles]+search = ["brave", "exa"]++[search.brave]+api_key = "your-brave-api-key"+```++Do not commit a plaintext API key. A key entered directly in `config.toml` stays plaintext until OpenHuman next saves the configuration with secret encryption on.++Environment overrides:++| Variable | Effect |+| ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |+| `OPENHUMAN_SEARCH_ENABLED` | Turns search on or off. |+| `OPENHUMAN_SEARCH_PROVIDERS` | Replaces the provider set, e.g. `exa:managed,gemini,brave`. |+| `OPENHUMAN_SEARCH_ROUTES` | Changes routes, e.g. `exa=direct,gemini=managed`. |+| `OPENHUMAN_SEARCH_ROLES` | Sets role orders, e.g. `search=brave\|exa;answer=gemini`. |+| `OPENHUMAN_EXA_API_KEY`, `OPENHUMAN_GEMINI_API_KEY`, `OPENHUMAN_BRAVE_API_KEY`, `OPENHUMAN_TAVILY_API_KEY`, `OPENHUMAN_QUERIT_API_KEY`, `OPENHUMAN_PARALLEL_API_KEY`, `OPENHUMAN_SELTZ_API_KEY` | Provider keys. The unprefixed names (`EXA_API_KEY`, `GEMINI_API_KEY`, …) work too. |++Treat environment-provided keys as secrets.++## SearXNG over RPC and MCP++Besides serving the Search role, an enabled SearXNG instance is exposed to RPC and MCP clients as `openhuman.tools_searxng_search` (`searxng_search` in the MCP catalog), which pins the call to SearXNG. Its `[searxng]` section in `config.toml` and the `OPENHUMAN_SEARXNG_*` variables (`ENABLED`, `BASE_URL`, `MAX_RESULTS`, `DEFAULT_LANGUAGE`, `TIMEOUT_SECONDS`) configure the instance.++## Parallel is own-key only++Parallel is no longer included with TinyHumans; it works only with your own Parallel key. A saved Parallel key carries over when you upgrade (Parallel stays first for search if it was your chosen engine). A setup that relied on the included Parallel route without a key moves to the included Exa and Gemini providers. `OPENHUMAN_PARALLEL_ROUTE` is ignored.++## How it differs from generic HTTP++A plain `http_request` tool can fetch a URL but can't _find_ one. Web search is the discovery layer: it finds the right URLs, and the Contents role (or the [Web Scraper](web-scraper.md)) reads them.++## See also++- [MCP Server](../../developing/mcp-server.md): how `searxng_search` appears to MCP clients.+- [Web Scraper](web-scraper.md): fetch and clean a specific URL.+- [Smart Token Compression](../token-compression.md): search snippets are compressed before they reach the model.diff --git a/docs/gitbooks/docs/gitbooks/en/features/notifications-and-activity.md b/docs/gitbooks/docs/gitbooks/en/features/notifications-and-activity.mdnew file mode 100644index 0000000000..bfb3d2b16d--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/notifications-and-activity.md@@ -0,0 +1,91 @@+---+description: >-+ The notification center, the quiet notice tray, and where background work+ now surfaces: everything OpenHuman tells you about, and everything it does+ while you are not watching.+icon: bell+---++# Notifications & Activity++OpenHuman surfaces two kinds of "what's happening": **notifications** (things you should look at, like an important Slack message, a failed webhook, or a high-priority email) and **activity** (a ledger of what the agent did on its own while you weren't watching).++Both live on the **Notifications** page. There is no longer an Activity hub or a Routines screen. Both addresses still resolve, but not to what they used to show: `/activity` redirects to **Settings → Account**, and `/routines` to [Workflows](workflows.md). The notification feeds moved here, and the scheduler moved to Workflows → Schedules.++---++## Notification Center++The notification center is fed by two independent streams, which render as two stacked sections on the Notifications page.++### Integration notifications++Notifications captured from connected accounts (Gmail, Slack, WhatsApp, Discord, …) are ingested through the `notification.ingest` RPC, persisted to a per-workspace SQLite store, and then **triaged by a local LLM in the background**. Ingest returns immediately; triage runs in a spawned task and back-fills the score a moment later, so a freshly arrived item can briefly show as unscored.++Triage assigns each notification an **action**, which maps to a fixed importance score between 0.0 and 1.0:++| Triage action | Score | What it means |+| ------------- | ----- | -------------------------------- |+| `drop` | 0.10 | Noise, not worth surfacing |+| `acknowledge` | 0.35 | Low value, informational |+| `react` | 0.65 | Worth a follow-up |+| `escalate` | 0.90 | High priority, hand to the agent |++Only `react` and `escalate` are considered "routed" actions; `drop` and `acknowledge` stay quiet. Each ingested item carries a one-sentence `triage_reason` justifying the classifier's call, plus a lifecycle status: **unread → read → acted → dismissed**. Duplicate content received within a 60-second window collapses to a single entry.++### System (core-bridge) notifications++The second stream translates selected internal events into compact, user-facing alerts and pushes them over the socket bridge as they happen. These are persisted before broadcast, so anything fired while the app was closed syncs down on the next open. Each carries a **category** and an in-app deep link:++| Source event | Category | Surfaces when |+| -------------------- | -------- | ----------------------------------------- |+| Cron job completed | Agents | Always (success or failure) |+| Webhook processed | System | **Only on failure**; successes are silent |+| Sub-agent finished | Agents | Always |+| Sub-agent failed | Agents | Always |+| Notification triaged | Agents | Only when routed (`escalate`/`react`) |+| API key rejected | System | Always; links to the LLM settings tab |++The category set the notification center understands is **messages, agents, skills, system, meetings, reminders, important**. The page shows a filter chip row, but only for the categories that actually appear in the current feed, plus **Mark all read** and **Clear**. Clicking a notification marks it read and follows its deep link. Some core notifications carry **action buttons** and are pinned to the top. The feed holds the most recent 200 items.++### Per-provider routing & thresholds++Every provider has its own settings (`notification.settings_set`), letting you tune the noise per source:++| Setting | Effect |+| ----------------------- | ------------------------------------------------------------------------------ |+| `enabled` | When off, that provider's notifications are not ingested at all |+| `importance_threshold` | Minimum score (0.0 to 1.0) to display; `0.0` shows everything |+| `route_to_orchestrator` | When on, high-importance (`react`/`escalate`) items are forwarded to the agent |++Auto-routing re-reads the provider's settings the moment before escalating, so toggling a setting mid-flight takes effect immediately. A notification is only routed to the agent when its score clears the provider threshold **and** `route_to_orchestrator` is enabled.++These per-provider settings have no UI today: the page that edited them was removed, so they are set through the RPC or by hand. The per-category preferences gate **ingest**, not just display, which is worth knowing before changing one.++---++## The notice tray++Separate from the notification center, a quiet tray in the bottom-right corner collects **things you can act on**: a provider key that was rejected, a plan limit reached, a keyring consent prompt. It replaced the full-width banners that used to push the chat down. Repeats of the same problem bump a count rather than stacking, and the tray is in-memory, so it clears on restart.++Product announcements arrive separately again, as a modal shown once per signed-in session, with the ids you have already seen remembered.++---++## Where background work surfaces++| Kind of background work | Where to look |+| --- | --- |+| Scheduled jobs and their run history | **Workflows → Schedules**. See [Cron & Scheduling](native-tools/cron.md). |+| Workflow runs | **Workflows → Runs** |+| Memory belief builds and source syncs | **Connections → Memory → Background** |+| Detached sub-agents and async delegation | The background inbox card in the thread that started them. See [Chat](chat.md). |+| Everything above, as notifications | The Notifications page, Agents category |++---++## See also++- [Cron & Scheduling](native-tools/cron.md): the scheduling engine and the agent tools behind the Schedules view.+- [Triggers](integrations/triggers.md): webhooks and inbound events that can raise a notification.+- [Chat](chat.md): where an approval or a sub-agent result lands when you are in the conversation.diff --git a/docs/gitbooks/docs/gitbooks/en/features/orchestration.md b/docs/gitbooks/docs/gitbooks/en/features/orchestration.mdnew file mode 100644index 0000000000..502c3dff4a--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/orchestration.md@@ -0,0 +1,54 @@+---+description: >-+ OpenHuman is an orchestrator, not a chatbot: durable agent graphs, visual+ workflows, sub-agent fleets, and a split-brain always-on layer, all in one+ coherent stack.+icon: sitemap+---++# The Orchestrator++<figure><img src="../.gitbook/assets/orchestration.png" alt=""><figcaption><p>OpenHuman orchestrating a fleet of agents.</p></figcaption></figure>++Most harnesses run one agent in one loop. OpenHuman is built as an **orchestrator**: a stack for coordinating many agents, over long horizons, across machines. It does this durably, observably, and under your control.++Four layers make that real:++## 1. Graphs, not loops++Every agent turn runs on [tinyagents](https://github.com/tinyhumansai/tinyagents), our open-source graph engine. Multi-step work compiles to **state-machine graphs with conditional routing**: `plan → execute ⇄ review → finalize` for delegation, phase DAGs for multi-agent workflow runs, and map-reduce fan-out for parallel workers. All of it has **durable checkpointing**. A graph can pause mid-run (for your answer, for an approval, for a restart) and resume exactly where it stopped.++## 2. Sub-agent fleets that don't get lost++The orchestrator spawns specialized sub-agents (up to 3 levels deep), reuses compatible idle workers instead of re-spawning, and routes each to the right model tier: heavy reasoning for the core, a fast **burst tier** for low-context workers. Reliability is structural: a no-progress circuit breaker stops loops, and stuck children hand back a `question` (pause + resume on your answer) or an `Incomplete` root-cause summary, never silence. See the [Agent Harness](../developing/architecture/agent-harness.md).++## 3. Workflows you can see++[Workflows](workflows.md) lift orchestration out of the chat: the agent _proposes_ a typed graph of triggers, agents, tools and conditions; you review it on a canvas and save it. Runs are durable, approval-gated, and fully inspectable step-by-step, powered by open-source [tinyflows](https://github.com/tinyhumansai/tinyflows).++## 4. An always-on split brain++Inbound traffic hits a **fast reflex agent** that triages in seconds and hands a deep **reasoning core** a concise brief; the core does the multi-step work and delegates to workers. Mid-task steering input can be delivered into a live session, and 20:1 compression keeps week-long sessions bounded.++## What's next++The scripted-orchestration idea this page used to advertise, agents writing control flow as small programs in a sandboxed REPL, is **not being built**: the harness dropped that runtime and the tool no longer exists. The substrate above, graphs with checkpointing under a trust model, is the shape orchestration takes.++What is tracked in the open instead: an [agent-to-agent protocol](https://github.com/tinyhumansai/openhuman/issues/3463) so a graph can span instances, and durable swarm task graphs. See the [roadmap](../overview/roadmap.md).++---++## Why this differentiates++| | Single-agent harnesses (Claude Code, OpenClaw, Hermes) | OpenHuman |+| --------------- | ------------------------------------------------------ | --------------------------------------------------------------- |+| Execution model | One loop, one context | Compiled graphs, conditional routing, checkpoint/resume |+| Parallelism | Manual / plugin | Native sub-agent fleets, map-reduce fan-out, worker reuse |+| Automation | Scripts & cron | Visual, durable, approval-gated workflows |+| Always-on | None | Split-brain reflex + reasoning core, mid-task steering |++## See also++- [Workflows](workflows.md)+- [Agent Harness](../developing/architecture/agent-harness.md): the developer deep-dive on graphs, breakers, journals.+- [Agent Coordination tools](native-tools/agent-coordination.md): the user-facing spawn/delegate surface.diff --git a/docs/gitbooks/docs/gitbooks/en/features/personalization.md b/docs/gitbooks/docs/gitbooks/en/features/personalization.mdnew file mode 100644index 0000000000..7d1133b5f1--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/personalization.md@@ -0,0 +1,31 @@+---+description: >-+ How OpenHuman learns your preferences from everyday use: learnings in memory,+ the memory pack recalled for each turn, and your persona files.+icon: brain+---++# Personalization & Self-Learning++OpenHuman gets to know you through [memory](memory.md), not a settings form. Three things shape how it behaves toward you, and all three are visible and editable.++## Learnings++A **learning** is one durable statement: a preference, fact, procedure or correction ("prefers pnpm", "never schedule meetings before 10"). The agent saves one with its `memory` tool (`learn` action) when you state or correct something worth keeping, and you can add your own on **Connections → Memory → Learnings**. Each learning records where it came from (workspace, thread, agent, the tool call). Delete any learning there, or ask the agent to forget it.++Learnings live in your selected memory engine, so memory has to be on (see [Engines](memory.md#engines)). Secrets and personal identifiers are scrubbed before storing.++## The memory pack++Before every turn, OpenHuman recalls a short, token-budgeted *memory pack* from memory: relevant learnings (and beliefs the engine has built from them), documents from your brain, this agent's earlier conversations and, briefly, other agents' turns. The pack is added to that turn's model request only and is never written into the chat, so the agent defaults to your preferences without being asked and the prompt cache is unaffected. Preview it on **Connections → Memory → Ask**. See [How the agent uses memory](memory.md#how-the-agent-uses-memory).++## Persona files++How the agent presents itself (`SOUL.md`, `IDENTITY.md`, `ROLE.md` in your workspace) is separate from memory. These are plain Markdown files you edit directly.++## See also++- [Memory](memory.md), the engines, sources and tabs behind all of this.+- [Memory tools](native-tools/memory-tools.md), how the agent recalls and learns.+- [Goals & Todos](goals-and-todos.md), the agent's in-session work tracking.+- [Cron & Scheduling](native-tools/cron.md), the scheduled runs that keep working your workspace between turns.diff --git a/docs/gitbooks/docs/gitbooks/en/features/platform.md b/docs/gitbooks/docs/gitbooks/en/features/platform.mdnew file mode 100644index 0000000000..8a5ac2da53--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/platform.md@@ -0,0 +1,108 @@+---+description: >-+ What OpenHuman ships as (native React + Tauri v2 desktop app with a Rust+ core), supported platforms, and what's in scope today.+icon: layer-plus+---++# Platform & Availability++OpenHuman is a native desktop application, not a browser extension, not an Electron wrapper. Built on **React + Tauri v2** with a **Rust core**, it ships small, starts fast, and stays out of the way.++---++## Supported platforms++| Platform | Architectures | Distribution |+| ----------- | -------------------- | ---------------------------------------------- |+| **macOS** | Intel, Apple Silicon | `.dmg` installer, Homebrew |+| **Windows** | x64, ARM64 | `.msi` installer |+| **Linux** | x64 | AppImage, `.deb`, AUR recipe (`openhuman-bin`) |++### Linux AppImage notes++The Linux AppImage is built for x64 desktops and is the default asset selected+by the curl installer. On newer distributions, especially builds that tighten+unprivileged user namespaces or AppArmor defaults, AppImage startup can fail+before OpenHuman reaches its own crash reporter. Known symptoms include:++- `unshare: write failed /proc/self/uid_map: Operation not permitted`+- `Interpreter not found!`+- `cannot execute binary file`++When that happens, prefer the `.deb` package on Debian/Ubuntu systems. For+Fedora, openSUSE, and other non-Debian distributions, include the distro+version, kernel version, GPU/driver stack, and the exact AppImage filename when+reporting the issue so maintainers can distinguish host restrictions from a+badly packaged AppImage runtime.++---++## Why native matters++OpenHuman is built as a native application rather than a web wrapper for three reasons.++**Small footprint.** A fraction of the size of typical communication tools. Starts in under a second and uses minimal memory.++**Fast startup.** No browser engine to initialize. Ready to accept requests immediately.++**OS-level security.** Credentials live in your platform's secure keychain, macOS Keychain, Windows Credential Manager, Linux Secret Service. Sensitive data never sits in browser storage or plain text files. Memory items live in the engine you select.++---++## Architecture at a glance++```text+┌────────────────────────────────────────────────────────┐+│ Tauri shell (Wry) · windowing, OS integration, IPC │+│ ┌──────────────────────────────────────────────────┐ │+│ │ Rust core, in-process (no sidecar) │ │+│ │ • Memory, integrations, source sync │ │+│ │ • Model router, TokenJuice, native tools │ │+│ │ • Voice (STT in, TTS out, live voice agent) │ │+│ └──────────────────────────────────────────────────┘ │+└────────────────────────────────────────────────────────┘+ ▲ JSON-RPC over loopback HTTP+ │+┌────────────────────────────────────────────────────────┐+│ React frontend · screens, navigation │+└────────────────────────────────────────────────────────┘+```++The shell is a delivery vehicle (windowing, process lifecycle, IPC). All product logic lives in the Rust core, which runs as a tokio task **inside** the shell process rather than as a separate binary the shell launches. The React frontend talks to it over JSON-RPC on loopback. See [Architecture](../developing/architecture/README.md) for the full picture.++---++## Remote/headless usage++Linux servers can host the Rust core without a desktop session. The production+shape is a remote `openhuman-core` JSON-RPC service plus a local desktop client+configured with that core URL and bearer token.++A private browser UI is possible for development/preview by serving the Vite+frontend and pointing it at the remote core, but it is not a full replacement+for the desktop shell. Native deep links, tray controls, OS keychain access, the+native iMessage scanner, and screen and window integrations still require the+Tauri app.+See [Cloud Deploy](cloud-deploy.md#remote-ui-choices) for the current remote UI+setup.++---++## Real-time communication++The desktop app maintains a persistent connection to the OpenHuman backend. Responses stream as they are generated; outputs appear progressively, not after a hang. If the network drops, the app reconnects automatically with progressive backoff.++---++## Offline behavior++Your local state persists on your device. Preferences, settings, and connected-source configurations remain available offline. Your workspace files stay readable without a network connection. The [memory engine](memory.md) itself needs connectivity unless you point CortexDB at a local endpoint.++Source sync and live LLM calls require connectivity. When the network returns, the next scheduled sync picks up where it left off.++---++## Auto-update++The desktop shell auto-updates itself via Tauri's updater plugin against a manifest published on GitHub Releases. The core is linked into the shell, so a shell update upgrades both; there is no separate core update. Details, including the retry policy and why a signature failure is never retried, are in [Auto-update](../overview/auto-update.md).diff --git a/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/README.md b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/README.mdnew file mode 100644index 0000000000..dfa6f757fa--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/README.md@@ -0,0 +1,119 @@+---+description: >-+ Where your memory is stored, what stays on your machine, what the backend+ brokers, and which of these layers are enforced by default.+icon: shield+---++# Privacy & Security++Your workspace files, settings and audio buffers stay on your machine. **Your memory does not**: memory items are stored in CortexDB, either the hosted CortexDB that TinyHumans runs for you or a CortexDB you point OpenHuman at. The OpenHuman backend brokers the rest of what has to leave the device (LLM calls, OAuth tokens, search proxying, hosted memory).++***++## Privacy by Design++**You choose where memory lives.** [Memory](../memory.md) is stored by the engine you select: hosted TinyHumans (CortexDB behind the OpenHuman backend, requires sign-in) or your own CortexDB endpoint. With neither, memory is off and nothing is stored. Secrets and personal identifiers are scrubbed from every item before it is sent, tool-call arguments are never stored, and you can delete any item. See [Where your memory is stored](./#where-your-memory-is-stored) below.++**Integration tokens are held by the backend, not on your laptop.** OAuth tokens are never written to disk in plaintext on your device. The OpenHuman backend brokers each integration request, the core never speaks any third-party API directly.++**OS-level credential storage.** Sensitive local secrets are rooted in your platform's secure keychain, macOS Keychain, Windows Credential Manager, Linux Secret Service. See [OS Keyring & Secret Storage](os-keyring-and-secret-storage.md).++**No training on your data.** Your conversations, your memories, and your personal information are never used to train AI models or improve systems.++**Optional** [**Local AI**](../model-routing/local-ai.md)**.** If you want embeddings and summary-tree building to stay on your machine, run a local runtime such as Ollama, pull the models yourself, and add it as a provider. Learning and reflection passes, and chat if you choose, can be moved on-device the same way. OpenHuman does not install the runtime or download models.++***++## What stays on your machine++| | |+| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Memory items** | **Not local with hosted memory.** Stored in CortexDB by your selected engine (see below); a CortexDB you self-host on your own machine keeps it there. |+| **Memory bookkeeping** | Local: the job queue and sync, backfill and import progress under `<workspace>/memory/`, the sources list in `config.toml`, a CortexDB key in the OS keychain. No memory content. |+| **Audio capture buffers** | Local. Discarded after STT. |+| **Local model state** | Local. |++## Where your memory is stored++Memory items are your brain documents, logged conversation turns, learnings, and the facts and beliefs the engine builds from them. They are stored in CortexDB, never in a database on your machine. Which CortexDB depends on the engine:++| Engine | Path | Who can reach it |+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **TinyHumans** (hosted) | The core sends each request over TLS to the TinyHumans backend's `/memory/*` routes, authenticated with your session or TinyHumans API key. The backend applies a per-user rate limit and billing, then forwards to a CortexDB proxy that places every scope under your own tenant root. | Only your account. The proxy derives the tenant from your credential, not from the request, so one user cannot read or write another's memory. TinyHumans operates the service. |+| **CortexDB** (direct) | The core calls CortexDB itself (`api-v1.cortexdb.ai`, or a self-hosted endpoint) with your own CortexDB API key, kept in the OS keychain. It does not go through the TinyHumans backend. | Whoever holds that key, and the operator of that endpoint. |++Inside either engine, memory is kept below a root derived from the active config identity (`org:<id>` for a TinyHumans account, `org:local-<digest>` for a local identity; on hosted memory this is the tenant root the backend pins, so paths read `org:<id>/ws:main/…`), so it can be listed, confined and erased as one tree. Learnings and the brain are shared by your agents; each agent's conversations are tagged with that agent.++We make no claim beyond TLS in transit and per-user tenant isolation for hosted memory. In particular, these docs do not promise end-to-end or client-side encryption: the hosted service can read what it stores, which is how it answers recall.++### Deleting memory++* **One item:** **Forget** in the Memory page's **Explorer**, on a memory chip under an answer, on the **Learnings** tab, or through the agent's `memory` tool (`forget`).+* **One source:** **Forget source** on the **Brain** tab, or tick **Also delete memory from this source** when disconnecting an integration.+* **Everything:** the `openhuman.memory_erase_all` RPC (`{"confirm": true}`) erases all memory the selected engine holds, for good. On hosted memory it calls the backend's `DELETE /memory`, which erases your whole tenant. On a direct CortexDB it erases your own `org:<id>` tree (and the earlier `user:<id>` tree while it is still read); memory written there before the per-user layout, which other accounts on a self-hosted CortexDB may share, is left for you to delete with your CortexDB account or endpoint. The **Settings** tab of the Memory page has an **Erase memory** card that calls the same RPC after you confirm.++Signing out does **not** delete stored memory, and neither does disconnecting an integration unless you tick that box.++## What the OpenHuman backend handles++| | |+| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **LLM calls** | Proxied through the backend under one subscription, then forwarded to the underlying provider (Anthropic / OpenAI / Google / etc.) per the [model router](../model-routing/). |+| **Web search proxy** | The native [web search tool](../native-tools/web-search.md) can use the backend proxy, so you don't carry a search API key. Only **Exa** and **Gemini** have a managed route; Brave, Querit, Tavily, Seltz, Parallel, TinyFish and Gemini Deep Research are bring-your-own-key and go **directly** to that provider, and SearXNG goes to the instance you configured. With Tavily selected, the `tavily_extract` tool also sends extraction requests, including the URLs being extracted, directly to Tavily. |+| **Integration OAuth & tool proxy** | Token storage and rate-limited request brokering for [the connected integrations](../integrations/). |+| **TTS streaming** | Hosted [text-to-speech](../native-tools/voice.md) audio streams. Audio is generated and discarded - not retained. |++***++## Permissions and access control++OpenHuman accesses an integration only after you complete its OAuth flow. Each connection has its own scope; you can revoke any of them at any time from the **Connections** page.++[Memory sources](../memory.md) sync on a schedule while they exist, which is the point. Integration sync is bound by:++* The **OAuth scope** you granted that integration.+* A **per-provider sync interval** (e.g. Gmail every 15 min by default).+* A **daily budget** per connection that caps API usage.++If you revoke a connection, the next sync stops; items already stored in your memory engine remain until you forget them.++***++## Why memory is scrubbed and scoped++Memory only helps if it is safe to keep. Every item passes through secret and PII scrubbing before it is stored, conversations record tool-call names and ids but never arguments, and the agent only sees what a recall or fetch returns at the moment of a turn. You can inspect and delete items from **Connections → Memory** (see [Deleting memory](./#deleting-memory)).++Scrubbing and scoped retrieval together become the privacy architecture.++## Security++**Encrypted in transit.** All communication between the application and the OpenHuman backend uses TLS, and so do hosted memory requests and direct calls to CortexDB's managed API. A self-hosted CortexDB endpoint is only as protected as the URL you configure.++**Key in keyring, ciphertext on disk.** For local secrets that must be persisted in app files, OpenHuman stores encrypted ciphertext on disk and keeps the master decryption key in the OS keyring. See [OS Keyring & Secret Storage](os-keyring-and-secret-storage.md).++**Sandboxed execution.** Shell and code the agent runs goes through a sandbox backend chosen per session: none, the OS jail (Landlock on Linux, Seatbelt on macOS), or a Docker container with no network, dropped capabilities and a read-only root filesystem by default. Skills are not separately sandboxed: the in-app JavaScript sandbox was removed, and a skill now runs as its own agent session subject to the same execution policy as any other turn.++**Working-folder-scoped tools.** The native [filesystem tools](../native-tools/coder.md) act inside the agent's working folder. That confinement is part of the autonomy policy, which is **off by default**: until you set `[autonomy] enabled = true` it is not enforced. What is enforced either way is the hard floor, credential stores and system roots. See [Approval Gate](../approval-gate.md).++**Short-lived tokens.** Authentication tokens between the app and the backend are time-limited.++***++## Trust & Risk Intelligence++OpenHuman includes an intelligence layer designed to help you reason about credibility, information quality, and potential risks across your connected sources.++**Scam and impersonation signals.** Behavioral patterns associated with scams, impersonation, or coordinated abuse can surface as warnings. Signals come from patterns, not from sharing individual message content.++**Contextual dynamic trust.** Trust is contextual, credibility in one domain does not automatically transfer to another. OpenHuman represents trust through aggregated artifacts and historical accuracy rather than static scores.++**Advisory, not enforcement.** Trust and risk outputs are advisory signals to inform your judgment. OpenHuman does not ban users, remove messages, or enforce moderation decisions.++***++## Shared environments++In team or community settings, privacy remains user-centric. Each user's connected sources are scoped to their account; admins do not get a backdoor into other users' memory.++Community-level intelligence is derived from aggregated and anonymized signals, never from direct access to individual message content.diff --git a/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/os-keyring-and-secret-storage.md b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/os-keyring-and-secret-storage.mdnew file mode 100644index 0000000000..536ce091ac--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/os-keyring-and-secret-storage.md@@ -0,0 +1,145 @@+---+description: >-+ The OS keyring as root of trust: what is stored there, what is encrypted on+ disk beside it, and what the consent prompt is asking for.+icon: key+---++# OS Keyring & Secret Storage++OpenHuman uses the **operating system's secure credential store** to protect the secrets that must live on your device.++On desktop builds, that means:++* **macOS:** Keychain+* **Windows:** Credential Manager+* **Linux:** Secret Service / libsecret++This is the root of trust for local secret material. OpenHuman does not rely on a plaintext `.env` file or a plaintext local config file for user credentials.++***++## What goes into the OS keyring++OpenHuman uses the OS keyring for two kinds of local secret material:++### 1. Credential entries++When a feature needs a local credential slot, OpenHuman stores it in the platform keyring rather than writing the raw secret into a normal config file.++Examples include:++* locally stored provider API keys+* session and bearer tokens that must remain on-device+* wallet secret material where applicable++These entries are scoped under OpenHuman's own key namespace so they do not collide with unrelated apps.++### 2. The master encryption key++Some sensitive values still need to live **inside local files** because the application configuration itself is file-based.++OpenHuman handles that by splitting storage in two:++* the **secret value on disk** is stored as encrypted ciphertext+* the **master key used to decrypt it** lives in the OS keyring++This means your local config and state files can contain encrypted values without the decryption key sitting beside them in plaintext.++***++## What stays encrypted on disk++When OpenHuman needs to persist sensitive application settings locally, it writes the **ciphertext** to disk and keeps the key in the OS keyring.++That covers local secrets such as:++* BYO API keys for supported providers+* channel and webhook secrets stored in local config+* other locally persisted secret settings required for desktop features++The encryption format is authenticated, so OpenHuman can detect tampering instead of silently accepting modified ciphertext.++In practice, the security model is:++* **key in keyring**+* **ciphertext in file**+* **plaintext only in memory when needed**++***++## Why this is better than plaintext config++If your machine has a local workspace backup, sync folder, or support bundle, plaintext secrets in config files are a liability.++Using the OS keyring as the root secret store gives OpenHuman a safer split:++* config files can be copied without exposing raw credentials+* accidental log or file inspection is less likely to reveal secrets+* the decryption key is delegated to the platform's credential system rather than to an app-managed plaintext file++This is not a replacement for full-disk encryption or OS account security. It is a narrower, stronger way to handle application secrets.++***++## Managed integrations vs local secrets++Not every secret follows the same path.++### Managed integrations++For the default managed integration flow, third-party OAuth tokens are handled by the OpenHuman backend. Your local app does **not** need to persist those provider tokens in plaintext on your machine.++### Local BYO credentials++When you choose a bring-your-own-key or direct-mode path, OpenHuman treats those credentials as **local secrets** and protects them using the OS keyring plus encrypted-at-rest local storage where needed.++***++## Migration from older installs++Older versions could keep local encryption material in a file-based form.++Current desktop builds migrate that material into the OS keyring and keep the encrypted payloads on disk. The goal is to move the root secret out of ordinary files and into the platform credential store, without requiring users to re-enter every secret by hand.++***++## Consent flow when the keyring is unavailable++Sometimes the OS keyring is unreachable, for example on Linux without a Secret Service daemon, or on macOS when keychain access is denied. When that happens, OpenHuman **stops and asks** before falling back to local encrypted storage.++### How it works++1. **Detection.** On startup the core probes the OS keychain. If the probe fails, it classifies the reason (no daemon, locked, denied) and reports a structured `KeyringStatus` via the `openhuman.keyring_consent_status` RPC and the app snapshot.+2. **Consent prompt.** The first time a secret must be read or written and no consent has been recorded, a modal overlay explains what happened, what "store locally" means, and what the risks are. The user can:+ * **Use Local Encrypted Storage**: consent to ChaCha20-Poly1305 encrypted files (master key also on disk).+ * **Retry OS Keychain**: re-probe (useful after granting OS permission).+ * **Skip**: decline local storage; features that need secrets will be unavailable.+3. **Persisted preference.** The choice is recorded in `app-state.json` (`keyringConsent` field) and cached in-process. The app re-probes on each launch and re-prompts if the keyring becomes available after a local-only session.+4. **Settings visibility.** **Settings → Security** shows the active storage mode, keychain availability, failure reason, and buttons to retry or change consent.++### Unified fallback policy++Auth profiles, config secrets, wallet mnemonic, and the `secrets.enc` backend all call `keyring_consent::policy::check_secret_access()` instead of raw `is_available()`. This ensures no code path silently switches storage modes.++| Policy decision | Meaning |+| ----------------- | ---------------------------------------------------------- |+| `Proceed` | OS keyring available, or user consented to local encrypted |+| `ConsentRequired` | Keyring unavailable, no consent yet; block and prompt |+| `Declined` | User refused local storage; skip the secret operation |++***++## Platform note++This page describes **desktop** OpenHuman: the Tauri app on macOS, Windows, and Linux.++In development and test environments, the repository may use test-specific overrides so automated runs do not depend on an interactive OS keychain. That is a developer convenience, not the end-user desktop security model.++***++## See also++* [Privacy & Security](./)+* [Third-party Integrations](../integrations/)+* [Local AI (optional)](../model-routing/local-ai.md)diff --git a/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/privacy-mode.md b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/privacy-mode.mdnew file mode 100644index 0000000000..d5d47a1b03--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/privacy-and-security/privacy-mode.md@@ -0,0 +1,59 @@+---+description: >-+ One switch, enforced in the Rust core: local-only mode blocks every cloud+ model call, plus network tools, web search, integrations and cloud embeddings,+ permitting only on-device runtimes (Ollama, LM+icon: lock+---++# Privacy Mode++Most assistants' privacy stories are a paragraph in a system prompt. OpenHuman's is an **enforcement chokepoint in the Rust core**.++The `[privacy]` config block defines three modes:++| Mode | What it means |+| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **`standard`** _(default)_ | Normal operation: managed cloud routing, BYO providers, and local models all available. |+| **`local_only`** | **No inference leaves the device.** Every external chat provider (the managed cloud, BYO cloud keys, even CLI delegates like Claude Code) is refused at construction time, and network tools, web search, integrations, and cloud embeddings are refused at their egress points. Only local runtimes pass: Ollama, LM Studio, MLX, and local OpenAI-compatible endpoints. Voice is the one exception, because no local STT engine exists. |+| **`sensitive`** | Foundation for the upcoming PII-aware tier (detection, redaction, destination disclosure). Today it behaves like `standard`. |++## Why "enforced" matters++Privacy Mode is deliberately **not** a policy the model is asked to follow. The first check lives in the inference provider factory (`crates/openhuman-core/src/inference/provider/factory/`): under `local_only`, the core refuses to _build_ an external provider at all, and the error names exactly which provider was blocked and tells you how to fix it: switch to a local model, or change the mode in Settings.++That makes the guarantee independent of prompts, agents, tools, or bugs upstream: if a code path anywhere in the app tries to reach a cloud model while you're in local-only mode, it structurally cannot get a client.++Inference is no longer the only chokepoint. `local_only` is also enforced at the egress points where the agent ships your data anywhere else (`crates/openhuman-core/src/security/egress/enforce.rs`):++| Egress point | Behaviour under `local_only` |+| ---------------------------------------------------------------- | --------------------------------------------------------- |+| Network tools (`http_request`, `web_fetch`, `curl`) | Refused, with a policy-blocked message in the tool result |+| Web search (Exa, Tavily) | Refused the same way |+| Composio tool calls and integration requests | Refused with an error |+| Cloud embeddings | Refused with an error |+| Local runtimes (Ollama, LM Studio, MLX, local OpenAI-compatible) | Always permitted, nothing leaves the device |++One deliberate exemption: backend **control-plane** round-trips (sign-in, session, team, billing, and the integration connection-management and catalog reads) keep flowing, because blocking them breaks the app for no privacy gain. They carry auth tokens, ids, and routing metadata, never user content.++**Voice is not covered.** There is no local speech-to-text engine, so dictation and transcription still leave the device under `local_only`: to the hosted OpenHuman STT proxy, or to whichever third-party STT provider you configured. If that matters for your threat model, leave voice off.++Privacy Mode governs **data egress**. It is orthogonal to the [autonomy tiers](../approval-gate.md) (readonly / supervised / full), which govern what the agent may _do_. You can run a fully autonomous agent that never sends a byte of inference off-device.++## Pairing it with local models++Local-only mode is designed to work with [Local AI](../model-routing/local-ai.md). OpenHuman does not install runtimes or download models, so you set these up yourself before turning it on:++* Chat and reasoning on a runtime you run (**Ollama, LM Studio, MLX, OMLX**, or another OpenAI-compatible server), with the models you pulled, added as a provider under **Connections → LLM**.+* **Piper** text-to-speech, if you install the Piper binary and a voice yourself and set `PIPER_BIN`.+* Memory stays on a CortexDB endpoint you run yourself; the hosted TinyHumans engine is a cloud call and is blocked by local-only mode.++With local-only on, a workload routed to a runtime that isn't running, or to a model you haven't pulled, fails instead of falling back to the cloud.++See the [Use OpenHuman with a local model](../../guides/guides/local-model.md) guide for a full local setup, and [Keep sensitive data private](../../guides/guides/privacy-sensitive-data.md) for a broader privacy walkthrough.++## See also++* [Privacy & Security](./): the full trust model (approval gate, sandboxing, path roots, command classification).+* [OS Keyring & Secret Storage](os-keyring-and-secret-storage.md): where credentials live.+* [Local AI](../model-routing/local-ai.md): the on-device model runtimes.diff --git a/docs/gitbooks/docs/gitbooks/en/features/settings.md b/docs/gitbooks/docs/gitbooks/en/features/settings.mdnew file mode 100644index 0000000000..163fe60230--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/settings.md@@ -0,0 +1,82 @@+---+description: >-+ The settings surface: what each panel controls, where the autonomy tier+ actually lives, and which old addresses now redirect into Connections.+icon: gear+---++# Settings++Settings is a two-pane screen: a grouped rail on the left, one panel on the right. It holds the things that change how the app behaves. Things that change what the agent can _reach_ live in [Connections](connections.md), and most of the old settings addresses for those now redirect there.++Open it with the gear in the sidebar header, or `⌘,`.++## The groups++**General**++| Panel | What it controls |+| ------------- | ----------------------------------------------------------------------------------------------------------- |+| **Account** | Who you are signed in as, your plan and usage, team, devices, notifications, and language. |+| **Privacy** | [Privacy Mode](privacy-and-security/privacy-mode.md) and what may leave the machine. |+| **Migration** | Moving your data folder, and importing from an earlier version. |+| **Core** | Point the app at a core running somewhere else: its RPC URL, a bearer token, and a live reachability check. |+| **Feedback** | Send feedback from inside the app. |+| **About** | Version, build, licences, and the capability catalogue. |++**Appearance**++| Panel | What it controls |+| ---------------- | --------------------------------------------------------------------------------------------------------------------------- |+| **Appearance** | Font size (including a custom pixel value), layout corners and borders, and language. |+| **Theme Studio** | Theme family and variant, per-token colours, per-role fonts, backdrop, and your own saved themes. See [Themes](theming.md). |+| **Personality** | The editable `SOUL.md` prompt and its companion identity file. See [Personalization](personalization.md). |+| **Face** | Which mascot, its colours, a second "duo" mascot, a custom image, and its voice. See [The Mascot](mascot.md). |++**Security**++| Panel | What it controls |+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| **Keychain** | The OS keyring, consent, and what is encrypted at rest. See [OS Keyring & Secret Storage](privacy-and-security/os-keyring-and-secret-storage.md). |+| **Agent access** | Trusted roots and their read or write grant, the always-allow list, the blanket auto-approve switch, action and tool timeouts, the workspace-only switch, and the tool-call dialect. |+| **Sandbox** | Which sandbox backend a session gets, and its limits. |+| **Approval history** | The audit trail of approval decisions and their outcomes. |++## Where the autonomy tier is++Not in Agent access, which is the first place everyone looks.++The tier itself (`readonly`, `supervised`, `full`) has no control in the normal settings navigation. The panel that holds the radios is registered developer-only and as a hidden deep link, so it does not appear in the sidebar. Set the tier in `config.toml`:++```toml+[autonomy]+enabled = true # off by default; nothing below applies until this is true+level = "supervised"+```++`[autonomy] enabled` is `false` out of the box, which means Agent access's trusted roots, the always-allow list and the workspace-only switch are all inert until you turn the policy on. [Approval Gate](approval-gate.md) explains the whole model, including what stays enforced either way.++## Redirects++Roughly three times as many settings routes redirect as render, because the panels moved into [Connections](connections.md) and the addresses were kept working. Notable ones:++| Old address | Now |+| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |+| `/settings/llm`, `/settings/embeddings`, `/settings/voice`, `/settings/search` | Connections, the matching API-keys tab |+| `/settings/agents/*`, `/settings/tools` | Connections → Tools |+| `/settings/memory-*`, `/settings/intelligence` | Connections → Memory |+| `/settings/mcp-server`, `/settings/skills-runner` | Connections → MCP Servers, Connections → Skills |+| `/settings/wallet-balances` | Connections → Wallet Balances |+| `/settings/cron-jobs` | Workflows → Schedules |+| `/settings/automations` | Workflows |+| `/settings/team`, `/settings/billing`, `/settings/notifications`, `/settings/devices`, `/settings/language` | Settings → Account |++## Not here yet++There is no search across settings: the global search bar was removed, and the per-entry keywords are no longer read by anything. Notification categories gate which events are ingested, but the page that edited them is gone, so they are config-only today.++## See also++* [Connections](connections.md): everything the agent plugs into.+* [Approval Gate](approval-gate.md): the autonomy policy these panels configure.+* [Privacy & Security](privacy-and-security/): the posture behind the privacy panel.diff --git a/docs/gitbooks/docs/gitbooks/en/features/theming.md b/docs/gitbooks/docs/gitbooks/en/features/theming.mdnew file mode 100644index 0000000000..1c8c6a05dd--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/theming.md@@ -0,0 +1,168 @@+---+description: >-+ Five theme families with light, dark and auto variants, a visual Theme Studio+ for colours, fonts and backdrops, and Appearance controls for text size,+ corner rounding and borders.+icon: palette+---++# Themes & Theme Studio++OpenHuman is re-skinnable at runtime. Every change applies instantly and persists locally, with no restart.++The controls sit in two places:++| Page | What you set there |+| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |+| **Settings → Appearance** (`/settings/appearance`) | Text size, corner rounding, border contrast, per-area borders |+| **Settings → Theme Studio** (`/settings/theme`) | Theme family, light/dark/auto, every colour token, fonts per role, the backdrop, and custom-theme management |++***++## Built-in themes++Five families ship in `app/src/lib/theme/presets.ts`, each with a light and a dark variant:++| Family | Feel | Default variant |+| ------------ | ------------------------------------------------- | --------------- |+| **Classic** | The default OpenHuman look. | Light |+| **Ocean** | Cool blues. | Light |+| **Sepia** | Warm and paper-like, set in a serif. | Light |+| **Matrix** | High-contrast green on black, set in a monospace. | Dark |+| **HAL 9000** | Deep black with a red accent. | Dark |++Each family is applied as **Light**, **Dark** or **Auto**. Auto follows your operating system's `prefers-color-scheme` and re-applies live the moment you flip the OS between light and dark, with no reload.++Classic carries no colour or font overrides of its own on purpose: it is the palette defined in `app/src/styles/tokens.css`, selected by nothing more than the light/dark switch.++***++## Colours++The Theme Studio exposes every colour token, grouped as **Surfaces**, **Text**, **Borders** and **Accent colours**. The four accent ramps (primary, sage, amber, coral) show their `500` shade by default and expand to all eleven shades from `50` to `950`.++Each token is stored as a space-separated RGB channel triple such as `255 255 255`, not a hex string, because Tailwind wraps every token as `rgb(var(--token) / <alpha-value>)` so opacity modifiers like `bg-surface/50` keep working. The reasoning is recorded at the top of `app/src/styles/tokens.css`.++A **contrast warning** appears when the luminance gap between `content` and `surface-canvas` falls under 0.2. It is advisory and does not block the change.++***++## Fonts++Five roles can each take a different family:++| Role | Used for |+| --------- | --------------------------- |+| `title` | Display and brand type |+| `heading` | Section headings |+| `body` | Everything else |+| `mono` | Code and fixed-width output |+| `serif` | Serif passages |++All five pick from the same six choices in `app/src/lib/theme/tokens.ts` (`FONT_CHOICES`): Inter, Cabinet Grotesk, System UI, Newsreader (serif), Georgia (serif) and JetBrains Mono. A role whose stored stack matches no choice shows a disabled **Current** entry rather than silently snapping to another font.++Cabinet Grotesk is not bundled, so every stack naming it resolves to Inter. The name is kept so the intended stack stays legible; see the note in `app/src/styles/tokens.css`.++***++## Backdrop++Three kinds, set in the Theme Studio's **Background** card:++| Kind | What it paints |+| ------- | ---------------------------------------------------------------------- |+| `solid` | Nothing of its own: the themed body colour shows through. The default. |+| `mesh` | An animated, theme-tinted WebGL mesh gradient. |+| `image` | A cover image from a URL you supply. |++No built-in preset sets a backdrop, so every family starts on `solid` and the animated shader is opt-in. The dotted-canvas overlay that once sat above all three was removed outright rather than defaulted off, so there is no setting to rediscover.++***++## Text size++Four tiers, applied as an inline `font-size` on the root `<html>` element so everything rem-based scales with it:++| Tier | Size |+| ----------- | -------------- |+| Small | 14px |+| Medium | 16px (default) |+| Large | 18px |+| Extra large | 20px |++Beyond the tiers, a **Custom size** number field and slider take any whole pixel value. It is clamped to **12px to 28px** by `clampFontSizePx` in `app/src/store/themeSlice.ts`, which brackets the tiers on both sides: denser than Small, larger than Extra large. A non-finite value falls back to 16. Picking a tile clears the custom value.++***++## Layout++Three controls in `app/src/lib/theme/layout.ts`, all under Appearance, with a **Reset layout** button that restores every default.++**Corner rounding** scales Tailwind's whole radius scale (`--radius-xs` through `--radius-5xl`) by one factor:++| Option | Factor |+| ------- | ----------------------------------------------------- |+| None | 0 |+| Subtle | 0.5 |+| Default | 1 (the variables are removed, so the stylesheet wins) |+| Round | 1.6 |++Pills and avatars use `rounded-full` rather than a radius token, so they stay round at any setting.++**Border contrast** adjusts `--line`, `--line-strong` and `--line-subtle`, leaving `--line-chrome` to the theme. The tokens are reset before each change, so levels never compound:++| Option | Effect |+| ------- | ------------------------------------------------------- |+| Subtle | Mixes the line tokens 55 percent toward the surface |+| Default | No change: the theme's own values stand |+| Strong | Mixes the line tokens 30 percent toward the text colour |++**Per-area borders** turn borders off for one area at a time, by setting a `data-borders-<area>="off"` attribute that `app/src/styles/layout-overrides.css` acts on. Four areas:++| Area | Covers |+| -------------- | ------------------------------------------- |+| Cards & panels | Settings cards, grouped sections and panels |+| Form controls | Text fields, text boxes and dropdowns |+| Row dividers | Hairlines between rows in lists |+| Window frame | The edge around the main content area |++***++## Custom themes++Changing any colour, font or backdrop on a built-in preset forks it into a new custom theme named `<Name> (custom)` and makes that active. The preset stays pristine, so you can start from Ocean, tweak it, and keep both. Forking happens once per source theme.++A custom theme also offers **Reset overrides** (back to the preset it was forked from, or empty if it was not) and **Delete theme**, which falls back to Classic.++Sharing goes through JSON on the clipboard, not a file. **Copy JSON** puts the whole theme object in your clipboard and also renders it in a read-only text box to copy by hand. Import is a paste field: the JSON needs a `colors` object whose values are all strings, an empty one is accepted, and an unrecognised backdrop kind is dropped rather than failing the import. An imported theme gets a fresh id, so importing never overwrites what you have.++***++## How a theme is applied++A theme is just a set of values for the tokens in `app/src/styles/tokens.css`. `applyTheme` in `app/src/providers/ThemeProvider.tsx` writes the active theme's colours and fonts as inline `--token` custom properties on the root `<html>` element, overriding the stylesheet's light and dark blocks at runtime.++**Presets and fully custom themes are the same mechanism.** There is no per-theme stylesheet class and no `data-theme` attribute. The only class involved is `.dark`, a light/dark base selector that also keeps residual Tailwind `dark:` utilities aligned. Any token a theme leaves out falls through to the stylesheet defaults, and tokens set by a previous theme are cleared on each switch so nothing leaks.++Theme state persists through `redux-persist` under the `theme` key in plain `localStorage` rather than `userScopedStorage`, deliberately: the theme is a pre-login, whole-app preference, so it survives switching users instead of being scoped to one.++***++## Not wired++Two fields in `app/src/store/themeSlice.ts` are persisted but inert. Neither has a UI control, and neither has a consumer:++| Field | State |+| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `developerMode` | Has a reducer and a `selectDeveloperMode` selector, but nothing dispatches or reads either. Its own doc comment points at a `useDeveloperMode` hook that does not exist. Developer Options gates on core mode instead. |+| `tabBarLabels` | Has a reducer and no selector at all, so there is not even a readable accessor. |++Both sit in the persist whitelist, so a stale default may sit in `localStorage` doing nothing. Editing either by hand has no visible effect.++***++## See also++* [Theming (contributor reference)](../developing/theming.md): the token taxonomy, Tailwind wiring and component-authoring rules.+* [The Mascot](mascot.md): the other large piece of OpenHuman's personality.+* [Platform & Availability](platform.md): which desktop platforms the shell ships on.diff --git a/docs/gitbooks/docs/gitbooks/en/features/token-compression.md b/docs/gitbooks/docs/gitbooks/en/features/token-compression.mdnew file mode 100644index 0000000000..da87406f88--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/token-compression.md@@ -0,0 +1,179 @@+---+description: >-+ TokenJuice - a multi-stage compression router that compacts verbose tool+ output before it ever enters LLM context.+icon: file-zipper+---++# Smart Token Compression++LLM tokens are expensive, and verbose tool output is where most of them go to die. A `git status` in a busy repo, a `cargo build` log, a 600-message email thread, a `docker ps -a` against a real cluster. Each can balloon a context window for almost no information gain.++OpenHuman ships with **TokenJuice**, a compression router wired directly into the agent's tool-execution path. Before any tool result reaches a model, TokenJuice classifies it, routes it to a specialized compressor, optionally offloads the full original to a recoverable cache, and records how many tokens (and dollars) it saved.++It began as a port of [vincentkoc/tokenjuice](https://github.com/vincentkoc/tokenjuice). That JSON rule overlay is still in here as the log/command compressor, but it has since grown into a multi-stage, content-aware pipeline.++---++## The pipeline, step by step++Every blob that flows through the policy-aware TokenJuice tool-output adapters+takes the same path through the vendored TinyJuice router (`vendor/tinyjuice/src/compress.rs`):++```text+raw tool result+ │+ ▼+1. Size gate router enabled? input ≥ min_bytes_to_compress (2 KB)?+ │ yes+ ▼+2. Detect kind Json · Diff · Html · Search · Code · Log · PlainText+ │+ ▼+3. Select compressor one specialized compressor per kind (+ per-kind toggles)+ │+ ▼+4. Compress run it; if it declines or grows the output, fall back / pass through+ │+ ▼+5. CCR eligibility lossy AND ≥ ccr_min_tokens (≈500)? → offload original to cache+ │+ ▼+6. Append marker ⟦tj:<hash>⟧ footer so the agent can retrieve the full original+ │+ ▼+7. Record savings tokens + cost saved, by model and by compressor+ │+ ▼+ compact text → LLM context+```++1. **Size gate.** If the router is disabled or the input is below `min_bytes_to_compress` (default **2048 bytes**), it passes through untouched. Tiny outputs aren't worth compressing.+2. **Content detection** (`detect/kind.rs`). The blob is classified into one of seven `ContentKind`s. Precedence: an explicit hint → MIME/extension tag → a per-tool prior (e.g. `grep` → Search, `git_operations` → Diff, `run_tests` → Log) → cheap structural heuristics (JSON → Diff → HTML → Search → Code → Log → PlainText). No regex on the hot path.+3. **Compressor selection.** Each kind routes to a dedicated compressor, honoring per-kind toggles (`search_enabled`, `code_enabled`, `html_enabled`, `ml_compression_enabled`).+4. **Compression.** The compressor runs. If it declines or its output is no smaller than the input, TokenJuice falls back to the generic compressor or passes the original through. It never makes things bigger.+5. **CCR offload.** For **lossy** compressions where the original is large enough (`ccr_min_tokens`, default ~500 tokens), the full original is stowed in the **Compress-Cache-Retrieve** store so nothing is permanently lost.+6. **Recovery marker.** A footer carrying the canonical marker `⟦tj:<hash>⟧` is appended, telling the agent it's looking at a partial view and how to fetch the rest.+7. **Savings accounting.** Tokens saved and estimated cost saved are recorded, attributed by model and by compressor.++---++## The compressors++Each content kind has a purpose-built compressor (`vendor/tinyjuice/src/compressors/`):++| Compressor | Kind | What it does |+| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **SmartCrusher** | JSON | Re-renders arrays of objects as a compact table; past ~40 rows keeps head + tail + error rows + numeric outliers. |+| **Code** | Code | Keeps signatures and imports, collapses deep function bodies to `{ … N lines … }` (tree-sitter when available, brace-depth heuristic otherwise). Preserves `TODO`/`FIXME`/`error`/`panic`/`unsafe` markers. |+| **Log** | Log | For **command output**, delegates to the JSON rule engine (below). For other logs, keeps errors / warnings / stack traces / summaries and drops the noise. |+| **Search** | Search | Groups grep/ripgrep `path:line:body` hits by file, ranks by query-term density, keeps the top matches per file, and tallies `[+N more]`. |+| **Diff** | Diff | Keeps changed lines and hunk headers, collapses long unchanged runs to an anchor; lockfile hunks shrink to a one-line `+A/-B` summary. |+| **Html** | HTML | Strips markup to readable text with sensible block-boundary newlines and entity decoding (allocation-light, no DOM). |+| **MlText** | PlainText | Opt-in ML salience compression (see below). |+| **Generic** | fallback | Head/tail summariser for command output that no specific rule matched; declines on structured blobs so they're preserved. |++Multi-byte text (CJK, emoji, combining marks) is handled grapheme-by-grapheme throughout, never split mid-character.++---++## Handle preview and the REPL tools (default)++Compaction is **on by default**. For a result of at least `ccr_min_tokens` the router does not compress to one blob. It stores the original in the CCR cache and shows the model a small preview instead:++- a one-line **stats** description of the shape (estimated tokens, bytes, lines, JSON keys or a Markdown outline, never values),+- the **first 500 characters**,+- an extractive outline, and+- a footer naming the **handle** (the CCR token).++The model then queries the stored original with three read-only tools, none of which calls a model:++| Tool | Does |+| ---- | ---- |+| `juice_find` | `text`, `grep`, `regex`, `rank` (BM25), `sed`, `awk` and `jq` over the output, with a Python-style `scope` slice. |+| `juice_extract` | Links or headings from HTML or Markdown output. |+| `juice_summarize` | Size, outline or JSON shape, then head and tail, or the parts most relevant to a `hint`. |++Answers are size-capped, and an unknown or evicted handle is an error. `juice_retrieve` still returns the whole original. Because a handle preview is built without a model call, it also replaces the LLM summary for results big enough to get one, so a slow summarizer cannot stall the turn. The three tools are registered (about 1.5 KB of schema) only while this mode is in effect.++Opt out of the whole feature with `context.compaction_enabled = false` or `OPENHUMAN_COMPACTION=0`. Keep compaction but return to the one-blob compression and `juice_retrieve` with `tokenjuice.repl_handle_enabled = false` (`OPENHUMAN_TOKENJUICE_REPL_HANDLE_ENABLED=0`). Set `tokenjuice.repl_save_enabled = true` to also write each stored original to `<workspace>/.tokenjuice/repl/<handle>.txt` (mode 0600) so an agent can script over it; that puts raw tool output on disk and nothing prunes it.++---++## ML compression (opt-in)++Beyond the deterministic compressors, TokenJuice can route plain text through a **ModernBERT** token-salience model that scores and drops low-information spans. The TinyJuice compressor exposes the optional ML slot, and OpenHuman bridges it to Kompress in `crates/openhuman-core/src/inference/tokenjuice/ml/`.++- **Off by default.** Enable with `ml_compression_enabled = true` in `[tokenjuice]`.+- **Runs locally** as the `kompress` backend of the long-running Python host+ process OpenHuman keeps warm for Python-backed models+ (`crates/openhuman-core/src/runtime/python_server/`), reached over a private+ stdio protocol. No data leaves your machine.+- **Tunable:** `ml_model_id` (default `answerdotai/ModernBERT-base`), `ml_target_ratio` (default `0.5`), `ml_max_input_chars` (default `200000`), `ml_device` (`cpu`/`auto`), `ml_sidecar_idle_timeout_secs`.+- **Graceful:** if that process is unavailable or an input exceeds the char cap, it degrades to the native compressors without ever failing the agent loop.++---++## Nothing is lost: CCR cache & retrieval++Lossy compression would normally mean throwing data away. TokenJuice instead **offloads** the full original into the **Compress-Cache-Retrieve (CCR)** store and leaves a breadcrumb (`vendor/tinyjuice/src/cache/`).++- **In-memory tier** (always on): a process-global store keyed by SHA-256 hash, bounded by entry count (`max_cache_entries`, default 256) and total bytes (`max_cache_bytes`, default 64 MiB), FIFO eviction.+- **On-disk tier** (optional): `<workspace>/.tokenjuice/ccr/`, enabled with `ccr_disk_enabled`, survives memory eviction. Optional TTL via `ccr_ttl_secs`.+- **The marker:** compacted output ends with a footer like `[compacted tool output — PARTIAL view; full original available via juice_retrieve with token "…"]` carrying the `⟦tj:<hash>⟧` token.+- **Retrieval tool:** the agent calls the read-only **`juice_retrieve`** tool with that token (optionally a byte/line `range`) to pull back the full original or a slice. The token is an unguessable SHA-256 digest.++So the agent gets the cheap compacted view by default, and can transparently "zoom in" on the full text only when it actually needs it.++---++## Savings tracking++Every compression is metered by an OpenHuman savings callback (`crates/openhuman-core/src/inference/tokenjuice/savings.rs`). TokenJuice reports events and token deltas; OpenHuman applies the configured default model's input pricing, aggregates `total`, `by_model`, and `by_compressor`, and persists stats to `<workspace>/state/tokenjuice_savings.json`.++Read them over RPC with `openhuman.tokenjuice_savings_stats`; clear them with `openhuman.tokenjuice_savings_reset`.++---++## The rule overlay (command & log output)++The original three-layer JSON rule overlay still powers the Log/command compressor. Rules merge in order, later layers overriding earlier ones:++| Layer | Path | Purpose |+| ----------- | ----------------------------- | ------------------------------------------------------------ |+| **Builtin** | shipped with the binary | ~96 vendored rules for git, npm, cargo, docker, kubectl, ls… |+| **User** | `~/.config/tokenjuice/rules/` | personal overrides, apply everywhere |+| **Project** | `.tokenjuice/rules/` | repo-specific overrides, checked in and shared with the team |++Each rule names a command/tool pattern and a reduction strategy (skip/keep filters, transforms like strip-ANSI and dedupe, head/tail summarize, named counters, canned messages). Rules are JSON. Add one and it applies with no recompile.++---++## Configuration, RPC & tools++Everything lives under the `[tokenjuice]` config block (`crates/openhuman-core/src/config/schema/tokenjuice.rs`) and can be changed live.++- **Master switches:** `context.compaction_enabled` (default `true`; `OPENHUMAN_COMPACTION=0` opts out) and `router_enabled` (default `true`).+- **Handle preview:** `repl_handle_enabled` (default `true`), `repl_save_enabled` (default `false`).+- **Thresholds:** `min_bytes_to_compress`, `ccr_min_tokens`.+- **CCR:** `ccr_enabled`, `ccr_disk_enabled`, `max_cache_entries`, `max_cache_bytes`, `ccr_ttl_secs`.+- **Per-kind:** `search_enabled`, `code_enabled`, `html_enabled`, plus the `ml_*` keys.+- **RPC** (`openhuman.tokenjuice_*`): `detect`, `compress` (dry-run the pipeline), `settings_get` / `settings_update` (live partial patch), `cache_stats`, `retrieve`, `savings_stats`, `savings_reset`.+- **Agent tools:** `juice_retrieve` recovers a whole offloaded original; `juice_find`, `juice_extract` and `juice_summarize` query one by handle. All are read-only.+- **Debugging:** start the core with `RUST_LOG=openhuman_core::inference::tokenjuice=debug` to watch detection, matching, and how much each blob is trimmed.++---++## Why this matters++Agents live or die by their context budget. A single working session can fan out across dozens of tool calls: greps, builds, test runs, `git` output, and large [web-fetch / scrape](native-tools/web-scraper.md) results the agent pulls down. TokenJuice sits on that tool-execution path and compacts each result before it lands in context, so an agent can sweep a noisy repo or a long web page without each step ballooning the window. The savings compound across a session and are metered in real dollars (see [Billing, Cost & Usage](billing-and-usage.md)).++> **Scope note.** TokenJuice runs on the agent's **tool results**, not on [memory](memory.md) ingestion. Source sync converts documents itself and does not route payloads through TokenJuice.++---++## See also++- [Available Tools](native-tools/README.md): most heavy tool output flows through TokenJuice.+- [Memory](memory.md): ingestion has its own document conversion and scrubbing.+- [Billing, Cost & Usage](billing-and-usage.md): where token savings show up as real money.diff --git a/docs/gitbooks/docs/gitbooks/en/features/wallet.md b/docs/gitbooks/docs/gitbooks/en/features/wallet.mdnew file mode 100644index 0000000000..20bdb2d373--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/wallet.md@@ -0,0 +1,114 @@+---+description: >-+ Local, non-custodial multi-chain crypto wallet the agent can read balances+ from and send transfers with. Keys stay in-core and never cross the wire.+icon: wallet+---++# Wallet++A deliberately **basic**, **non-custodial** multi-chain crypto wallet owned by the Rust core. It manages one account per supported chain derived from a single recovery phrase, reads balances, and runs a strict **prepare → confirm → execute** flow for native sends and a small set of token transfers.++It is intentionally minimal: key/account management plus the primitive on-chain operations. Higher-level DeFi (swaps, bridges, generic contract/dapp calls) lives in a separate `web3` module and is **not** part of the wallet's agent or RPC surface.++The most important property to understand: **signing and broadcast happen entirely in-core from the decrypted recovery phrase. No private keys ever leave the device or cross the network.** This is your money, so the wallet is conservative by design.++***++## Supported chains and token standards++Setup derives **exactly one account per chain**. EVM is a single account reused across six networks. Only the standards listed below are supported for transfers. Anything else (swaps, arbitrary contract calls) is out of scope for the wallet.++| Chain | Networks | Native | Token standard | Notes |+| ------- | ------------------------------------------------------ | ---------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| EVM | Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain | ETH / BNB / etc. | ERC-20 (BEP-20 on BNB Chain) | One `Evm` account across all six; network selected per request, defaults to Ethereum mainnet. EIP-1559 / typed-tx signing. |+| Bitcoin | Mainnet | BTC | None | P2WPKH (native SegWit). **Rejects token transfers.** Esplora REST for balance/broadcast. |+| Solana | Mainnet / devnet (per RPC) | SOL | SPL | ed25519 signing; native + SPL token transfers. |+| Tron | Mainnet | TRX | TRC-20 | TronGrid REST for native + TRC-20 transfers. |++Built-in asset catalogs include the native asset plus common stablecoins per chain (e.g. USDC/USDT as ERC-20/BEP-20, USDC as SPL on Solana, USDT as TRC-20 on Tron).++***++## Onboarding and the recovery phrase++Setup is a single, all-or-nothing operation: it persists a consent flag, the mnemonic word count, the setup source, exactly one derived account per supported chain, and the encrypted recovery phrase. Valid BIP-39 mnemonic word counts are **12, 15, 18, 21, or 24**.++The recovery phrase is the only secret. The wallet stores the per-chain account **addresses** (safe to surface) separately from the secret material, and only the encrypted phrase can reconstruct private keys.++***++## Key custody and security++The wallet is **non-custodial and local**. There is no server-side key escrow.++* **The recovery phrase is always encrypted at rest.** It is encrypted via the core `encryption` domain before being persisted anywhere.+* **Preferred home: the OS keychain.** The encrypted phrase lives in the operating system keychain under the key `wallet.mnemonic`, scoped by a workspace-derived user id. Access is gated by the keyring consent policy.+* **Fallback: workspace JSON.** When the keychain is unavailable (e.g. headless), the encrypted phrase falls back to `{workspace_dir}/state/wallet-state.json`. On load, any JSON-resident secret is transparently **migrated into the keychain** when one becomes available, and stripped from the JSON.+* **Atomic, guarded writes.** `wallet-state.json` is written atomically (temp file + fsync + persist) under a process-wide lock. Corrupt or invalid state files are quarantined rather than trusted.+* **Decrypt only at signing time.** Chain signers decrypt the phrase in-core only when deriving a key to sign a confirmed transaction. Plaintext keys are never persisted and never serialized over the wire.++See [OS keyring & secret storage](privacy-and-security/os-keyring-and-secret-storage.md) for how secrets are stored across platforms, and [Privacy & security](privacy-and-security/) for the broader model.++***++## Reading balances and chain info++Read-only surfaces require no confirmation:++* **Status**: onboarding state plus the safe per-chain account addresses.+* **Balances**: native-asset balances per account. Note: only **EVM balances read live** today (Ethereum mainnet); BTC, Solana, and Tron call their providers but fall back to a zero balance with a "provider missing" status on error.+* **Network defaults / supported assets**: per-chain RPC and explorer URLs, capability flags, and the built-in asset catalog.+* **Chain status**: per-chain readiness and the active RPC URL.++RPC endpoints are overridable per chain/network via `OPENHUMAN_WALLET_RPC_*` environment variables. URLs are redacted to scheme + host in logs.++***++## Sending transfers: prepare → confirm → execute++Every write is a two-step, intentional flow. The wallet never sends in one shot.++1. **Prepare** (`prepare_transfer`): validates the amount, destination address, and (for tokens) calldata, estimates fees, and returns a **prepared quote** with a `quoteId`. Quotes are held in an in-memory store with a **5-minute TTL**, capped at 64, and are **not** persisted across restarts.+2. **Confirm + execute** (`execute_prepared`): requires `confirmed: true` and a valid `quoteId`. The quote is consumed atomically before broadcast so concurrent confirmations can't double-submit; on failure it's restored with a refreshed TTL so it stays retryable.++**Quote-owner binding.** Each quote is bound to the chat thread that prepared it. A quote can only be executed by the same owner that prepared it; a `quoteId` leaked into a shared channel returns an indistinguishable "not found" error rather than letting another session hijack it.++Transfers are limited to **native sends and the token standards in the table above**. Bitcoin rejects token transfers. Swaps, bridges, and generic contract calls are not available here.++***++## Transaction status tracking++After broadcast, three read-only inspectors let the agent follow a transaction by hash:++* **`tx_status`**: lifecycle state (pending / confirmed / failed / not found).+* **`tx_receipt`**: receipt details (success, fee, block).+* **`lookup_tx`**: the raw transaction payload.++***++## Agent tools and approval safety++The agent reaches the wallet through six tools:++| Tool | Purpose |+| ------------------------- | --------------------------------------- |+| `wallet_status` | Onboarding status + account addresses. |+| `wallet_chain_status` | Per-chain readiness + active RPC. |+| `wallet_prepare_transfer` | Build a validated, fee-estimated quote. |+| `wallet_tx_status` | Transaction lifecycle state by hash. |+| `wallet_tx_receipt` | Transaction receipt by hash. |+| `wallet_lookup_tx` | Raw transaction lookup by hash. |++Notice there is **no agent tool that executes a transfer.** The agent can prepare a quote, but actually moving funds (`execute_prepared`) goes through the RPC surface, where it must be explicitly confirmed and pass the owner-binding check. Combined with the prepare-then-confirm flow and the per-thread quote binding, this keeps the agent from silently spending funds.++Because these are financial actions, the shape of every write is prepare-then-confirm: a quote is bound to the conversation that asked for it, expires after five minutes, and is consumed when it executes, so two confirmations cannot double-submit. The [approval gate](approval-gate.md) is the second layer, and it only applies once you have turned the autonomy policy on, which is **off by default**. Treat every transfer as a high-stakes action and read that page before relying on the gate.++***++## See also++* [Approval gate](approval-gate.md)+* [Privacy & security](privacy-and-security/)+* [OS keyring & secret storage](privacy-and-security/os-keyring-and-secret-storage.md)diff --git a/docs/gitbooks/docs/gitbooks/en/features/workflows.md b/docs/gitbooks/docs/gitbooks/en/features/workflows.mdnew file mode 100644index 0000000000..2f6cd451cb--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/features/workflows.md@@ -0,0 +1,67 @@+---+description: >-+ Durable, visual automations built on the open-source tinyflows engine. The+ agent proposes a workflow in chat; you review it on a canvas, save it, and it+ runs on schedules or live app events, pausing f+icon: diagram-project+---++# Workflows++<figure><img src="../.gitbook/assets/workflows.png" alt=""><figcaption><p>A workflow on the visual canvas. The agent proposes the graph; you review each step and save.</p></figcaption></figure>++Chat is great for one-off asks. **Workflows** are for the things you want done _every time_: triage every new support email, file every Linear ticket that mentions your team, post a digest every Monday at 9. Heavily inspired by [n8n](https://n8n.io) and [Zapier](https://zapier.com), a workflow is a saved, typed graph of steps you can see on a canvas and that runs without you. It is backed by the open-source [tinyflows](https://github.com/tinyhumansai/tinyflows) engine and the same trust and approval machinery as the rest of OpenHuman. The difference from n8n and Zapier: you don't build the graph, the agent does.++## The agent builds it, you approve it++You don't drag boxes to get started. Describe the automation in chat, for example _"whenever a new email arrives from a customer, summarize it and post to my Slack"_, and the agent uses its `propose_workflow` tool to draft a complete workflow graph. The proposal shows up in chat as a **Workflow Proposal Card** with a plain-English summary of every step.++Three design guarantees make this safe:++* The `propose_workflow` tool **only validates and describes** a candidate graph. It can never persist or enable a flow by itself.+* Every authoring turn is propose-only by default. The usual path from a proposal to a saved workflow is you clicking **Save & enable** on the card, which calls the `flows_create` RPC directly from the app, not from the agent.+* Nothing the agent can do turns a flow **on**. `flows_set_enabled` is off its belt entirely.++Persisting is scoped to two explicit asks. `save_workflow` writes the built graph onto an **already-existing** flow, the case when _you_ started the build: the Workflows page prompt bar creates the flow first and opens the copilot on it. When there is no flow yet and you explicitly ask for one ("create this and save it"), the agent may also use `create_workflow`, or `duplicate_flow` to clone a saved flow for clone-then-edit. Both are on the `workflow_builder` agent's named tool list (`crates/openhuman-core/src/flows/agents/workflow_builder/agent.toml`), and both are force-disabled at creation: `CreateWorkflowTool` calls `flows_set_enabled(.., false)` on anything `flows_create` left enabled, and reports the flow's real state rather than the intended one if that second write fails. So a flow the agent creates is born off and stays off until you enable it, and a real test run of a saved flow always needs your confirmation first.++## What a workflow is made of++A workflow graph is built from the engine's **22 node kinds**: exactly one `trigger`, plus any mix of `agent` (a full agent turn with tools), `tool_call`, `http_request`, `code` (JavaScript or Python), `shell`, `condition`, `switch`, `transform`, `split_out`, `merge`, `output_parser`, `sub_workflow`, `memory`, `dedup`, `loop`, `spawn`, `gate`, `scatter`, `gather`, `approval`, and `void`.++The canvas palette offers fifteen of them today: `trigger`, `agent`, `tool_call`, `http_request`, `code`, `condition`, `switch`, `merge`, `split_out`, `transform`, `output_parser`, `sub_workflow`, `memory`, `dedup` and `loop`. The other seven are reachable by importing a graph. Two also have no host adapter wired yet: a `shell` node has no runner, and an `approval` node falls back to pausing the run for `flows_resume` rather than raising its own card.++A graph is usually a straight line or a fan-out, but it may also contain a **bounded loop**: a `loop` node emits on its `body` port until its `max_iterations` cap (or an optional `condition`) says stop, then emits on `done`. You close the loop by wiring the body's last node back to the `loop` node. The cap is always finite, and `on_exceeded` decides what reaching it means: `error` fails the run and names the loop, `continue` stops looping and carries the last pass's items out through `done`.++Triggers come in several kinds. The ones live today:++* **Schedule**: cron-backed; the flow fires on its schedule and re-registers itself on every app boot.+* **App event**: a live [trigger](integrations/triggers.md) from a connected integration (a new Gmail thread, a Notion change, a Linear ticket) matched by toolkit + trigger slug.+* **Manual**: a Run button on the Workflows page or the `flows_run` RPC.+* **Resume**: continuing a run that paused at an approval gate.++A per-flow dispatch lock means a schedule burst can never run the same flow twice concurrently.++## Trust, approvals, and human-in-the-loop++Every flow run executes under a dedicated trust origin (`TrustedAutomation → Workflow`). The reasoning: the flow's _actions_ (which tools it calls, which URLs it hits) are static graph configuration you approved at save time. The runtime trigger payload (a webhook body, an inbound event) stays **untrusted**: it can feed arguments into those pre-declared actions, but it can never introduce a new action.++On top of that, each flow has a **"Require approval for outbound actions"** switch. With it on, every external-effect tool or HTTP call in the run parks at the [approval gate](approval-gate.md) and waits for a real decision. The run's trust root does not auto-allow anything.++When a run pauses, you get a **Flow Approval Card** in your notifications naming the flow and the pending steps. Approve resumes the run (via `flows_resume`) exactly where it stopped. Runs are durable and checkpointed, so "later today" is fine.++## Watching it run++* **`/flows`**: the Workflows hub, showing every flow with its enabled toggle, last-run status (`completed` / `pending approval` / `failed`), and a Run button.+* **`/flows/:id`**: a read-only **canvas view** of the workflow graph, rendered as nodes and edges so you can see exactly what you approved.+* **Run Inspector**: a drawer showing each run step by step (node label, emitted output, and final status), live-polling every 2 seconds until the run finishes.+* Full **run history** is persisted per flow: status, start/finish times, pending approvals, errors, and reconstructed per-step output.++## RPC surface (for developers)++The `flows` domain (`crates/openhuman-core/src/flows/`) exposes 36 controllers under `openhuman.flows_*`, covering definitions (`create`, `get`, `list`, `update`, `delete`, `set_enabled`, `duplicate`, `validate`, `import`), runs (`run`, `resume`, `cancel`, `list_runs`, `get_run`, history), drafts and the authoring copilot. See the [Agent Harness](../developing/architecture/agent-harness.md) page for how flow runs share the tinyagents execution stack.++## See also++* [Triggers](integrations/triggers.md): the live app events that fire `app_event` workflows.+* [Approval Gate](approval-gate.md): how pending approvals are surfaced and expire.+* [Cron & Scheduling](native-tools/cron.md): one-shot and recurring agent jobs (workflows are the structured, multi-step upgrade).diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/README.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/README.mdnew file mode 100644index 0000000000..25f7507ae9--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/README.md@@ -0,0 +1,70 @@+---+description: >-+ Outcome-driven, step-by-step guides for getting a real result out of+ OpenHuman: set up an assistant, run one or several local models, protect+ sensitive data, recover a broken install, or move to a new+icon: list-check+---++# Guides++The rest of the docs explain **how OpenHuman works**. This section is about **what you want to get done**. Each guide starts from a concrete outcome ("I want a private assistant", "my install is broken", "I'm moving to a new laptop") and walks you to a working result without asking you to first understand the architecture.++You do not need to read these in order, and you do not need to be technical. Pick the guide that matches your goal.++***++## Pick your goal++| I want to… | Guide |+| --------------------------------------------------- | -------------------------------------------------------------------- |+| Set up a personal assistant from scratch | [Create my personal AI assistant](personal-assistant.md) |+| Keep model inference on my own machine | [Use OpenHuman with a local model](local-model.md) |+| Share work across several model servers I run | [Use multiple local LLM servers](multiple-local-llm-servers.md) |+| Understand what leaves my computer and what doesn't | [Keep sensitive data private](privacy-sensitive-data.md) |+| Fix an install that won't start or finish | [Recover from a failed installation](recover-failed-installation.md) |+| Move everything to a new computer | [Move OpenHuman to a new PC](move-to-new-pc.md) |+| Let the agent tidy a folder of files | [Organize my project folders](organize-project-folders.md) |+| Build a role-specific assistant (e.g. clinical) | [Create a doctor-specific assistant](doctor-assistant.md) |+| Set up a locked-down assistant for a child | [Create a safe companion for a child](child-safe-companion.md) |++***++## How to read a guide++Every guide in this section follows the same shape, so you always know where to look:++* **Prerequisites**: what you need before you start (an account, disk space, another app installed).+* **Privacy implications**: what stays on your machine and what is sent to the OpenHuman backend or a model provider for this workflow, in plain language.+* **Steps**: the actual click-by-click path.+* **Success checks**: how to confirm the workflow is actually working, not just "looks done".+* **Common failures**: the specific ways this flow breaks, and what each symptom means.+* **Recovery**: how to get unstuck without losing your data.++{% hint style="info" %}+**These guides describe the shipping desktop app.** OpenHuman is in active development; where a guide points at a Settings screen or diagnostic surface, that surface may keep improving. When a screen name and what you see disagree, trust the app and check the [release notes](https://github.com/tinyhumansai/openhuman/releases), then let us know on [Discord](https://guild.tinyhumans.ai).+{% endhint %}++## The one thing worth knowing first++OpenHuman keeps your settings, workspace files and secrets on your machine, but **your memory is stored in CortexDB**: the hosted CortexDB that TinyHumans runs (behind your account) or your own CortexDB. The managed backend also brokers sign-in, model routing, integration access, web-search proxying, and some real-time integration triggers. That split is behind most of the privacy and recovery advice in this section. If you read only one background page, read [Privacy & Security](../../features/privacy-and-security/).++Where your data physically lives on disk:++| Platform | Data folder |+| ------------- | --------------------------- |+| macOS / Linux | `~/.openhuman/` |+| Windows | `%USERPROFILE%\.openhuman\` |++Almost everything in this section (backups, recovery, migration) comes back to that one folder. Memory items are not in it: backing up or deleting the folder neither copies nor erases them.++***++## See also++* [Privacy & Security](../../features/privacy-and-security/): the trust model every guide here assumes.+* [Local AI (optional)](../../features/model-routing/local-ai.md): the config reference behind the local-model guides.+* [Memory](../../features/memory.md): what memory stores and where.+* [Getting Started](../../overview/getting-started.md): install and first run, before any guide.+* [Troubleshooting Sign-In](../../overview/troubleshooting-sign-in.md): if you cannot get past login.+* [Developing](../../developing/developing.md): building from source, for the technical reader.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/child-safe-companion.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/child-safe-companion.mdnew file mode 100644index 0000000000..d67947d845--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/child-safe-companion.md@@ -0,0 +1,98 @@+---+description: >-+ Compose OpenHuman's autonomy, approval, and content-screening controls into a+ locked-down assistant for a child, with an honest account of the limits.+icon: child+---++# Create a safe companion for a child++**Goal:** set up the most restricted, supervised version of OpenHuman you can, intended for a child to use with an adult present.++{% hint style="danger" %}+**Read this first. It is an honest warning.** OpenHuman has **no dedicated "child mode"**, no age verification, and no content filter on what the model _says_. There is no certified parental-control product here. What you _can_ do is compose the existing safety controls into a tightly locked-down setup. That reduces risk; it does not make an AI assistant a safe, unsupervised experience for a child. **Adult supervision is the control that matters most.** Do not rely on software alone.+{% endhint %}++This guide is about stacking the real controls that exist, and being clear about what they do and don't cover.++***++## Prerequisites++* OpenHuman set up on the machine the child will use. See [Create my personal AI assistant](personal-assistant.md).+* An adult who owns the account and stays involved.++## Privacy implications++* Keep it local. Use a [local model](local-model.md) so conversations aren't sent to a cloud provider, and connect **no** personal integrations.+* Do not connect a child's accounts. The safest memory is minimal memory.++## What each control actually does++| Control | What it protects against | What it does **not** do |+| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |+| **`readonly` autonomy** (needs the policy on) | The assistant taking any action (sending, writing files, running commands, or reaching the network on its own) | Doesn't filter what it _says_ |+| **Approval Gate (on)** | Any state-changing/network action slipping through without an adult's yes | Doesn't review conversation content |+| **Workspace-only + blocked system dirs** | The agent touching files outside a small folder, or any credential/system directory | Doesn't restrict what topics come up |+| **Prompt-injection screening** | Attempts (in pasted text) to hijack the assistant's instructions | Isn't a general content moderator |+| **No integrations connected** | The assistant pulling in or acting on personal data | (Nothing; not connecting is the whole control) |++The honest gap: **none of these filter the model's language or subject matter.** That gap is filled by an adult in the room and by persona instructions, not by a setting.++***++## Steps++### 1. Set the strictest autonomy tier++**Settings → Agents → Agent access:**++* Autonomy: `[autonomy] enabled = true` with `level = "readonly"` in `config.toml`. The assistant can then talk and answer, but cannot act, write files, or reach the network on its own. The policy is off by default, so this is the first thing to set.+* Keep **workspace-only** on.+* Leave the [Approval Gate](../../features/approval-gate.md) installed as a second layer. (At `readonly`, acting is blocked outright anyway.)+* Review the **auto-approve** list and remove anything you don't want running without a prompt.++### 2. Keep inference and data local++* Set up a [local model](local-model.md) (run the runtime and pull the model yourself), then **route chat and reasoning at the local provider** so conversations run on-device. Adding the provider alone does not move chat; it stays on the default cloud route until you point the chat/reasoning workloads at the local provider and confirm with a test message. Turning on `local_only` [Privacy Mode](../../features/privacy-and-security/privacy-mode.md) makes that guarantee hard.+* Connect **no** integrations. Don't sign the child's accounts in.++### 3. Write a protective persona++Edit the behavior prompt (`SOUL.md`, via the **Brain** page `/brain`) to set age-appropriate rules directly. For example: "You are talking with a child. Keep language simple and kind. Refuse and redirect anything violent, sexual, frightening, or unsafe. Never give instructions that could cause harm. Encourage them to ask a parent." Persona instructions are your main lever over _content_, since there's no built-in filter.++### 4. Supervise, and test first++* Sit with the child, at least at first.+* Before handing it over, **try to break it yourself**: ask it things a child might, and confirm the persona redirects appropriately.++***++## Success checks++* [ ] `[autonomy] enabled = true` and `level = "readonly"`; `workspace_only` is on.+* [ ] No integrations are connected.+* [ ] Inference is local (`ready`), so conversations aren't going to a cloud provider.+* [ ] In your own testing, the persona refuses and redirects unsafe prompts.+* [ ] An adult is present for use. _(This is a check, not a nicety.)_++## Common failures++| Symptom | Cause | Fix |+| ---------------------------------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------- |+| It produced content you consider inappropriate | There is no content filter; the persona alone governs tone | Strengthen the `SOUL.md` rules; supervise; this is an inherent limit of the tool |+| It tried to do something (send/open/fetch) | The policy is off, or the tier isn't `readonly` | Set `enabled = true` and `level = "readonly"` in `config.toml` |+| Conversation went to the cloud | Chat isn't routed to a local provider | Route chat to a [local model](local-model.md) and send a test message |+| The child reached settings and changed things | OpenHuman has no separate child login | Use OS-level user accounts/parental controls to lock down the machine itself |++## Recovery++* **Instant lockdown:** set `enabled = true` and `level = "readonly"` (if either drifted). The level does nothing while `enabled` is `false`, so check both. Acting stops next turn.+* **Reset persona:** revert your `SOUL.md` edits to defaults if the customization misbehaves.+* **The real recovery is supervision.** If the experience isn't right for the child, step in. No software setting substitutes for that.++## See also++* [Keep sensitive data private](privacy-sensitive-data.md): the controls this guide stacks.+* [Approval Gate](../../features/approval-gate.md): the autonomy tiers and what each one blocks.+* [Privacy & Security](../../features/privacy-and-security/): what leaves the machine, and what does not.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/doctor-assistant.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/doctor-assistant.mdnew file mode 100644index 0000000000..92e19e913d--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/doctor-assistant.md@@ -0,0 +1,93 @@+---+description: >-+ Shape OpenHuman into a role-specific assistant for clinical work: persona,+ tight data boundaries, and the limits you must keep in mind.+icon: user-doctor+---++# Create a doctor-specific assistant++**Goal:** tailor OpenHuman for a clinician's workflow: a persona that speaks the part, memory scoped to the right sources, and privacy settings appropriate for sensitive information.++{% hint style="danger" %}+**Read this first.** OpenHuman is a general-purpose assistant, **not** a medical device and **not** a source of medical advice. It can hallucinate. Nothing here makes it safe for diagnosis, treatment decisions, or handling protected health information under a specific regulatory regime (HIPAA, GDPR, etc.). You are responsible for compliance, for clinical judgment, and for what data you let it touch. Treat its output as draft text a qualified human must verify.+{% endhint %}++With that boundary set, here's how to shape it responsibly.++***++## Prerequisites++* OpenHuman set up. See [Create my personal AI assistant](personal-assistant.md).+* A clear decision about **what data this assistant may and may not see**. For anything sensitive, plan to keep inference [local](local-model.md).++## Privacy implications++* Decide early whether any real patient data will ever be involved. If regulatory rules apply to your data, the safest posture is: **local model on, minimal integrations, read-only or supervised autonomy.**+* OpenHuman keeps memory local and redacts secrets/PII on save, but **that is not a compliance guarantee**. It is a general privacy design. Do not treat it as certified for regulated health data.+* If you route reasoning to the [OpenHuman backend](../../features/privacy-and-security/) (the default), relevant snippets are sent to the model provider for each turn. For sensitive material, turn on a [local model](local-model.md) so that work stays on-device.++***++## Steps++### 1. Lock down the boundaries before adding data++In **Settings → Agents → Agent access**:++* Turn the autonomy policy on and set its tier: `[autonomy] enabled = true` with `level = "readonly"` (pure Q\&A and drafting) or `level = "supervised"` (drafting plus approved actions) in `config.toml`. Avoid `full` for clinical use. The policy is off until you set `enabled = true`.+* Keep **workspace-only** on so the agent can't wander your disk.+* With the policy on, the [Approval Gate](../../features/approval-gate.md) stands between the assistant and any acting call: at `readonly` the tier refuses the call outright, and at `supervised` the gate parks it for your yes, unless its tool is on the always-allow list. Clear that list in **Settings → Agent access** if you want every call reviewed. Note the gate covers **actions**, not network transport: prompts and attachments can still be sent upstream for inference.++### 2. Turn on local inference for sensitive work++Follow [Use OpenHuman with a local model](local-model.md) and pick at least **"memory + reflection"** so embeddings and background summarization stay on-device. Confirm status reads `ready`.++### 3. Give it a clinical persona++The assistant's tone and behavior come from an editable prompt (`SOUL.md`), with mission/values in `IDENTITY.md`. To make it clinical:++* Set a display name and description in **Settings → Personality**.+* Edit the behavior prompt (via the **Brain** page, `/brain`) to describe the role you want. For example: "You assist a physician with documentation and literature summaries. You always flag uncertainty, cite sources, and never present output as a diagnosis or treatment recommendation. You remind the user to verify clinically."++Bake the caveats **into the persona** so they show up in every reply, not just your memory.++### 4. Connect only the sources that belong++Add only the integrations relevant to the workflow (e.g. a reference/notes source), and **not** anything carrying data you're not cleared to process. Every integration is a separate, revocable OAuth grant.++### 5. Verify behavior with safe, synthetic inputs++Test with **made-up** cases, never real patient data, until you're satisfied with tone, caution, and citations.++***++## Success checks++* [ ] `[autonomy] enabled = true`, `level` is `readonly` or `supervised`, and `workspace_only` is on.+* [ ] If you're keeping inference on-device, your local runtime is running, the models are pulled, and a turn routed to it answers.+* [ ] The persona reliably adds uncertainty flags and "verify clinically" language in replies to synthetic prompts.+* [ ] Only intended sources are connected.+* [ ] The assistant declines to present output as a diagnosis when tested.++## Common failures++| Symptom | Cause | Fix |+| ------------------------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- |+| It states things with false confidence | Persona doesn't enforce caution | Strengthen `SOUL.md` to require uncertainty flags and citations |+| Sensitive text went to the cloud | Inference is on the default route | Turn on a [local model](local-model.md) and confirm `ready` before using sensitive input |+| It tried to take an action on its own | The policy is off, or the tier is too permissive | Set `enabled = true` and `level = "readonly"` |+| It "remembered" something it shouldn't have | A source with disallowed data was connected | Revoke the integration; already-ingested chunks are local and can be cleared from the workspace |++## Recovery++* **Instant containment:** set `enabled = true` and `level = "readonly"` together. The level is inert while the policy is off, so both have to be set. Acting stops on the next turn.+* **Pull a source:** revoke any integration from Settings; future syncs stop immediately.+* **Reset the persona:** the behavior lives in an editable file; revert your edits to return to default tone.++## See also++* [Keep sensitive data private](privacy-sensitive-data.md): the controls this guide composes.+* [Use OpenHuman with a local model](local-model.md): keeping sensitive inference on-device.+* [Approval Gate](../../features/approval-gate.md): how actions are gated.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/local-model.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/local-model.mdnew file mode 100644index 0000000000..b528aac14b--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/local-model.md@@ -0,0 +1,117 @@+---+description: >-+ Run a local model runtime yourself (Ollama, LM Studio, MLX, or any+ OpenAI-compatible server), pull your own models, and add the endpoint to+ OpenHuman as a provider. Includes checks and common failures+icon: microchip+---++# Use OpenHuman with a local model++**Goal:** move some or all of OpenHuman's model work onto your own computer, so that the data used for those workloads never leaves the machine.++OpenHuman does not install a runtime, start it, or download models. You run the runtime, you pull the models, and OpenHuman calls the endpoint you give it. Local AI is **opt-in**; adding a local provider does not reroute anything until you point workloads at it.++For the config reference (provider strings, endpoint overrides, every workload field), see [Local AI (optional)](../../features/model-routing/local-ai.md). This guide is the task-oriented version.++***++## Prerequisites++* A local runtime you install and run yourself:+ * [**Ollama**](https://ollama.com), default address `http://localhost:11434`.+ * [**LM Studio**](https://lmstudio.ai) with its local server enabled, default `http://localhost:1234/v1`.+ * MLX (`mlx_lm.server`), OMLX, or any other OpenAI-compatible server.+* Disk and RAM for the models you pick. A small chat model plus `bge-m3` for embeddings is a few GB on disk; 8 GB+ RAM is a sensible floor.++## Privacy implications++* Workloads you route locally run on-device. Nothing about that work is sent out.+* Anything you leave on the default route still goes through the OpenHuman [model router](../../features/model-routing/). Local AI only changes the workloads you move.+* Without [Privacy Mode](../../features/privacy-and-security/privacy-mode.md), lightweight hints routed locally can fall back to the remote provider if the runtime is unreachable. Turn on `local_only` privacy mode if strict locality matters; then an unreachable runtime makes the request fail instead.++***++## Steps++### 1. Start the runtime++Install and launch the runtime so its server is running. For Ollama, confirm from a terminal:++```bash+curl http://localhost:11434/api/tags+```++A JSON list of models (even an empty one) means the server is reachable. For LM Studio or another OpenAI-compatible server, `curl http://localhost:1234/v1/models` (adjust the port) should return a model list.++### 2. Pull the models yourself++OpenHuman never pulls models. Pull every model you plan to route to before you configure it. For Ollama:++```bash+ollama pull gemma3:4b-it-qat # chat, and vision from 4B up+ollama pull bge-m3 # memory embeddings (1024 dimensions)+```++In LM Studio, download the model in LM Studio and load it. For MLX or another server, start it with the model you want served.++See [Local models & bring your own key](../../features/model-routing/local-and-byok-models.md) for which models can do chat, vision, and embeddings.++### 3. Add the endpoint as a provider++Open **Connections → LLM** and choose **Add a provider**:++* For Ollama, LM Studio, or OMLX, pick it under **Local runtimes**. The default endpoint is filled in; change it if your runtime listens elsewhere.+* For MLX or another server, choose **Add a custom provider** and enter its OpenAI-compatible endpoint (for example `http://127.0.0.1:8080/v1`).++When you save, OpenHuman asks the endpoint for its model list. If the runtime isn't reachable, the provider isn't saved; fix step 1 and try again.++### 4. Route workloads to it++Use **Custom routing** on the workloads you want local (chat, reasoning, vision, and so on) and pick a model the runtime reported. Only models you have pulled or loaded appear.++For memory embeddings, open **Connections → Embeddings** and choose Ollama with `bge-m3`, or set `embeddings_provider = "ollama:bge-m3"` in `config.toml`.++### 5. Test that it answers++Send a short message on a workload you routed locally, or use the model test in the LLM panel. A coherent reply means the path works end to end (endpoint reachable, model present, inference running). For Ollama you can also watch `ollama ps` while the request runs.++***++## Success checks++Local AI is working when:++* [ ] The local provider shows as connected under **Connections → LLM**, and its model list contains the models you pulled.+* [ ] A turn routed to the local provider returns a real reply.+* [ ] For embeddings: after the next memory sync, new summaries keep appearing in the **Memory** tab with the runtime running.++## Common failures++| What you see | Meaning | Fix |+| --------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |+| Provider won't save; the endpoint is reported unreachable | OpenHuman can't reach the runtime at that address | Start the runtime; check the port with `curl`; correct the endpoint |+| The model you want isn't in the picker | The runtime doesn't have it | `ollama pull <model>`, or download and load it in LM Studio, then reopen the picker |+| A request fails saying the model is not found | The workload names a model the runtime no longer has | Pull it again, or route the workload to a model you have |+| Ollama answers but every model call fails | Ollama's model runner is broken | Quit and relaunch Ollama, then retry |+| Embeddings fail with a dimension error | The embedding model doesn't produce 1024-dimension vectors | Use `bge-m3` |+| Agent turns lose context on Ollama | Ollama's default context window is small | Set `local_ai.num_ctx` (for example `8192`) |+| Answers feel cloud-quality | The runtime was unreachable and a lightweight hint fell back to remote | Fix reachability; use `local_only` privacy mode if fallback is unacceptable |++## Recovery++* **Back to cloud:** set the routed workloads back to the default route in **Custom routing**, or remove the local provider. No data is lost.+* **Stuck runtime:** quit the runtime fully and relaunch it. OpenHuman reconnects on the next request.+* **Disk pressure:** model pulls happen in your runtime, not in OpenHuman. Free space and pull again with the runtime's own command.++***++## Notes on what stays cloud anyway++Some workloads use the backend unless you configure something else: speech-to-text and web search go through the backend proxy, and text-to-speech uses the hosted voice unless you install Piper yourself and set `PIPER_BIN`. See [what stays in the cloud](../../features/model-routing/local-ai.md#what-stays-in-the-cloud-by-default).++## See also++* [Local AI (optional)](../../features/model-routing/local-ai.md): the config reference.+* [Keep sensitive data private](privacy-sensitive-data.md): the plain-language version of local vs external.+* [Automatic Model Routing](../../features/model-routing/): how tasks get matched to models.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/move-to-new-pc.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/move-to-new-pc.mdnew file mode 100644index 0000000000..a5a52daadd--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/move-to-new-pc.md@@ -0,0 +1,122 @@+---+description: >-+ Carry your OpenHuman persona, memory, workspace, and model/provider config to+ a new computer, and understand which secrets travel and which you re-enter.+icon: truck+---++# Move OpenHuman to a new PC++**Goal:** set up OpenHuman on a new machine so it picks up where the old one left off (same memory, same persona, same settings), with credentials handled at a safe level of detail.++The short version: **copy one folder, sign back in.** The nuance is in what a folder copy does and does not carry, which this guide makes explicit so you're not surprised.++***++## Prerequisites++* Both computers available (or a backup of the old one's data folder).+* Your OpenHuman sign-in credentials.+* A way to move files between them (external drive, secure file transfer, etc.).++## What lives where++Everything OpenHuman persists is in a single folder:++| Platform | Data folder |+| ------------- | --------------------------- |+| macOS / Linux | `~/.openhuman/` |+| Windows | `%USERPROFILE%\.openhuman\` |++Inside it, the things you care about migrating:++| What | Where (inside the data folder) | Travels with a folder copy? |+| ------------------------------------------------------ | --------------------------------------------- | -------------------------------- |+| **Memory items** | In your engine (TinyHumans or CortexDB) | Sign in again / re-enter the key |+| **Persona & behavior** | `SOUL.md`, `IDENTITY.md`, `ROLE.md` | Yes |+| **Config** (models, providers, routing, autonomy) | `config.toml` | Yes |+| **Session history** | `sessions/`, `session_raw/` | Yes |+| **Approval history** | `approval/approval.db` | Yes |+| **OS-stored secrets** (session token, some local keys) | Your OS keychain, **not** in this folder | No (re-established on sign-in) |+| **Integration access** (Gmail, Slack, …) | Brokered by the backend, tied to your account | No (reconnects on sign-in) |++{% hint style="info" %}+**Why some things don't travel, and why that's fine.** OpenHuman deliberately keeps secrets out of loose files. Your session token and certain local secrets live in the operating system's secure store (Keychain / Credential Manager / Secret Service), and your integration tokens are held by the backend against your account. So the folder copy carries your _data and persona_; **signing in on the new machine re-establishes the secrets and integrations.** You never hand-copy raw tokens between machines.+{% endhint %}++***++## Steps++### 1. Quit OpenHuman on the old machine++Fully close the app so nothing is mid-write to the database. A clean copy needs a quiet source.++### 2. Copy the data folder++Copy the **entire** data folder from the old machine to the same location on the new one:++* macOS / Linux: copy `~/.openhuman/` → `~/.openhuman/`+* Windows: copy `%USERPROFILE%\.openhuman\` → `%USERPROFILE%\.openhuman\`++Copy the whole folder rather than cherry-picking. It keeps memory, persona, config, and history consistent with each other.++The data folder holds config and memory but **not** the files the agent created or edited in its action sandbox. Also copy your **projects/action folder**, by default `~/OpenHuman/projects` (or wherever you pointed the action directory). Otherwise those project files stay behind on the old PC. That folder also holds `Files` (`~/OpenHuman/projects/Files`), where the decks, documents and generated images and videos the agent delivers are saved.++{% hint style="warning" %}+Copy it somewhere secure. This folder contains your personal memory in readable form. Treat the transfer like moving personal documents.+{% endhint %}++### 3. Install OpenHuman on the new machine++Install the current build from [tinyhumans.ai/openhuman](https://tinyhumans.ai/openhuman). If the data folder is already in place, the app will find it on launch. (Order doesn't strictly matter; installing first and copying after works too, as long as the app isn't running while you copy.)++### 4. Launch and sign in++Open the app and sign in with the **same account**. Signing in:++* Re-establishes your session token in the new machine's OS keychain.+* Reconnects your account so backend-brokered integrations come back.++### 5. Reconnect anything account-scoped++* **Integrations** (Gmail, Slack, etc.): confirm they show as connected under **Settings**. If any need a fresh OAuth approval, re-approve them. Each takes a quick click.+* **Bring-your-own keys:** if you had entered your own provider API key, a Composio direct key, or similar **local** secrets, re-enter them on the new machine. Those are stored in the OS keychain and don't come across in the folder.++### 6. Re-check model / provider config++Your `config.toml` came along, so model routing and provider choices should already match. If you used a [local model](local-model.md), remember that **Ollama/LM Studio is separate software** and the model weights live in its own store, not in the OpenHuman data folder. Install the runtime on the new machine and pull the same models yourself (for example `ollama pull bge-m3`); OpenHuman does not download them.++***++## Success checks++The migration worked when:++* [ ] The **Memory** tab on the new machine shows your existing summaries. Your memory came across.+* [ ] The assistant replies in your configured style, and your display name/persona is intact.+* [ ] Connected integrations show as connected under **Settings** (reconnect any that don't).+* [ ] Your autonomy tier and settings match what you had (check **Settings → Agents → Agent access**).+* [ ] If you use local AI: the runtime is installed and running on the new machine, you have pulled the models your workloads name, and a turn routed to the local provider answers.++## Common failures++| Symptom | Cause | Fix |+| ------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |+| New machine starts fresh, no memory | Data folder wasn't in the right place, or app was running during the copy | Quit the app, place the folder at `~/.openhuman/` (or `%USERPROFILE%\.openhuman\`), relaunch |+| Signed in but integrations are disconnected | Integration access is account/backend-scoped, not in the folder | Reconnect each integration in Settings (one OAuth click each) |+| Local model doesn't work on the new PC | Ollama/LM Studio and the weights aren't on the new machine | Install the runtime and pull the models yourself; see [local model guide](local-model.md) |+| Assistant lost its personality | `SOUL.md` / `IDENTITY.md` weren't copied | Copy the **whole** data folder, not just the database |+| Sign-in stalls on the new machine | An auth/handler issue unrelated to migration | See [Troubleshooting Sign-In](../../overview/troubleshooting-sign-in.md) |++## Recovery++* **Keep the old machine's folder until you've verified the new one.** Don't wipe the source until every success check passes.+* If the new machine won't start at all, treat it as a fresh-install problem: [Recover from a failed installation](recover-failed-installation.md). Your copied folder is safe to move aside and restore.++## See also++* [Recover from a failed installation](recover-failed-installation.md): same data folder, different problem.+* [Keep sensitive data private](privacy-sensitive-data.md): why secrets are stored the way they are.+* [Use OpenHuman with a local model](local-model.md): re-standing-up a runtime on the new machine.+* [OS Keyring & Secret Storage](../../features/privacy-and-security/os-keyring-and-secret-storage.md): what the keychain holds instead of the folder.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/multiple-local-llm-servers.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/multiple-local-llm-servers.mdnew file mode 100644index 0000000000..c595576507--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/multiple-local-llm-servers.md@@ -0,0 +1,152 @@+---+description: >-+ Route different OpenHuman workloads to models on different machines you own,+ behind one OpenAI-compatible gateway, with a Mac mini and Linux GPU PC worked+ example.+icon: network-wired+---++# Use multiple local LLM servers++**Goal:** keep a small, fast model and a large, slow one on separate machines you own, and send each OpenHuman workload to the right one, without giving up the local provider path.++OpenHuman talks to one endpoint per provider string. If your models live on more than one machine, put a gateway in front of them: it exposes a single OpenAI-compatible endpoint and uses a prefix on the model ID to choose the upstream. This guide uses [Model Router](https://github.com/tjm8874/model-router), an independent, MIT-licensed community project. OpenHuman does not bundle, install, or supervise it, and any compatible gateway can play the same part.++The worked example puts the OpenHuman core, the gateway, and a small model on a **Mac mini**, and a larger model server on a **Linux GPU PC**:++```+OpenHuman core (Mac mini)+ └─ gateway, 127.0.0.1:18080/v1+ ├─ MacMini:small-model → local model server, 127.0.0.1:8080/v1+ └─ LinuxGPU:large-model → SSH tunnel → Linux PC, 127.0.0.1:8000/v1+```++***++## Prerequisites++* A single-server local setup you already understand. Start with [Use OpenHuman with a local model](local-model.md) if you have not routed one workload locally yet.+* An OpenAI-compatible model server on each machine, which you install, start, and load models into yourself. OpenHuman does not do any of that, and neither does the gateway.+* Enough memory and context headroom on each machine for the models you pick, including KV-cache and whatever concurrency you expect.+* SSH access from the machine running the core to each remote machine.++## Privacy implications++* A loopback gateway is not the same thing as on-device inference. The gateway listens on `127.0.0.1`, but it forwards prompts to whatever upstream its own config names, which may be another machine.+* OpenHuman classifies the `local-openai:` prefix as a local runtime and does not inspect the gateway's upstreams, so `local_only` privacy mode will not stop a prompt that the gateway relays off the box. Review those destinations yourself.+* Keep authenticated remote inference behind SSH or HTTPS. Do not send bearer keys over plain HTTP across a network.+* Changing inference destinations does not move the core's workspace, memory, or project files. Those stay where they were.++***++## Steps++### 1. Start the model servers++Run the small model on the Mac mini at `http://127.0.0.1:8080/v1`, for example under MLX or LM Studio. Run the larger model on the Linux PC at that machine's `http://127.0.0.1:8000/v1`, for example under vLLM. Use each runtime's own install and model-loading instructions.++Then, on the Mac mini, forward the Linux endpoint over SSH and keep the tunnel up:++```sh+ssh -N -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 \+ -L 127.0.0.1:18000:127.0.0.1:8000 [email protected]+```++The Linux server is now reachable as `http://127.0.0.1:18000/v1` on the Mac mini.++### 2. Start the gateway++Build and run the gateway following its own README. The backend mapping for this example looks like:++```toml+[server]+host = "127.0.0.1"+port = 18080++[backends.MacMini]+base_url = "http://127.0.0.1:8080/v1"+endpoints = ["chat/completions"]++[backends.LinuxGPU]+base_url = "http://127.0.0.1:18000/v1"+endpoints = ["chat/completions"]+# For an authenticated upstream, name an environment variable the gateway reads:+# api_key_env = "LINUX_LLM_API_KEY"+```++Check the config, start it, and read back the catalogue:++```sh+model-router --config router.toml --check-config+model-router --config router.toml+curl http://127.0.0.1:18080/v1/models+```++Use the binary's real path if it is not on `PATH`. A config check does not contact the upstreams, so read `router_errors` as well as `data`: one reachable backend does not mean every backend is ready. The catalogue prefixes each upstream model ID with its backend name, so `org/model:4bit` on the Mac mini appears as `MacMini:org/model:4bit`. Colons and slashes inside the upstream ID are left alone.++### 3. Point OpenHuman at the gateway++Merge the following into the active user's `config.toml`, keeping your other settings. Replace the placeholder model IDs with exact IDs from the gateway catalogue, and keep the workload keys at the top level, **before** the `[local_ai]` table, or TOML will read them as part of it:++```toml+chat_provider = "local-openai:MacMini:your-small-model-id"+memory_provider = "local-openai:MacMini:your-small-model-id"+reasoning_provider = "local-openai:LinuxGPU:your-large-model-id"+agentic_provider = "local-openai:LinuxGPU:your-large-model-id"+coding_provider = "local-openai:LinuxGPU:your-large-model-id"++[local_ai]+runtime_enabled = true+opt_in_confirmed = true+provider = "lm_studio"+base_url = "http://127.0.0.1:18080/v1"+chat_model_id = "MacMini:your-small-model-id"+vision_model_id = ""+```++Three things are worth being precise about:++| Key | What it actually does here |+| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `local-openai:` prefix | Selects OpenHuman's generic OpenAI-compatible runtime (`crates/openhuman-core/src/inference/provider/factory/local_runtime.rs`). The rest of the string is passed to the endpoint unchanged, so `MacMini:your-small-model-id` reaches the gateway intact and the gateway strips `MacMini:` before forwarding. |+| `local_ai.base_url` | The endpoint every `local-openai:` route falls back to. This is what points OpenHuman at the gateway. |+| `local_ai.provider` | Selects which runtime the Local AI settings page talks to. It does not affect a `local-openai:` route, where the prefix decides. `lm_studio` is simply the existing identifier for a local OpenAI-compatible server. |++`OPENHUMAN_LOCAL_INFERENCE_URL` and then `LOCAL_OPENAI_URL` in the core's environment both take priority over `local_ai.base_url`, so update or unset them when you change endpoints. The full precedence order is in [Local AI](../../features/model-routing/local-ai.md#supported-runtimes).++Assign vision only to a vision-capable model, through `vision_provider` and `local_ai.vision_model_id`. This example is text-only and leaves vision and embeddings on their existing routes. Embeddings and the memory engine are configured separately, and adding a gateway does not reroute them: a gateway can forward an embeddings path to a compatible service, but it does not translate between APIs or start anything. Any workload you do not assign keeps the route it had.++### 4. Verify each route++Send a short chat message, which should land on the small model, then run a reasoning or agentic turn, which should land on the large one. Confirm the backend and model in the gateway's logs and the reply in OpenHuman. Model discovery and a `/health` probe are not proof of inference. If your models support streaming and tool calls, exercise both.++***++## Success checks++* [ ] `curl http://127.0.0.1:18080/v1/models` lists models from every backend, with no entries in `router_errors`.+* [ ] A chat turn answers, and the gateway log shows the Mac mini backend.+* [ ] A reasoning or agentic turn answers, and the gateway log shows the Linux backend.+* [ ] Killing the SSH tunnel makes the large-model workload fail rather than silently answer from somewhere else.++## Common failures++| What you see | Meaning | Fix |+| ----------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |+| The model is not found | The workload names an ID that is not in the gateway catalogue | Copy the exact prefixed ID from `/v1/models` |+| Only one backend answers | The other upstream is down, or its tunnel dropped | Check `router_errors`, then restart the server or the tunnel |+| Every local route hits the wrong endpoint | An environment override is still set | Unset `OPENHUMAN_LOCAL_INFERENCE_URL` and `LOCAL_OPENAI_URL`, or point them at the gateway |+| Workload keys are ignored | They were written after `[local_ai]`, so TOML read them as part of that table | Move them above the table |++## Keeping it up++Run the gateway under a per-user LaunchAgent or a systemd user service if you need it always available, and supervise the SSH tunnel separately. Re-check the gateway config and restart it after every change. This gateway returns an error on an upstream failure: there is no automatic retry and no fallback, which is the behaviour you want when the alternative is a silent reroute.++The gateway listens only on loopback and has no inbound authentication of its own. It keeps upstream keys separate from the core's own `Authorization` header.++## Next steps++* [Use OpenHuman with a local model](local-model.md): the single-server version of this setup.+* [Local AI (optional)](../../features/model-routing/local-ai.md): provider strings, endpoint precedence, and every `local_ai` field.+* [Privacy Mode](../../features/privacy-and-security/privacy-mode.md): why `local_only` cannot vouch for a gateway's upstreams.+* [Keep sensitive data private](privacy-sensitive-data.md): the broader picture of what leaves your machines.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/organize-project-folders.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/organize-project-folders.mdnew file mode 100644index 0000000000..1c573c6cb8--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/organize-project-folders.md@@ -0,0 +1,96 @@+---+description: >-+ Let OpenHuman tidy, rename, and restructure a folder of files safely, inside a+ boundary you set, with changes gated by your approval once the autonomy policy+ is on at the supervised tier.+icon: folder-tree+---++# Organize my project folders++**Goal:** point the assistant at a folder and have it clean it up (sort files, rename consistently, remove clutter) without letting it roam your whole disk or make changes you didn't see.++The core idea: the agent works inside a **boundary you define**, and with the autonomy policy on at the `supervised` tier, any file change that isn't provably read-only is **parked for your approval** before it runs. The tier is what decides that: at `full`, routine writes run on their own and only network, install and destructive actions stop to ask.++***++## Prerequisites++* OpenHuman set up. See [Create my personal AI assistant](personal-assistant.md).+* A specific folder you want organized. Ideally, make a copy first if the contents are irreplaceable.++## Privacy implications++* File organizing is **local**. Reading, moving, and renaming files happens on your machine.+* If you ask the agent to _reason about_ file contents (e.g. "group these by topic"), it may send relevant snippets to the model to do that. Route inference to a [local model](local-model.md) if you want that reasoning on-device too.+* The agent cannot touch system or credential folders (`~/.ssh`, `~/.gnupg`, `~/.aws`, OS directories). Those are blocked outright regardless of settings.++***++## Steps++### 1. Decide where the agent may act++{% hint style="warning" %}+Everything in this step needs the autonomy policy switched on. It is **off by default**: set `[autonomy] enabled = true` in `config.toml` (`~/.openhuman/config.toml`, or `%USERPROFILE%\.openhuman\config.toml` on Windows). Without it, trusted roots, `workspace_only` and the approval gate are all inert and acting tool calls run unprompted. Credential stores and system roots stay blocked either way.+{% endhint %}++Confinement to the working folder has two preconditions: the policy enabled, and `workspace_only` on. With both, the agent's read/write root is its working folder and it has no ambient access to the rest of your disk. With either one off, that boundary is not enforced.++A **trusted root** is the deliberate exception. Each one grants its subtree even though it sits outside the working folder, taking precedence over `workspace_only`. To let the agent work on a folder elsewhere, add that folder as a trusted root:++* Open **Settings → Agent access**.+* Add the target folder as a trusted root with read-write access.++Keep the boundary as tight as the task: grant the one folder, not your home directory.++### 2. Set the right autonomy tier++In the same `[autonomy]` block, `level` decides how much runs without asking:++* `supervised` _(recommended)_: the agent proposes each change and you approve moves, renames and deletes as they come, except where you have already put the tool on the always-allow list.+* `full`: routine file writes run automatically. Still tighten the trusted root so "automatic" stays contained.++Deleting and moving files are state-changing actions, so with `supervised` they are parked for your yes or no by the [Approval Gate](../../features/approval-gate.md). Answering **Always allow** to a prompt adds that tool to the always-allow list, and from then on its calls run without a fresh approval. Remove it from the list in **Settings → Agent access** when you want each call reviewed again.++### 3. Ask for the reorganization++Be concrete about the folder and the rules. For example:++* "In my trusted `~/Documents/receipts` folder, rename every file to `YYYY-MM-DD-vendor.pdf` based on its contents, and move anything older than 2023 into an `archive/` subfolder."+* "Group the loose files in this folder into subfolders by type, and show me the plan before doing anything."++### 4. Review each proposed action++When the agent wants to move, rename, or delete, an **Approval Request card** appears with the exact action. **Approve** one, **Always allow** a repetitive safe one, or **Deny**. You can also just type **yes** / **no**.++***++## Success checks++* [ ] The policy is enabled and `workspace_only` is on, so the folder boundary is actually being enforced.+* [ ] The agent only touched the folder you granted, and nothing outside your working folder and trusted roots changed.+* [ ] Each move/rename/delete showed up as an approval prompt (unless you chose "Always allow" for that tool).+* [ ] The folder matches the structure you asked for.+* [ ] Files you didn't mention are untouched.++## Common failures++| Symptom | Cause | Fix |+| ----------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| "I can't access that folder" | The folder isn't a trusted root, or `workspace_only` is confining the agent | Add it in **Settings → Agent access** as a read-write trusted root |+| It asks for approval on every single file | The `supervised` tier gates each write | Use **Always allow** for the specific safe tool, or narrow the request so there are fewer actions |+| It refuses to touch a path | The path is a blocked system/credential directory | That's by design; those paths are never accessible. Choose a normal working folder |+| It reorganized more than you wanted | The instruction was broad | Ask it to "show the plan first"; approve selectively |++## Recovery++* **Nothing runs without approval** at the `supervised` tier, apart from the tools on your always-allow list. If a plan looks wrong, **Deny** and it doesn't happen.+* **Undo is manual.** OpenHuman doesn't roll file operations back for you, so work on a **copy** of anything precious, or keep the folder under version control (e.g. `git`) so you can revert.+* If the agent is doing too much, set both `enabled = true` and `level = "readonly"`. The level does nothing on its own: with `enabled = false` the whole policy is inert. With both set, the agent can still suggest a plan but can't change files.++## See also++* [Approval Gate](../../features/approval-gate.md): exactly what gets parked and why.+* [Coder toolset](../../features/native-tools/coder.md): the filesystem/git tools the agent uses here.+* [Privacy & Security](../../features/privacy-and-security/): workspace scoping and path hardening.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/personal-assistant.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/personal-assistant.mdnew file mode 100644index 0000000000..aed573c229--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/personal-assistant.md@@ -0,0 +1,128 @@+---+description: >-+ Go from a fresh install to a working personal assistant that knows your+ context, respects the boundaries you set, and, at the supervised tier, acts+ only with your approval.+icon: robot+---++# Create my personal AI assistant++**Goal:** a working assistant that has some memory of your world, replies in a style you like, and, once you put it on the supervised tier, takes no real-world action without your say-so.++This is the "start here" guide. It assumes nothing beyond a downloaded app.++***++## Prerequisites++* OpenHuman installed on macOS, Windows, or Linux. If you haven't installed yet, do [Getting Started](../../overview/getting-started.md) first, then come back.+* 4 GB+ RAM (16 GB+ if you plan to connect very large mailboxes or run a [local model](local-model.md)).+* An account to sign in with (social login works).+* Optional: one account you'd like the assistant to know about (Gmail is the usual first one).++## Privacy implications++* Signing in **does not** grant ongoing access to anything. Every integration is a separate, explicit OAuth approval you can revoke later.+* Your memory is stored by the engine you choose: hosted TinyHumans or your own CortexDB. With neither, memory is off.+* By default, chat/reasoning runs through the OpenHuman-hosted [model router](../../features/model-routing/). If you want inference on-device instead, see [Use OpenHuman with a local model](local-model.md).+* Full detail: [Keep sensitive data private](privacy-sensitive-data.md).++***++## Steps++### 1. Sign in++Launch the app. The first screen is **"Sign in! Let's Cook"**. Choose a login option. There is an **Advanced** panel for pointing at a custom core; most people ignore it.++### 2. Choose how AI runs++After sign-in you'll hit a **runtime choice**:++* **Cloud**: one click, and the hosted model router handles inference. This is the fastest path to a working assistant.+* **Custom**: walk through choosing your inference provider, voice, integrations (OAuth), web search, and embeddings yourself.++If you're not sure, pick **Cloud**. You can change any of this later in **Settings**.++### 3. Give it something to remember++An assistant with no memory is just a chatbot. Connect at least one source so it has context to draw on:++* Open **Settings** and connect an integration (Gmail is the common starting point). Each connection is a one-click OAuth approval.+* Add folders, files or links as sources under **Connections → Memory** so they sync into [Memory](../../features/memory.md) on a schedule.++### 4. Set your boundaries++Open `config.toml` in your data folder (`~/.openhuman/config.toml`, or `%USERPROFILE%\.openhuman\config.toml` on Windows) and turn the policy on:++```toml+[autonomy]+enabled = true+level = "supervised" # "readonly" | "supervised" | "full"+```++| Tier | What it means |+| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `readonly` | The assistant can observe and answer, but never acts (no sending, no file writes, no commands). |+| `supervised` | It can act, but any state-changing, network, install, or destructive action is **parked for your approval** first, unless its tool is on your always-allow list. |+| `full` | Routine actions run automatically; network, install and destructive actions still ask. |++{% hint style="warning" %}+**The policy is off until you set `enabled = true`.** It is not on out of the box, and there is no user-facing switch for the tier: the panel that holds the radios is a developer-only deep link. Until you turn it on, acting tool calls run without a prompt. Credential stores (`~/.ssh`, `~/.gnupg`, `~/.aws`) and system roots stay blocked either way.+{% endhint %}++`supervised` is the right starting point. With it on, nothing with an external effect happens in a chat without you saying yes: that is the [Approval Gate](../../features/approval-gate.md). The one exception is a tool you put on the always-allow list, by answering **Always allow** to a prompt. That tool runs from then on without a fresh approval. Remove it from the list in **Settings → Agent access** when you want per-call review back.++**Settings → Agent access** holds the rest of the boundary once the policy is on: the trusted roots, the always-allow list, the action timeout and the workspace-only switch.++### 5. Shape its personality (optional)++How the assistant talks and behaves is defined by an editable prompt called **`SOUL.md`** (its mission and values live in a companion **`IDENTITY.md`**). You don't have to touch these (they ship with sensible defaults), but you can:++* Set a display name and short description in **Settings → Personality**.+* Edit the behavior itself via the **Brain** page (the raised center button in the bottom bar, `/brain`), where memory, goals, and intelligence live.++OpenHuman also **learns** durable preferences from how you correct it over time. See [Personalization & Self-Learning](../../features/personalization.md).++### 6. Run your first real request++Once a source has been ingested, try:++* "What do I need to know from the last 12 hours?"+* "What's waiting on me?"+* "Summarize what I missed today."++***++## Success checks++You have a working assistant when **all** of these are true:++* [ ] The app is signed in (you're past the welcome screen and in the chat/home view).+* [ ] At least one integration shows as **connected** in Settings.+* [ ] A briefing prompt ("what's waiting on me?") returns something drawn from your actual data, not a generic answer.+* [ ] Opening **Connections → Memory → Brain** shows your source with an item count after it syncs.+* [ ] When you ask it to do something with an external effect (e.g. "draft and send an email"), you see an **Approval Request card** appear above the chat box rather than it silently acting.++## Common failures++| Symptom | What it means | Fix |+| ------------------------------------------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |+| Sign-in returns to the welcome screen | The OAuth callback didn't reach the app | Follow [Troubleshooting Sign-In](../../overview/troubleshooting-sign-in.md) |+| Connected a source but memory stays empty | Source not added or not synced yet, or the OAuth scope is too narrow | Press sync on the source; re-check the connection in Settings |+| Assistant answers generically, ignores your data | It answered without recalling memory | Ask again and reference the source explicitly ("from my email…"); confirm the source is connected |+| It performed an action you didn't expect | The autonomy policy is off, or `level` is `full` | Set `[autonomy] enabled = true` and `level = "supervised"` in `config.toml` |++## Recovery++* **Reset boundaries fast:** if the assistant is doing too much, set both `enabled = true` and `level = "readonly"` in `config.toml`. The level alone changes nothing while `enabled` is `false`, because the whole policy is inert then. With both set, it takes effect on the next turn and blocks all acting immediately.+* **Nothing you connect is permanent:** revoke any integration from Settings; items already stored in your memory engine stay until you forget them (or tick **Also delete memory from this source** when disconnecting), and the next sync tick stops pulling that source.+* **If the app itself won't start,** see [Recover from a failed installation](recover-failed-installation.md). Your configuration is preserved by default.++***++## Next steps++* [Use OpenHuman with a local model](local-model.md): keep inference on-device.+* [Keep sensitive data private](privacy-sensitive-data.md): understand exactly what leaves your machine.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/privacy-sensitive-data.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/privacy-sensitive-data.mdnew file mode 100644index 0000000000..726ec9a3b0--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/privacy-sensitive-data.md@@ -0,0 +1,107 @@+---+description: >-+ A plain-language map of what OpenHuman keeps on your computer versus what it+ sends out, and the settings that let you keep sensitive work local.+icon: lock+---++# Keep sensitive data private++**Goal:** understand, in everyday language rather than architecture, what stays on your machine and what leaves it, so you can decide what OpenHuman should touch.++If you want the engineering detail, read [Privacy & Security](../../features/privacy-and-security/). This guide is the version you can act on in five minutes.++***++## The one-sentence version++**Your settings and local secrets stay on your computer; your memory is stored in CortexDB (hosted by TinyHumans for your account, or your own). The OpenHuman backend handles what has to be brokered: signing you in, hosted memory, routing model requests, and talking to the services you connect.**++Everything below is an expansion of that sentence.++***++## What stays on your machine++These never leave your computer as raw data:++| Thing | Plain meaning |+| ----------------------------- | -------------------------------------------------------------------------------------- |+| **Audio you speak** | Captured to transcribe, then discarded. |+| **Local model state** | If you use [local AI](local-model.md), your own runtime and its models stay on-device. |+| **Your persona and settings** | The files that define how your assistant behaves and what it's allowed to do. |++## Where your memory is stored++When memory is on, documents, conversations, learnings and the beliefs built from them are stored in **CortexDB**. With TinyHumans-hosted memory they are not stored on your computer; a CortexDB you self-host may keep them on your own machine (with no engine available, memory is off and nothing is stored):++* **TinyHumans engine (default when signed in):** stored in the hosted CortexDB that TinyHumans runs, through the TinyHumans backend. Each account gets its own isolated tenant, so other users cannot see your memory. TinyHumans operates that service.+* **CortexDB engine:** stored in your own CortexDB account or self-hosted CortexDB, reached directly with your key. A CortexDB you run on your own machine keeps the data on that machine.++Secrets and personal identifiers are scrubbed before an item is sent. You can forget single items or whole sources from the Memory page; see [Deleting memory](../../features/privacy-and-security/#deleting-memory) for erasing everything.++## What the backend handles (and why)++These leave your machine because they can't work otherwise, but note _what_ is sent:++| Thing | What's actually sent |+| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Hosted memory** | With the TinyHumans engine, every item stored and every recall goes through the backend to hosted CortexDB. |+| **Model requests** | Only what the assistant needs for that turn: your prompt plus the memory recalled for it. Not your whole memory. |+| **Web search** | Your search query goes to the backend proxy (so you don't need your own search key). |+| **Connected services** | When you connect Gmail, Slack, etc., the backend brokers each request. Your login tokens for those services are held by the backend, **not written in plain text on your laptop**. |+| **Text-to-speech** | The words to be spoken are streamed to generate audio, then discarded. They are not retained. |++{% hint style="info" %}+**Memory is not local, so scrubbing and scoping matter.** Your memory engine stores items in CortexDB and answers recall there. What protects you is that items are scrubbed before they are sent, tool-call arguments are never stored, hosted memory is isolated per account, and a model turn sees only what was recalled for it.+{% endhint %}++## Two promises worth knowing++* **No training on your data.** Your conversations, memory, and personal information are never used to train models.+* **Secrets are stored by your operating system.** Local secrets are kept in your platform's secure store (macOS Keychain, Windows Credential Manager, or the Linux Secret Service), not lying around in app files. See [OS Keyring & Secret Storage](../../features/privacy-and-security/os-keyring-and-secret-storage.md).++***++## Turning the dial toward "more local"++You have real controls. From most to least private:++1. **Route inference on-device.** Run a local runtime such as Ollama yourself, pull the models, and [add it as a provider](local-model.md) so embeddings, summarization, and optionally chat/reasoning happen on your machine. OpenHuman doesn't install the runtime or download models for you. _(Speech and web search still use the backend proxy even then.)_+2. **Tighten what the assistant can do.** Set `[autonomy] enabled = true` and `level = "readonly"` in `config.toml`: it can then observe and answer but never act or reach the network on its own. The policy is **off by default**, so this is a switch you have to throw, not one to leave alone. See the [Approval Gate](../../features/approval-gate.md).+3. **Keep it in one folder.** The filesystem boundary has two preconditions: the policy enabled, and `workspace_only` on. With both, the agent is confined to its working folder and cannot read the rest of your disk. With either one off, that boundary is not enforced. A **trusted root** is the deliberate exception: each one you add grants its subtree outside the working folder, taking precedence over `workspace_only`. System and credential folders (`~/.ssh`, `~/.gnupg`, `~/.aws`, and OS directories) are blocked outright regardless of all three.+4. **Connect only what you need.** Every integration is a separate OAuth approval you grant (and can revoke) individually. Revoking stops the next sync; memory already collected stays in your memory engine until you forget it.++## Built-in protections you didn't have to configure++* **Prompt-injection screening.** Incoming content is screened for attempts to hijack the assistant's instructions before it acts on them.+* **Secret & PII redaction on save.** When content is written into long-lived memory, OpenHuman strips things like API keys, tokens, private-key blocks, and personal identifiers so they don't get stored.+* **Encrypted in transit.** All traffic between the app and the backend is TLS. Nothing travels in plain text.++***++## Success checks++You know your privacy posture when you can answer these:++* [ ] Is the autonomy policy on, and do you know its tier? (Check `[autonomy]` in `config.toml`.)+* [ ] If you are relying on the filesystem boundary, is `workspace_only` on as well, and do you know which trusted roots grant access outside the working folder?+* [ ] Do you know which integrations are connected? (Check **Settings**; disconnect any you don't need.)+* [ ] If locality matters for a workload, is it routed to a [local provider](local-model.md) that is running and answering?+* [ ] Are you comfortable that model turns send _retrieved snippets_, not your whole memory?++## Common misunderstandings++| Belief | Reality |+| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| "My memory is stored on my laptop." | It is stored in CortexDB (hosted by TinyHumans, or yours). Only bookkeeping is local. |+| "OpenHuman uploads my whole memory to the model to answer." | The model gets only what was recalled for that specific turn. |+| "My service passwords are on my laptop." | Integration tokens are held by the backend; local secrets go in your OS keychain. |+| "Turning on local AI makes _everything_ local." | Speech-to-text, text-to-speech, and web search still use the backend proxy by default, and memory is still stored in CortexDB. |+| "Revoking an integration deletes what it already gathered." | Already-ingested memory stays in your memory engine until you forget it; revoking only stops future syncing. |++## See also++* [Privacy & Security](../../features/privacy-and-security/): the detailed architecture.+* [Use OpenHuman with a local model](local-model.md): keep inference on-device.+* [Create a safe companion for a child](child-safe-companion.md): the strictest lockdown, composed from these controls.diff --git a/docs/gitbooks/docs/gitbooks/en/guides/guides/recover-failed-installation.md b/docs/gitbooks/docs/gitbooks/en/guides/guides/recover-failed-installation.mdnew file mode 100644index 0000000000..995eb67161--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/guides/guides/recover-failed-installation.md@@ -0,0 +1,124 @@+---+description: >-+ Get a broken or half-installed OpenHuman running again without losing your+ memory, personas, or settings. Configuration is preserved by default.+icon: life-ring+---++# Recover from a failed installation++**Goal:** the app won't install, won't start, or starts broken, and you want it working again **without wiping your data**.++The guiding rule of this guide: **your configuration and memory are preserved by default.** Recovery means fixing the runtime around your data, not deleting the data. We only touch your data folder as an explicit, backed-up last resort.++***++## Prerequisites++* Nothing special. You can do all of this from the app plus a file manager and, occasionally, a terminal.+* Know where your data lives. **Everything OpenHuman persists is in one folder:**++ | Platform | Data folder |+ | ------------- | --------------------------- |+ | macOS / Linux | `~/.openhuman/` |+ | Windows | `%USERPROFILE%\.openhuman\` |++ Leave that folder alone unless a step here explicitly says to touch it.++## Privacy implications++* Recovery is local. You're restarting or reinstalling software; your memory never gets uploaded as part of this.+* If you file a bug report, **redact secrets**. Attach status codes, app version, OS, and log lines, never tokens or JWTs.++***++## First: read the logs++Almost every failure names itself in the log. Get to the logs first; it turns guessing into fixing.++* **In the app (if it opens):** **Settings → About → App Logs Folder**. There's a button to reveal the folder in your file manager.+* **On disk:** logs are under your data folder, e.g. `~/.openhuman/logs/openhuman.<date>.log` (Windows: `%USERPROFILE%\.openhuman\logs\openhuman.*.log`). They rotate daily.++Open the most recent log and read the last error lines. Match the message to the tables below.++***++## Recovery ladder++Work top to bottom. **Stop as soon as it works.** Each rung is more disruptive than the last, and the early rungs never touch your data.++### Rung 1: Restart cleanly++* Fully quit OpenHuman (make sure no leftover process is running) and reopen it.+* Only **one** instance should run at a time. A second copy can hold a lock the first one needs.++### Rung 2: Reinstall the app over your data++Reinstalling the **application** does not delete your **data folder**; they're separate. This fixes a corrupted or partial install while preserving everything.++* Download the current build from [tinyhumans.ai/openhuman](https://tinyhumans.ai/openhuman) and install over the top.+* On macOS, install the real `.app` bundle (some features need the bundle, not a dev build).+* Reopen. Your memory, personas, and settings are still there because they live in `~/.openhuman/`, which you didn't touch.++### Rung 3: Fix the specific error++Match your symptom:++| Symptom in logs / UI | Cause | Fix |+| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Sign-in stalls after the provider step; log mentions `openhuman://` scheme **not registered** (Windows) | The URL handler didn't register, or the install was moved after first launch | Follow the repair steps in [Troubleshooting Sign-In](../../overview/troubleshooting-sign-in.md#windows-openhuman-handler-not-registered) |+| App won't render, or the window opens blank | A previous instance is still holding the port or the webview data directory | Ensure no other OpenHuman is running; if it persists, close all instances and relaunch |+| Local AI / Ollama errors | The local runtime you configured isn't running, or a model isn't pulled | This does **not** block the app. OpenHuman doesn't install or start the runtime; start it yourself, see [Use OpenHuman with a local model](local-model.md#common-failures) |+| "Low disk space" warning, or writes failing | The workspace can't be written | Free up space (the app wants a healthy margin, a few hundred MB minimum) and restart |++### Rung 4: Move the data folder aside (non-destructive reset)++If the app still won't start and you suspect the **data folder** itself is the problem, **rename** it rather than delete it. This gives you a clean start while keeping a full backup you can restore from.++{% hint style="warning" %}+Quit OpenHuman completely before moving its folder.+{% endhint %}++```bash+# macOS / Linux+mv ~/.openhuman ~/.openhuman.backup-$(date +%Y%m%d)+```++```powershell+# Windows (PowerShell)+Rename-Item "$env:USERPROFILE\.openhuman" ".openhuman.backup"+```++Relaunch. OpenHuman recreates a fresh data folder and you sign in again.++* If the fresh start **works**, the old folder was the issue, but your data is safe in the backup. You can copy specific pieces back (your workspace files such as `SOUL.md` or `config.toml`) and test after each.+* If it **still fails**, the data folder wasn't the cause. **Restore your backup** by renaming it back, so you lose nothing, and escalate (below).++***++## Success checks++You've recovered when:++* [ ] The app launches to the sign-in or chat screen without crashing.+* [ ] You can sign in and reach your home/chat view.+* [ ] Your **Memory** tab still shows your existing summaries (confirming your data survived).+* [ ] The most recent log file shows a clean startup with no repeating error.++## What "preserved by default" means here++At no point in Rungs 1 to 3 do you delete anything. Rung 4 **renames** your data folder; it never removes it. Even the most aggressive step is fully reversible. Reinstalling the app and reinstalling the OS-level runtime never target your `~/.openhuman/` data.++## If you're still stuck++Gather this and open an issue on [GitHub](https://github.com/tinyhumansai/openhuman) or ask on [Discord](https://guild.tinyhumans.ai):++* App version and OS.+* The last error lines from the log (**tokens/JWTs redacted**).+* Which rung you reached and what happened.+* Whether moving the data folder aside changed anything.++## See also++* [Troubleshooting Sign-In](../../overview/troubleshooting-sign-in.md): the deep dive for auth-specific failures.+* [Move OpenHuman to a new PC](move-to-new-pc.md): the same data folder is what you carry over.diff --git a/docs/gitbooks/docs/gitbooks/en/legal/privacy-policy.md b/docs/gitbooks/docs/gitbooks/en/legal/privacy-policy.mdnew file mode 100644index 0000000000..55cbd3d27e--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/legal/privacy-policy.md@@ -0,0 +1,76 @@+---+description: >-+ How OpenHuman collects, uses, processes, stores, and protects information+ when you use the service.+icon: key+---++# Privacy Policy++Last Updated: 02/02/2026++This Privacy Policy describes how we collect, use, process, store, and protect information when you use our system-level AI assistant (the “Service”). The Service is designed to operate as a general-purpose assistive agent on a user’s device, such as a laptop or desktop computer. We are committed to protecting user privacy and minimizing data collection and retention.++This Privacy Policy is intended to comply with applicable global data protection laws, including the EU General Data Protection Regulation (GDPR), India’s Digital Personal Data Protection Act (DPDP), the California Consumer Privacy Act and Privacy Rights Act (CCPA/CPRA), Brazil’s LGPD, and Canada’s PIPEDA.++## Information We Collect++We collect and process information only as necessary to provide the Service and only in response to explicit user actions.++1.1 User Content and System Data When you use the Service, it may process files, application data, system context, or other information on your device only when you explicitly instruct it to do so and only to the extent required to complete a requested task.++1.2 Minimal User Metadata We collect limited user metadata required for basic account or service functionality. This is restricted to: • First name • Last name • User-provided profile information (such as a bio, where applicable)++We do not collect phone numbers, contact lists, precise location data, device identifiers, browsing history, behavioral analytics, or background system activity unless explicitly required for and permitted by a user-requested task.++## How We Use Information++We use information solely to operate, maintain, and provide the Service, including to: • Perform tasks explicitly requested by the user++• Provide contextual assistance across files, applications, or workflows++• Improve reliability and security of the Service++We do not use personal data for advertising, marketing, profiling, or behavioral tracking. We do not sell, rent, or trade personal data. User data is not used to train shared, public, or third-party AI models.++## Data Retention and Deletion++The Service operates under a zero-retention-by-default design.++• System data and content are processed transiently++• No long-term logs of system activity, files, or actions are maintained++• Temporary data required to complete a task is deleted immediately after task completion or within a maximum of 30 days++Users may request deletion of their data at any time. Upon such request, all associated data is permanently deleted and cannot be recovered. Revoking permissions or uninstalling the Service immediately halts further processing.++## Legal Bases for Processing++Where required by law, we process personal data based on one or more of the following legal bases:++• User consent++• Performance of a contract++• Legitimate interests, where applicable and balanced against user rights++## Security Measures++We implement reasonable and appropriate technical and organizational measures designed to protect information from unauthorized access, loss, misuse, or alteration. These measures include encryption in transit and at rest, least-privilege access controls, isolated processing environments, and internal monitoring and audit mechanisms. Access to user data by personnel is restricted to operational, security, or legal necessity.++## Service Providers++We may engage third-party service providers to support operation of the Service, such as infrastructure hosting or AI inference providers. These providers act only on our behalf, are subject to confidentiality obligations, and are restricted from using data for their own purposes.++## International Data Transfers++Information may be processed in locations outside your country of residence. Where applicable, we implement appropriate safeguards to ensure adequate protection consistent with applicable data protection laws.++## Your Rights++Depending on your location, you may have rights to access, correct, delete, restrict processing of, or withdraw consent for your personal data, as well as request data portability. Requests can be done on the dashboard at any time or may be submitted to [email protected].++## Changes to This Policy++We may update this Privacy Policy from time to time. Material changes will be communicated as required by law. Changes will not apply retroactively in a manner that reduces existing privacy protections.diff --git a/docs/gitbooks/docs/gitbooks/en/legal/terms-of-use.md b/docs/gitbooks/docs/gitbooks/en/legal/terms-of-use.mdnew file mode 100644index 0000000000..56078e70ed--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/legal/terms-of-use.md@@ -0,0 +1,60 @@+---+description: Terms and conditions governing use of the OpenHuman service.+icon: file-contract+---++# Terms & Conditions++Last Updated: 2026-02-02++These Terms & Conditions (“Terms”) govern your use of the Service. By installing, accessing, or using the Service, you agree to be bound by these Terms. If you do not agree, you must not use the Service.++## The Service++The Service is a system-level AI assistant designed to help users complete tasks, automate workflows, and interact with files, applications, and system resources based on explicit user instructions. The Service acts only on user requests and does not operate autonomously.++## User Responsibilities++You agree to:++• Use the Service in compliance with applicable laws and regulations++• Use the Service only with content and systems you have the right to access++• Not use the Service for surveillance, harassment, or unlawful activity++• Not attempt to reverse engineer, interfere with, or misuse the Service++You are responsible for reviewing and validating any outputs before acting on them.++## Content and Data Ownership++You retain ownership of your content, files, and data. We do not claim ownership over user content or AI-generated outputs. Our access to data is limited, permission-based, and solely for the purpose of providing the Service.++## AI Outputs Disclaimer++The Service uses artificial intelligence systems that generate outputs probabilistically. Outputs may be inaccurate, incomplete, or outdated. The Service does not guarantee accuracy, reliability, or suitability for any purpose and does not replace professional judgment. You are solely responsible for how you use AI-generated outputs.++## Availability and Modifications++We may modify, suspend, or discontinue the Service or any part of it at any time, including to improve functionality, address security issues, or comply with legal requirements.++## Limitation of Liability++To the maximum extent permitted by law, the Service is provided on an “as is” and “as available” basis. We disclaim all warranties, express or implied. We are not liable for indirect, incidental, consequential, special, or punitive damages, including loss of data, loss of profits, or reliance on AI-generated outputs. We are not responsible for interruptions or failures caused by third-party software, operating systems, or services.++## Indemnification++You agree to indemnify and hold harmless the Service and its affiliates from claims, damages, losses, or expenses arising from your use of the Service, violation of these Terms, or infringement of third-party rights.++## Termination++You may stop using the Service at any time. We may suspend or terminate access if you violate these Terms or if required by law. Upon termination, data will be handled in accordance with the Privacy Policy.++## Governing Law++These Terms are governed by the laws of \[Insert Jurisdiction], without regard to conflict of law principles.++## Onboarding Consent (Shown During Installation)++By installing or using this AI assistant, you consent to it accessing system information, files, and application context solely to perform tasks you explicitly request. The assistant does not monitor your system continuously, does not act without instruction, and does not retain system data beyond what is necessary to complete a task. You remain in control of permissions at all times and may revoke access or delete your data at any time. Your data is not used for advertising or to train shared AI models.diff --git a/docs/gitbooks/docs/gitbooks/en/overview/auto-update.md b/docs/gitbooks/docs/gitbooks/en/overview/auto-update.mdnew file mode 100644index 0000000000..c88c289942--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/overview/auto-update.md@@ -0,0 +1,55 @@+---+description: >-+ How OpenHuman updates itself: one signed manifest, a bounded download retry,+ and a shell update that carries the core with it.+icon: arrows-rotate+---++# Auto-update++OpenHuman updates the whole app in one step. The core is linked into the desktop shell rather than shipped beside it, so there is no separate core update to think about: a shell update upgrades both.++## What you see++When a newer build is available, the app checks for it and downloads it in the background. The prompt appears once the download is ready, then moves through **ready to install**, **installing** and **restarting**. If you are already current you see **up to date**, and a failure says so rather than silently retrying forever.++Installing shuts the in-process core down first, under the same restart lock the app uses elsewhere, so replacing the bundle never races a core still holding file handles. On macOS that is what keeps a `.app` replacement clean.++## Where updates come from++A single endpoint, a manifest published with every release:++```text+https://github.com/tinyhumansai/openhuman/releases/latest/download/latest.json+```++Every artifact is signed, and the public key is compiled into the app. A build whose signature does not verify is refused. That is the whole trust story: no update server to trust, no second channel.++## Retry policy, and what is deliberately not retried++Downloads get **three attempts** (one try plus two retries) with a linear backoff of two seconds times the attempt number.++Only transient network failures are retried. Signature failures, filesystem errors and "no artifact for this target" are **not**, and that asymmetry is the point: re-downloading cannot fix a bad signature, and looping on a verification failure would both waste the user's bandwidth and mask tampering. The policy lives in `crates/openhuman-app/src/app_update.rs`, where `classify` and `is_transient_updater_err` are the two functions that decide.++## Periodic checks++The core runs the schedule, under `[update]` in `config.toml`:++| Key | Default | What it does |+| --- | --- | --- |+| `enabled` | `true` | Turn periodic checks off entirely. |+| `interval_minutes` | `60` | How often to check. The runtime floor is 10 minutes. |+| `restart_strategy` | `self_replace` | `self_replace` restarts in place after staging; `supervisor` stages and leaves the restart to whatever is managing the process. |+| `rpc_mutations_enabled` | `true` | Whether a bearer-authenticated RPC client may call the mutating update methods at all. |++`supervisor` is the setting for a headless or containerised core: something else owns the process lifecycle, and the update should not decide to restart on its own.++## Headless and self-hosted cores++A core you run yourself (`openhuman-core serve`) checks and stages through the `update` namespace rather than the desktop prompt, which is why `rpc_mutations_enabled` exists as a separate switch. The desktop commands that used to update a core binary separately (`check_core_update`, `apply_core_update`) are kept as explicit no-ops for frontend compatibility and do nothing.++## See also++- [Platform & Availability](../features/platform.md): what ships on each OS.+- [Release Policy](../developing/release-policy.md): how a release is cut, and the OAuth minimum-version gate.+- [Cloud Deploy](../features/cloud-deploy.md): running the core somewhere else.diff --git a/docs/gitbooks/docs/gitbooks/en/overview/getting-started.md b/docs/gitbooks/docs/gitbooks/en/overview/getting-started.mdnew file mode 100644index 0000000000..17ae455f22--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/overview/getting-started.md@@ -0,0 +1,91 @@+---+description: >-+ Install OpenHuman, walk through the in-app onboarding (sign in, choose how AI+ runs, connect an app), and run your first request against your own memory.+icon: play+---++# Getting Started++This page walks you through installing OpenHuman, going through the in-app onboarding, and running your first request.++OpenHuman is open source under the GNU GPL3 license. The codebase is at [github.com/tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman).++{% hint style="info" %}+**Want a specific outcome?** If you're here to accomplish something concrete (set up a private assistant, run a local model, recover a broken install, or move to a new machine), the [Guides](../guides/guides/) section has task-by-task walkthroughs.+{% endhint %}++***++## System requirements++OpenHuman runs on **macOS, Windows and Linux** desktops. 4 GB+ RAM is recommended; 16 GB+ if you intend to ingest very large mailboxes or repos, or run a [local model](../features/model-routing/local-ai.md) on the same machine (you install the runtime, such as Ollama, and pull the models yourself).++### Permissions++The first time you launch OpenHuman, the OS will prompt for the permissions the app needs (Accessibility on macOS, Input Monitoring for the voice hotkey). You can review and adjust these any time under **Settings**.++***++## 1. Download and install++Get the OpenHuman desktop app from [tinyhumans.ai/openhuman](https://tinyhumans.ai/openhuman) or via your platform's package manager. Open the app once it's installed.++## 2. Sign in++The first screen is **"Sign in! Let's Cook"**. Multiple sign-in options are available, including social login. There's also an **Advanced** panel for pointing the app at a custom core RPC URL if you're running your own backend; most users can ignore it.++{% hint style="info" %}+**No permanent lock-in.** Signing in does not grant OpenHuman ongoing access to anything. All third-party access requires explicit OAuth approval per integration in the steps below.+{% endhint %}++{% hint style="warning" %}+**Know what is local and what is managed.** Your workspace config, and local runtime state live on your machine. The default setup still uses OpenHuman-hosted services for sign-in, model routing, managed integration OAuth/tool calls, and web search proxying. Use the custom setup paths if you want to bring your own model, search, or Composio credentials. Some hosted features and real-time integration triggers still require the managed backend.+{% endhint %}++## 3. Connect something, and set up memory++Onboarding offers a runtime choice (the managed TinyHumans route, or a custom setup where you bring your own model, search, embeddings and connector keys) and then drops you into the app. Two things make the first request worth making:++* **An integration.** Open [Connections](../features/connections.md) → Apps and connect one. Gmail is the usual first choice; each connection is a one-click OAuth approval you can revoke.+* **A memory engine.** Connections → Memory. Signed in, the hosted engine is already there; otherwise point it at your own CortexDB. With neither, [memory](../features/memory.md) is off and the agent starts from zero every chat.++Add the integration as a memory source on the Brain tab to sync it on a schedule.++## 4. Run your first request++Once a memory source has synced, try prompts like:++**Briefings**++* "What do I need to know from the last 12 hours?"+* "What's waiting on me?"++**Cross-source queries**++* "Summarize what I missed today."+* "What are the key decisions from this week?"+* "Extract action items from my recent conversations."+* "What did Sarah say about the project across email and chat?"++OpenHuman picks the right model for each task automatically. See [Automatic Model Routing](../features/model-routing/).++***++## 5. Keep going++Now that the agent has memory and a model, the rest of the product is about giving it more surfaces:++* [**Chat**](../features/chat.md): what a turn can actually do, and the four ways it stops to ask you something.+* [**Connections**](../features/connections.md): everything the agent plugs into, on one page.+* [**Memory**](../features/memory.md): connect more sources; they sync on a schedule into your memory engine.+* [**Workflows**](../features/workflows.md): describe an automation and review the graph the agent proposes.+* [**Native Voice**](../features/native-tools/voice.md): dictation and spoken replies, or a live voice agent.+* [**Roadmap**](roadmap.md): what is coming, and what was removed.++## Join the community++OpenHuman is in early beta. Feedback and contributions make a real difference at this stage.++* **GitHub:** [github.com/tinyhumansai/openhuman](https://github.com/tinyhumansai/openhuman)+* **Discord:** [guild.tinyhumans.ai](https://guild.tinyhumans.ai)diff --git a/docs/gitbooks/docs/gitbooks/en/overview/roadmap.md b/docs/gitbooks/docs/gitbooks/en/overview/roadmap.mdnew file mode 100644index 0000000000..292d0200d2--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/overview/roadmap.md@@ -0,0 +1,57 @@+---+description: >-+ What is being worked on next, and the known gaps. Tracked in public issues+ rather than promised here.+icon: map+---++# Roadmap++This page is a reading of the open issue tracker, not a commitment. Dates are deliberately absent. Everything below links to the issue that owns it, so if this page goes stale the issue is still the truth.++Checked 2026-10-07.++## Taking off the early-beta badge++[#6047](https://github.com/tinyhumansai/openhuman/issues/6047) is the checklist, with an explicit definition of done: the badge comes off when the boxes are closed, the memory smoke test passes on macOS, Windows and Linux, and the release workflow can publish without hand-holding. Read the boxes against the text beside them: a ticked box is not always a passing test.++| Area | State |+| --- | --- |+| Memory end to end (store, restart, recall, and the agent actually uses it) | Two of three items ticked ([#6041](https://github.com/tinyhumansai/openhuman/issues/6041), [#6040](https://github.com/tinyhumansai/openhuman/issues/6040)); the third is the end-to-end smoke test, which the checklist itself records as not currently passing |+| Reply persistence: a completed reply can never vanish | Done |+| Clean-install sign-in on all three platforms | Open, [#6020](https://github.com/tinyhumansai/openhuman/issues/6020) |+| Windows: native modules refused when `%TEMP%` grants Modify to a non-owner group, leaving memory and connectors unavailable | Open, [#6008](https://github.com/tinyhumansai/openhuman/issues/6008) |++The release-pipeline and Windows path-length blockers the checklist also lists have since been closed, even though the boxes are still unticked there.++## Programmes with several issues behind them++- **Agent to agent.** [#3463](https://github.com/tinyhumansai/openhuman/issues/3463) is the umbrella over five phases: an agent-card endpoint and discovery, accepting tasks, delegating to an external agent as a tool, streaming and push notifications, and multi-instance coordination.+- **Pluggable memory adapters.** [#5390](https://github.com/tinyhumansai/openhuman/issues/5390) adds the adapters directory and the dependency rule; supermemory, mem0, agentmemory and cognee follow behind it. Today [memory](../features/memory.md) has two engines and no adapter directory exists yet.+- **External agent runtimes.** [#4731](https://github.com/tinyhumansai/openhuman/issues/4731) is an abstraction layer for driving Cursor, Windsurf and Codex, with a shared ACP transport for several more and per-session model and effort selection. Session import from one of them is the live edge of this work.+- **Local and self-hosted.** [#6130](https://github.com/tinyhumansai/openhuman/issues/6130) would bring back a managed local runtime with model downloads and a compute-backend selector, deliberately re-adding something that was removed: local inference today means an endpoint you run yourself. [#4844](https://github.com/tinyhumansai/openhuman/issues/4844) is a no-UI Linux build for a server or a Raspberry Pi.+- **Observability.** [#4496](https://github.com/tinyhumansai/openhuman/issues/4496) adds scores to traces, so user feedback and automated quality signals land next to the run they describe.++## Shipped but inert++Two surfaces exist in the build and do nothing, which is worth knowing before you go looking for them:++- **Follow-up suggestion chips** are built and unreachable: nothing produces them, so the row is always empty ([#6465](https://github.com/tinyhumansai/openhuman/issues/6465)).+- **SearXNG** is configurable and reachable over the MCP server, but `searxng_search` is not registered as an agent tool, so the agent in chat cannot use it ([#6127](https://github.com/tinyhumansai/openhuman/issues/6127)).++The app also ships its own maturity ledger: **Settings → About** lists every capability with a status of stable, beta or coming soon, which is a better answer than this page for "is X finished".++## Recently removed++Things the docs used to describe that are gone, so you are not hunting for them:++- The **live Google Meet agent**. It joined a call through the old embedded Chromium webview and spoke back as a camera stream. The frontend, the domain and the join path were all removed. See [Voice](../features/native-tools/voice.md).+- The **embedded Chromium (CEF) runtime**. The shell runs on Tauri's native webview; browser control is a real Chrome driven over the DevTools protocol. See [Browser & Computer Control](../features/native-tools/browser-and-computer.md) and the historical [CEF notes](../developing/cef.md).+- **In-app model downloads** and runtime lifecycle management for local models. Point OpenHuman at a server you run.+- The **skills sandbox**. Skills are a catalogue you browse and install plus a run surface, not code executing inside a JavaScript sandbox in the app.+- The **memory tree, graph view, people list and `MEMORY.md`**, replaced by the per-turn memory pack. [Memory](../features/memory.md) has the full list.++## See also++- [Release Policy](../developing/release-policy.md): how a release is cut and what the version gate does.+- [Platform & Availability](../features/platform.md): what runs where today.diff --git a/docs/gitbooks/docs/gitbooks/en/overview/troubleshooting-sign-in.md b/docs/gitbooks/docs/gitbooks/en/overview/troubleshooting-sign-in.mdnew file mode 100644index 0000000000..04df78bbac--- /dev/null+++ b/docs/gitbooks/docs/gitbooks/en/overview/troubleshooting-sign-in.md@@ -0,0 +1,86 @@+---+description: >-+ Diagnose sign-in failures, OAuth callbacks that do not complete, and remote+ core RPC authentication problems.+icon: key+---++# Troubleshooting Sign-In++Use this checklist when social sign-in hangs, returns to the welcome screen, or the core logs an unauthorized `/auth` request.++## Check backend reachability++From the same network as the desktop app, verify the public OpenHuman endpoints:++```bash+curl -I https://tinyhumans.ai/+curl -I https://api.tinyhumans.ai/health+```++If the website loads but the API endpoint fails, the desktop app may not be able to exchange OAuth callbacks for a session. Capture the HTTP status, region, and DNS result in the issue report.++## Check the selected core++If you use the **Advanced** remote-core mode, confirm both the RPC URL and bearer token before starting OAuth:++```bash+curl -sS https://your-core.example/rpc \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer CORE_TOKEN" \+ -d '{"jsonrpc":"2.0","id":1,"method":"core.ping","params":{}}'+```++A `401` response means the desktop token and remote core token do not match. Fix that before retrying Google or GitHub sign-in.++## Check the deep-link callback++Successful desktop OAuth ends with an `openhuman://auth?...` callback. If the browser shows that URL but the app stays on the welcome screen:++1. Make sure only one OpenHuman desktop instance is running.+2. Restart the app, keep the same remote-core settings, and retry sign-in.+3. If using a remote core, check whether the core receives `openhuman.auth_set_credential` (the desktop shell validates the session against the backend first, then hands the credential to the core).++## Windows: `openhuman://` handler not registered++On Windows the `openhuman://` URL scheme is registered to the running executable via `HKEY_CURRENT_USER\Software\Classes\openhuman\shell\open\command` at first launch. If that registration silently failed, or if the install was moved/copied after first launch, the browser cannot hand the OAuth callback back to the app, and sign-in stalls after the provider step (issue #2699).++The Tauri shell now emits a `log::error!` line at startup when this happens. Look for it in your log file (default `%USERPROFILE%\.openhuman\logs\openhuman.*.log`):++```text+[deep-link] openhuman:// scheme registration unhealthy — OAuth callbacks may never reach the app.+register_all_error=…, hkcu_status=NotRegistered|MissingCommand|Stale { … }|ReadError(…)+```++To repair manually, open PowerShell **as the same user that runs OpenHuman** (no admin required; HKCU is per-user) and replace the path with your actual install location:++```powershell+$exe = 'C:\Path\To\OpenHuman.exe' # update this+New-Item -Path 'HKCU:\Software\Classes\openhuman' -Force | Out-Null+Set-ItemProperty -Path 'HKCU:\Software\Classes\openhuman' -Name '(Default)' -Value 'URL:OpenHuman Protocol'+New-ItemProperty -Path 'HKCU:\Software\Classes\openhuman' -Name 'URL Protocol' -Value '' -Force | Out-Null+New-Item -Path 'HKCU:\Software\Classes\openhuman\shell\open\command' -Force | Out-Null+Set-ItemProperty -Path 'HKCU:\Software\Classes\openhuman\shell\open\command' -Name '(Default)' -Value ('"' + $exe + '" "%1"')+```++Restart OpenHuman afterwards and retry sign-in. If `register_all_error` is non-`None` in the log (for example because antivirus or a locked-down image is blocking writes to `HKCU\Software\Classes`), fixing the underlying policy is required; the manual script above will hit the same block.++For a remote core, a temporary manual injection can confirm the core is otherwise healthy (the core stores the credential as given; supply the user id the token belongs to unless the JWT carries a subject claim):++```bash+curl -sS https://your-core.example/rpc \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer CORE_TOKEN" \+ -d '{"jsonrpc":"2.0","id":1,"method":"openhuman.auth_set_credential","params":{"token":"JWT_FROM_CALLBACK","userId":"YOUR_USER_ID"} }'+```++Do not paste real JWTs into public GitHub issues. Redact tokens and attach only status codes, hostnames, app version, OS, and the relevant log lines.++## What to include in a bug report++- App version and OS.+- Whether the core mode is local or remote.+- The RPC URL host, redacted token status, and `core.ping` result.+- The OAuth provider used.+- Whether an `openhuman://auth` URL appeared in the browser.+- The first unauthorized log line, if present.