Skip to content

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

Merge upstream/main and the latest saas-profile-host (#7247) into saas-profiles-embed

Steven Enamakel260320e3eee7
diff --cc crates/openhuman-core/src/profiles/README.md
index 93aecc2331,5fa79be79f,dd0a811308..ddda7f21d6
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@@@ -25,29 -11,14 -11,20 +25,29 @@@@ Two hosts drive it
```text
<root>/users/<profile-id>/ the desktop's users/<id> shape (config::schema::ProfileLayout)
- profile.toml ProfileMeta
- config.toml the profile's config_path
- workspace/ sessions, memory, threads, cron, cost
- sandbox/ action_dir: the only place it may act
+ profile.toml ProfileMeta (only without a storage backend)
+ .lease, .lease.json the file-lock lease (only without a storage backend)
- config.toml the profile's config_path
- workspace/ sessions, memory, threads, cron, cost
- sandbox/ action_dir: the only place it may act
++ config.toml the profile's config_path (never read in SaaS)
++ auth-profiles.json its credential (unless secrets live in the backend)
++ workspace/ threads, sessions, memory, cron, cost and run ledgers
++ sandbox/ action_dir: the only place its tools may act
<root>/deprovisioned/<id>-<secs>-<uuid>/ an archived profile
- <root>/operator/ the operator plane's own state
+ <root>/operator/ the operator plane's own state (operator_dir overrides it)
++<root>/service.token the gateway bearer (service_token_file overrides it)
```
-With a storage backend (`storage_url` / `OPENHUMAN_STORAGE_URL`), the
-registry and the leases live in the backend's `cluster` scope instead
-(collections `profiles` and `leases`); a profile's files stay under
-`<root>/users/<id>/`, so nodes of a cluster share `<root>` on one volume.
++With a storage backend (`storage_url` / `OPENHUMAN_STORAGE_URL`):
++
++| Where | What |
++| --- | --- |
++| scope `cluster`, collection `profiles` | the profile registry (replaces `profile.toml`) |
++| scope `cluster`, collection `leases` | the profile leases (replace the file locks) |
++| scope `profile:<id>` (`storage::scope_for_profile`) | that profile's records on the storage ports: secrets and auth profiles, approvals, cron, flows, ... |
++| session key `<id>~<agent or default>` (`tenant::session_key`) | its session store: transcripts, turn states |
++
++A profile's files stay under `<root>/users/<id>/` either way, so the nodes of a
++cluster share `<root>` on one volume (see [Known limits](#known-limits)).
+
The desktop config loader resolves a signed-in user's `users/<id>/config.toml`
and `workspace/` through the same `ProfileLayout`, so the two layouts cannot
drift. The older `<root>/agents/u-<hash>/` layout is gone; data left there is
@@@@ -55,120 -26,31 -32,37 +55,126 @@@@ not migrated
## Profile ids
- `profile_ids` in the operator config picks how a gateway user id becomes a
- `ProfileId`:
--The top-level `profile_ids` setting (`profile_ids = "hashed"`, not under a table) picks how a gateway user id becomes a `ProfileId`:
+++The top-level `profile_ids` setting in the operator config
+++(`profile_ids = "hashed"`, not under a table) picks how a gateway user id
+++becomes a `ProfileId`:
- `"raw"` (the default): a user id matching `^[a-z0-9][a-z0-9_-]{0,63}$` is
used unchanged, so the desktop's 24-hex backend ids pass through. `local`,
`operator` and anything starting with `h-` are reserved.
--- Anything else, or every id under `"hashed"`, becomes `h-` + the first 32 hex
-- characters of `sha256(user_id)`.
++- Anything else, or every id under `"hashed"`, becomes `h-` plus the first 32
++ hex characters of `sha256(user_id)`.
- Both forms fit the agent-id charset and can never contain a path separator.
- Changing the mode may re-map users onto different profiles.
++ Provisioning also refuses a profile id equal to the file name of the node's
++ `operator_dir`: keyring secrets are namespaced by their store's directory name,
++ so such a profile would share the operator's credential slots.
+
- ## Files
-Both forms fit the agent-id charset and can never contain a path separator.
-Changing the mode may re-map users onto different profiles.
++Both forms fit the agent-id charset and never contain a path separator.
- Changing the mode re-maps users onto different profiles. Gateway user ids are
- turned into profile ids at once (`ops.rs`, `gateway.rs`) and are never logged
- or stored; under raw mode a user id that fits the charset *is* the profile id,
- so use `"hashed"` where user ids must not reach paths and logs.
+++Changing the mode may re-map users onto different profiles. Gateway user ids
+++are turned into profile ids at once (`ops.rs`, `gateway.rs`) and are never
+++logged. Under raw mode a user id that fits the charset *is* the profile id, so
+++it reaches paths, storage and the provisioning response; use `"hashed"` where
+++user ids must not. Log lines and `Outcome` messages never carry the profile id.
- | File | Purpose |
-## Files
++## The tenant key
+
-| File | Purpose |
++The isolation boundary is the profile's own `CoreContext`, derived from the
++operator's (`ProfileHost::open`) with:
++
++- the forced config ([`layout::profile_config`](layout.rs));
++- its own security policy (`agent_policy`, built over its workspace and
++ sandbox), never the operator's live policy;
++- `profile = <profile id>`: the **tenant key**;
++- `session_agent = <profile id>` (see the rules below);
++- fresh state slots, and the user families only (`host::user_domains`:
++ threads, channels, memory), narrowed further by `surface::USER_METHODS`.
++
++Work for a user runs under that context, and everything per-tenant keys on
++`core::runtime::current_tenant()`, which in SaaS reads only the task's own
++scope and fails closed (`NoTenant`) instead of falling back to the operator:
++
++| What | Keyed by |
| --- | --- |
--| `types.rs` | `ProfileId` and `ProfileIdMode`, `ProfileMeta`, and the operator-plane result types |
--| `layout.rs` | The SaaS side of the shared `ProfileLayout`, archived profiles, and `profile_config`: the forced paths, memory binding (pinned to the legacy layout) and autonomy policy |
- | `host.rs` | `ProfileHost`: provisioning, lazy open, LRU and idle eviction (never of a profile in use), each profile's derived `CoreContext`, `current()` |
-| `host.rs` | `ProfileHost`: provisioning, lazy open behind the profile lease, LRU and idle eviction (never of a profile in use), release, fencing, each profile's derived `CoreContext`, `current()`, `ensure_hosted()` |
-| `lease.rs` | The profile lease as the host uses it: `OpenError`, the lease store choice (`DocumentLeases` over a backend, else `LocalLeases`), and the heartbeat that renews every open profile's lease and fences the ones lost |
-| `registry.rs` | `ProfileRegistry`: which profiles are provisioned, in the backend's `cluster` scope or as `profile.toml` files |
--| `gateway.rs` | Which context a gateway request runs under: the operator plane, or the profile of the user named in `X-OpenHuman-User`, after the signature check |
--| `surface.rs` | What a user may call: `USER_METHODS`, the exact allowlist applied at dispatch, in the controller list and in `/schema`; the operator scope sees only the operator plane; user thread-id rules |
--| `background.rs` | The SaaS background loop: every minute it sweeps idle profiles and runs each profile's queued memory jobs (deferred ingests, belief builds) under that profile's context |
--| `tools.rs` | Which agent tools a user gets: the operator's host tool groups (`host_files`, `host_shell`), the hard-deny list, the tool-list filter, the approval gate's SaaS verdict, and the container policy for a user's shell |
--| `credentials.rs` | A profile's TinyHumans credential, stored beside its config |
- | `ops.rs` | `provision` / `deprovision` / `list` / `status` / `set_credential` / `clear_credential`, returning `Outcome<T>` |
-| `ops.rs` | `provision` / `deprovision` / `list` / `status` / `set_credential` / `clear_credential` / `release`, returning `Outcome<T>` |
--| `schemas.rs` | The `profiles.*` controllers (`profile_id` in and out) |
++| storage backend records | `storage::scope_for_profile` |
++| session store | `tenant::session_key` |
++| web chat sessions, in-flight and parallel turns, background completions | `tenant::tenant_key(tenant, thread or request id)` |
++| `/events` | `WebChannelEvent::profile`, stamped at publish, filtered per stream |
++| cost ledger | the profile's own `CostTracker`, seeded at open |
++| config loader | the context's config (`config/schema/load/saas_scope.rs`) |
++
++So two users' `t1` are two threads, a cancel on one never stops the other,
++and neither sees the other's events.
++
++## Leases: one process per profile
++
++Exactly one process hosts a profile at a time. `ProfileHost::open` takes the
++profile's lease (`storage::lease`) before it opens it:
++
++- **With a storage backend** it uses `DocumentLeases` in the backend's
++ `cluster` scope: one compare-and-swapped record per profile with an owner
++ (`node_id`), an endpoint (`advertise_url`), an epoch and an expiry
++ `lease_ttl_secs` (default 30) out. Every node sharing the backend contends
++ for the same records. A clustered node (one that sets `advertise_url`) must
++ use a driver whose CAS holds across processes
++ (`storage::driver_has_cross_process_cas`: SQLite, MongoDB); the boot guard
++ refuses anything else.
++- **Without one** it uses `LocalLeases`: an exclusive `flock` on
++ `<root>/users/<id>/.lease`, which keeps two processes on one root apart and
++ drops when its holder dies.
++
++What the lease drives:
++
++- **Refusal.** A live lease held elsewhere makes `open` return
++ `OpenError::HeldElsewhere(record)`. The gateway answers `409` (below);
++ `ProfileRuntime::open` returns the error with the record.
++- **Recovery.** A lease taken over from a holder that never released it
++ (`previous_unclean`: it crashed or stopped renewing) means that holder's
++ turns may have died mid-flight. `recover_workspace` marks them interrupted
++ and settles orphaned run-ledger rows, and a storage-backed session store is
++ swept for the profile too. A clean hand-over (eviction, release, shutdown)
++ recovers nothing, so a re-open never interrupts live work. This is why the
++ SaaS session store never recovers on open
++ (`session_store::install_for_saas`).
++- **Heartbeat.** `lease::heartbeat` renews every open profile's lease every
++ third of the TTL. A renewal that finds the record changed (another node
++ took over, or an operator released it), or that keeps failing until the
++ grant would have expired, **fences** the profile: it is marked fenced, its
++ in-flight turns are stopped (`web_chat::cancel_all_turns` under its
++ context) and it is closed. `ensure_hosted` refuses new turns for a profile
++ this node no longer hosts.
++- **In use.** A profile is in use while anyone holds its `Profile` (a gateway
++ request, a `ProfileHandle`) or a turn still runs on its context
++ (`CoreContext::tenant_in_use`). A profile in use is never evicted, released
++ or deprovisioned from under its work.
++- **Release.** Idle eviction (`idle_evict_secs`, or LRU when
++ `max_profiles_open` is reached), `profiles.release {profile_id}`,
++ deprovisioning and a clean shutdown release the lease, so another node can
++ take the profile at once. On shutdown a busy profile keeps its lease, so
++ its successor treats the hand-over as unclean and recovers its turns.
++- **Node ids** (`node_id`, else `OPENHUMAN_NODE_ID`, else random per process)
++ must be unique among live nodes. A stable one lets a restarted node take its
++ own profiles back at once instead of waiting out their leases.
++
++## Chat interfaces: one thread each
++
++A profile holds one thread per conversation, whatever interface it came in on:
++
++- **Web chat.** The user picks the thread id (`threads_upsert`,
++ `channel_web_chat`): 1–128 characters of `[A-Za-z0-9_-]`. The core-reserved
++ prefixes `channel:`, `proactive:` and `subagent:` are refused
++ (`surface::validate_user_thread_id`).
++- **Hosted platforms (relay).** The gateway owns the hosted Telegram, iMessage
++ and Discord webhooks and account links. It relays each message in as its
++ user with `channel_relay_inbound`
++ ([`channels/providers/relay`](../channels/providers/relay/README.md)). The
++ message lands on the user's `channel:<channel>/<sender>/<chat>` thread,
++ which the user cannot mint themselves; its turn runs through the channel
++ dispatch pipeline under the profile's context; each reply is published as a
++ `channel_outbound` event on that user's `/events` stream for the gateway to
++ deliver. A retried `message_id` runs nothing twice.
++- **Deferred.** Native per-profile listeners (a user's own bot token) and
++ several agents per profile need the host-agent resolver and
++ `AgentContextRegistry` keyed by `(profile, agent)` first.
## Rules
@@@@ -184,18 -69,11 -81,22 +190,18 @@@@
and would answer `org:<id>` or a minted local root instead.
- The autonomy policy is on and supervised, with no auto-approval, no tool
installation and no trusted roots.
- - **The isolation boundary is the profile's `CoreContext`.** It carries the forced
- config and `session_agent = <profile id>`, and the user families (threads, channels
- for web chat, memory), narrowed further by `surface::USER_METHODS`. Work for a
-- **The isolation boundary is the profile's `CoreContext`.** It carries the
- forced config, its own security policy (`agent_policy`, never the
- operator's), `profile = <profile id>` (the tenant key: storage scope,
- `/events`, cost, per-thread tables, via `core::runtime::current_tenant`) and
- `session_agent = <profile id>`, and the user families (threads, channels for
- web chat, memory), narrowed further by `surface::USER_METHODS`. Work for a
-- user runs under it, which is what the config loader, the session store and
-- the per-thread caches key on.
-- **`session_agent` stays the profile id.** The plan was for the default agent
- to run with no `session_agent`, as on the desktop. That needs every site
- that keys on the acting agent to key on the tenant instead; the approval
- gate's thread routes, the MCP host, skill homes, origin delivery and the
- transcript fallback still read `agent_scope::current_agent_id()`, so a
- profile without an agent id would share their keys with every other
- profile. Until those move to `current_tenant`, the profile id doubles as the
- agent id.
++- **`session_agent` stays the profile id.** The default agent was meant to run
++ with no `session_agent`, as on the desktop. That needs every site that keys
++ on the acting agent to key on the tenant instead; the approval gate's thread
++ routes, the MCP host, skill homes, origin delivery and the transcript
++ fallback still read `agent_scope::current_agent_id()`, so a profile without
++ an agent id would share their keys with every other profile. Until those
++ move to `current_tenant`, the profile id doubles as the agent id.
++- **No ambient fallback.** Tenant-keyed code reads `current_tenant()`, never
++ `CoreContext::current()` or `.session_agent()`; `pnpm saas:ambient`
++ ratchets the reads that remain (`ambient-context`), alongside bare spawns,
++ direct `load_or_init` calls, environment writes and `home_dir()` lookups.
++ Detached work uses `spawn_scoped` so it keeps its profile.
- **Host tools are opt-in and confined.** A user's context has no `Platform`
family, so shell and file tools are absent unless the operator lists their
group in `tool_allowlist`:
@@@@ -213,57 -91,29 -114,31 +219,58 @@@@
hard-denied whatever the allowlist says (`tools::HARD_DENIED`).
- There is no per-user approval surface, so the approval gate never parks
in SaaS: it allows tools from an allowlisted group and refuses the rest.
++- **The user surface is an allowlist.** Within the user families, only the
++ methods on `surface::USER_METHODS` are live: thread reads and writes
++ (including `threads_delete` and `threads_purge`, confined to the caller),
++ the turn-starting thread methods, web chat with cancel and queue control,
++ `channel_relay_inbound`, and memory reads and writes confined to the user's
++ tree. Anything unlisted answers as an unknown method and is absent from
++ `/schema`. `DomainSet::saas()` registers the user families so profile
++ contexts can derive them, and the surface gate keeps the operator scope on
++ the operator plane, so the operator never serves user methods on its own
++ workspace.
- **Deprovisioning archives.** The profile's directory moves to
-- `<root>/deprovisioned/<id>-<unix-secs>-<uuid>/`. Nothing is deleted. A profile
-- still in use is not archived; the call fails and can be retried.
++ `<root>/deprovisioned/<id>-<unix-secs>-<uuid>/`; nothing is deleted. Its
++ credential is cleared first (it lives in the keyring or the storage
++ backend, not only in the directory), so a re-provisioned user does not
- inherit it. A profile in use, or hosted by another node, is not archived:
- the call fails and can be retried.
+++ inherit it. If clearing it fails the profile is kept, not archived, and its
+++ lease is given back so the retry can take it. A profile in use, or hosted
+++ by another node, is not archived: the call fails and can be retried.
## Gateway contract
```text
Authorization: Bearer <service token> every request
X-OpenHuman-User: <gateway user id> work for a user
--X-OpenHuman-User-Sig: t=<unix secs>,v1=<hex hmac-sha256(token, "<t>.<user id>")>
++X-OpenHuman-User-Sig: t=<unix secs>,v1=<hex hmac-sha256(service token, "<t>.<user id>")>
```
--- No user header: the request runs on the operator plane.
++- No user header: the request runs on the operator plane (`profiles.*`).
- With one, `openhuman-rpc`'s `saas_gateway` layer handles it in this order:
-- 1. It checks the bearer **before** anything else. An unauthenticated caller
++ 1. The bearer, **before** anything else (`401`). An unauthenticated caller
cannot tell which users exist, and cannot open profiles.
-- 2. It checks the signature: ±60 s, bound to the user id. It is required
-- unless the operator sets `require_user_signature = false`.
-- 3. It opens the user's profile, which must already be provisioned
- (`403` otherwise).
- (`403` otherwise), taking its lease. A profile another core hosts
- answers `409` (see [Leases](#leases-one-core-per-profile)); a full host
- or a storage failure answers `503`.
-- 4. It runs the request under that profile's context. A user's context cannot
++ 2. A duplicate or unreadable user header (`400`).
++ 3. The signature: ±60 s, bound to the user id (`401`). Required unless the
++ operator sets `require_user_signature = false`.
++ 4. The user's profile, opened and leased: `403` when it is not provisioned,
++ `503` when every slot is busy or storage fails, and **`409`** when
++ another node hosts it:
++
++ ```text
++ X-OpenHuman-Profile-Owner: <owner node id>
++
++ {"error": "profile_held", "owner": "<node id>",
++ "endpoint": "<owner's advertise_url, or null>", "retry_after_ms": <ms>}
++ ```
++
++ The gateway routes the user to `endpoint`, or retries after
++ `retry_after_ms`; a dead owner's lease lapses within `lease_ttl_secs`.
++ 5. The request runs under that profile's context. A user's context cannot
reach the operator plane.
--- Routes a SaaS core never serves answer `404`: `/v1`, `/events*`, `/ws/*`,
++- `GET /events?client_id=` with a user header streams only that profile's
++ events (chat progress, `chat_done`, `channel_outbound`, ...). Without one it
++ answers `404`, and browser bind tokens are not accepted in SaaS.
++- Routes a SaaS core never serves answer `404`: `/v1`, `/events/*`, `/ws/*`,
`/socket.io`, `/dev/connect` and `/oauth/*`.
## Credentials
@@@@ -280,55 -162,19 -187,65 +287,55 @@@@ instead ride the operator's `OPENHUMAN_
## Background work
--A single-user core drains memory jobs from a cron system job behind the process-wide scheduler gate. A SaaS core cannot use either: the cron service is off, and the gate reflects the operator, who holds no credential. So `background::spawn` (started by `saas::build`) runs one loop per process instead. Each tick:
-
-- sweeps idle profiles;
-- visits every provisioned profile whose workspace has queued memory jobs (`memory::lifecycle::jobs::has_pending`);
-- opens that profile and runs its due jobs under the profile's own context, with its config, credential and memory root.
++A single-user core drains memory jobs from a cron system job behind the
++process-wide scheduler gate. A SaaS core cannot use either: the cron service
++is off, and the gate reflects the operator, who holds no credential. So
++`background::spawn` (started by `saas::build`) runs one loop per process. Each
++tick it sweeps idle profiles, then opens every provisioned profile whose
++workspace has queued memory jobs (`memory::lifecycle::jobs::has_pending`) and
++runs its due jobs under that profile's own context. Profiles with nothing
++queued are not opened. User cron jobs are not served yet: the cron RPCs are
++not on the user surface.
- - sweeps idle profiles;
- - visits every provisioned profile whose workspace has queued memory jobs (`memory::lifecycle::jobs::has_pending`);
- - opens that profile and runs its due jobs under the profile's own context, with its config, credential and memory root.
-Profiles with nothing queued are not opened.
++The prompt says `Host: hosted` instead of the server's hostname, and the
++`## User` identity block stays empty, because no process-wide identity is ever
++set.
- Profiles with nothing queued are not opened.
-User cron jobs are not served yet: the cron RPCs are not on the user surface.
-
-## Leases: one core per profile
-
-Exactly one process hosts a profile at a time. `ProfileHost::open` takes the
-profile's lease (`storage::lease`) before opening it:
-
-- **With a storage backend** the host uses `DocumentLeases` in the backend's
- `cluster` scope: one compare-and-swapped record per profile with an owner,
- an endpoint (`advertise_url`), an epoch and an expiry `lease_ttl_secs`
- (default 30) out. Every node sharing the backend contends for the same
- records. A clustered node (one that sets `advertise_url`) must use a driver
- whose CAS holds across processes (`storage::driver_has_cross_process_cas`:
- SQLite, MongoDB); the boot guard refuses anything else.
-- **Without one** it uses `LocalLeases`: an exclusive `flock` on
- `<root>/users/<id>/.lease`, which keeps two processes on one root apart and
- drops when its holder dies.
++## Files
- On the **first** open of a profile in a process, `recover_workspace` settles anything a previous process left in that profile's workspace:
-The lease drives the rest:
++| File | Purpose |
++| --- | --- |
++| `types.rs` | `ProfileId` and `ProfileIdMode`, `ProfileMeta`, and the operator-plane result types |
++| `layout.rs` | The SaaS side of the shared `ProfileLayout`, archived profiles, and `profile_config`: the forced paths, memory binding (pinned to the legacy layout) and autonomy policy |
++| `host.rs` | `ProfileHost`: provisioning, lazy open behind the lease, LRU and idle eviction (never of a profile in use), release, fencing, each profile's derived `CoreContext` and policy, `current()`, `ensure_hosted()` |
++| `lease.rs` | The profile lease as the host uses it: `OpenError`, the lease store choice (`DocumentLeases` over a backend, else `LocalLeases`), and the heartbeat that renews every open profile's lease and fences the ones lost |
++| `registry.rs` | `ProfileRegistry`: which profiles are provisioned, in the backend's `cluster` scope or as `profile.toml` files |
++| `gateway.rs` | Which context a gateway request runs under: the operator plane, or the profile of the user named in `X-OpenHuman-User`, after the signature check; the typed refusal (`409` holder) |
++| `surface.rs` | What a user may call: `USER_METHODS`, applied at dispatch, in the controller list and in `/schema`; user thread-id rules |
++| `background.rs` | The SaaS background loop: idle sweeps and each profile's queued memory jobs under its context |
++| `tools.rs` | Which agent tools a user gets: the host tool groups, the hard-deny list, the tool-list filter, the approval gate's SaaS verdict, and the container policy for a user's shell |
++| `credentials.rs` | A profile's TinyHumans credential, stored beside its config or in the backend |
++| `ops.rs` | `provision` / `deprovision` / `list` / `status` / `set_credential` / `clear_credential` / `release`, returning `Outcome<T>` |
++| `schemas.rs` | The `profiles.*` controllers (`profile_id` in and out) |
- - turns that were mid-flight are marked interrupted;
- - run-ledger rows left running are closed.
-- **Refusal.** A live lease held elsewhere makes `open` return
- `OpenError::HeldElsewhere(record)`; the gateway answers `409` with
- `{"error":"profile_held","owner","endpoint","retry_after_ms"}` and
- `X-OpenHuman-Profile-Owner: <owner>`. Load balancers route users stickily;
- the lease is what makes it correct.
-- **Recovery.** A lease taken over from a holder that never released it
- (`previous_unclean`: it crashed, or stopped renewing) means that holder's
- turns may have died mid-flight. `recover_workspace` marks them interrupted
- and settles orphaned run-ledger rows, and a storage-backed session store
- is swept for the profile too. A clean hand-over (eviction, release,
- shutdown) recovers nothing, so a re-open never interrupts live work. This
- replaces the old once-per-process sweep, and is why the SaaS session
- store never recovers on open (`session_store::install_for_saas`).
-- **Heartbeat.** `lease::heartbeat` renews every open profile's lease every
- third of the TTL. A renewal that finds the record changed (another node
- took over, or an operator released it), or that keeps failing until the
- grant would have expired, **fences** the profile: it is marked fenced, its
- in-flight turns are stopped (`web_chat::cancel_all_turns` under its
- context) and it is closed. `ensure_hosted` refuses new turns for a
- profile this node no longer hosts.
-- **Release.** Idle eviction, `profiles.release {profile_id}` (refused while
- the profile is in use), deprovisioning and a clean shutdown (idle profiles
- only; a busy one keeps its lease so its successor recovers) release the
- lease, so another node can take the profile at once.
-- **Node ids** (`node_id`, else `OPENHUMAN_NODE_ID`, else random per process)
- must be unique among live nodes. A stable one lets a restarted node take
- its own profiles back at once instead of waiting out their leases.
-
-Known limits: storage writes carry no epoch fence, so a node that is
-partitioned but still running could write after its lease expired; the TTL
-being much longer than the renew interval, the fence check before each turn
-and stopping turns on loss are the mitigations. Each node keeps its own
-operator keyring (`operator_dir`), so a credential installed through one node
-is only readable there unless secrets live in the storage backend.
++Each file's tests sit beside it (`*_tests.rs`), including property suites for
++ids (`types_proptest_tests.rs`) and the tenant key
++(`core/runtime/tenant_proptest_tests.rs`). End to end:
++`tests/saas_mode_e2e.rs` (the gateway, two users on one thread id, relayed
++channel threads, `409`) and `crates/openhuman-embed/tests/saas_profiles.rs`
++(the in-process `ProfileRuntime`).
+
- A re-open after an eviction never sweeps again, because this process may still be running one of that profile's turns.
++## Known limits
+
- User cron jobs are not served yet: the cron RPCs are not on the user surface.
++- Thread JSONL, the local memory engine, the cost and run ledgers, background
++ completions and the sandbox stay as files under `users/<id>/workspace`, so a
++ multi-node deployment needs `<root>` on a shared read-write-many volume and
++ a remote memory engine. Moving those onto the storage ports is a follow-up.
++- Storage writes carry no epoch fence, so a node that is partitioned but still
++ running could write after its lease expired. The mitigations are a TTL much
++ longer than the renew interval, the fence check before each turn, and
++ stopping turns when the lease is lost.
++- Each node keeps its own operator keyring (`operator_dir`), so a credential
++ installed through one node is only readable there unless secrets live in
++ the storage backend.
++- Existing `agents/u-*` data is orphaned.
diff --cc crates/openhuman-core/src/storage/README.md
index 2d1bdbb0d2,a57da9739f,2a562e2f13..08f882ebee
--- a/crates/openhuman-core/src/storage/README.md
+++ b/crates/openhuman-core/src/storage/README.md
@@@@ -94,15 -91,6 -94,12 +94,15 @@@@ reference model
## Consumers
+ - The SaaS profile host (`profiles::lease`, `profiles::registry`): one
+ lease per profile (`DocumentLeases` over the installed backend, else
+ `LocalLeases` under `<root>/users`) and the profile registry, collection
+ `profiles` in the same `cluster` scope. A lease taken over unclean runs
+ the profile's workspace recovery; a lost one fences the profile. See
- `profiles/README.md`.
++ `profiles/README.md`. The server opens the operator's storage URL before
++ boot (`openhuman-rpc`'s `session_store::install_for_saas`);
++ `openhuman_embed::ProfileRuntime` opens and installs it itself when no
++ backend is installed yet.
- The session store: `openhuman_rpc::session_store::install_for_host` opens
the configured backend before boot and installs `DriverSessionStores`
over it. See that module's README.
diff --cc crates/openhuman-embed/README.md
index 33eb2854bf,6ea2dc4557,6ea2dc4557..c342b18199
--- a/crates/openhuman-embed/README.md
+++ b/crates/openhuman-embed/README.md
@@@@ -505,12 -448,11 -448,11 +505,12 @@@@ agent to another. See [`src/agent/READM
| [`src/call.rs`](src/call.rs) | The private typed dispatch helper over `CoreRuntime::invoke` that every facade method uses. |
| [`src/config.rs`](src/config.rs), [`src/auth.rs`](src/auth.rs), [`src/core_agent.rs`](src/core_agent.rs) | The `Core` sub-facades: runtime flags, credentials (`Session`, `AuthState`), and the orchestrator turn. |
| [`src/memory.rs`](src/memory.rs) | `Memory`, the per-tenant memory facade returned by `Runtime::memory`. |
++| [`src/profiles.rs`](src/profiles.rs), [`src/profiles/handle.rs`](src/profiles/handle.rs) | `ProfileRuntime`, `ProfileRuntimeBuilder`, `ProfileHandle`, `ProfileEvents`, `ProfileError`: SaaS profiles in-process (locks the process to SaaS mode). |
| [`src/process.rs`](src/process.rs), [`src/process_sentry.rs`](src/process_sentry.rs) | Host lifecycle helpers: the agent-sized tokio runtime, logging init, dotenv and launch overrides, the master key, and (`crash-reporting`) the Sentry `ClientOptions` with the single `before_send` chain. |
| [`src/artifacts.rs`](src/artifacts.rs), [`src/chat_surface.rs`](src/chat_surface.rs), [`src/identity.rs`](src/identity.rs), [`src/modules.rs`](src/modules.rs) | Curated host facades: artifact file resolution, the in-process web-chat event stream, the signed-in identity peek, bundled module releases. `config` also carries `load_or_init`, `load_config_with_timeout`, `default_root_openhuman_dir`, `read_active_user_id`. |
- | [`src/host_internals.rs`](src/host_internals.rs) | `__host` (doc-hidden): an explicit list of core modules for `openhuman-tinyhumans` and `openhuman-rpc` only. |
+ | [`src/host_internals.rs`](src/host_internals.rs) | `__host` (doc-hidden): an explicit list of core items (nested modules mirroring the core paths, each entry used by a named consumer) for `openhuman-tinyhumans` and `openhuman-rpc` only. |
| [`src/error.rs`](src/error.rs) | `CoreError`, the error every facade call returns (`Domain`, `Unavailable`, `Rpc`, route refusals). |
--| [`examples/`](examples/README.md) | Runnable programs: one turn on a harness, and two agents on one runtime. |
++| [`examples/`](examples/README.md) | Runnable programs: one turn on a harness, two agents on one runtime, and two users' profiles on one thread id. |
| [`tests/`](tests/README.md) | End-to-end suites against `wiremock` providers. |
## Key types and entry points
diff --cc crates/openhuman-embed/src/host_internals.rs
index 4ea9a5012d,159c4b75b2,736b7d2cf1..d7115f8469
--- a/crates/openhuman-embed/src/host_internals.rs
+++ b/crates/openhuman-embed/src/host_internals.rs
@@@@ -2,16 -2,339 -2,343 +2,343 @@@@
//! (`openhuman-tinyhumans`, `openhuman-rpc`), and nothing else.
//!
//! Those layers implement the backend transport, the hosted controllers and
- //! the JSON-RPC server, which reach deep into the core by nature. Routing
- //! them through this module keeps the dependency chain strict (they need no
+ //! the JSON-RPC server, which reach into the core by nature. Routing them
+ //! through this module keeps the dependency chain strict (they need no
//! `openhuman-core` dependency of their own) without inventing a public API
- //! for every server internal. It is an explicit list of modules, not a glob:
- //! a new reach-in is added here on purpose. Hosts (app, CLI, TUI) use the
- //! curated facade at the crate root instead.
-
- pub use openhuman_core::{
- agent, backend, channels, config, core, desktop, inference, integrations, mcp, platform,
- profiles, security, storage, tools, util, voice, web3, web_chat,
- };
+ //! for every server internal.
+ //!
+ //! This is an explicit list of items, not a glob of modules: every entry is a
+ //! symbol one of the two consumers named in its group actually uses, and a new
+ //! reach-in is added here on purpose. The nested module layout mirrors the
+ //! core's paths so a consumer's `__host::a::b::item` reads like the core path.
+ //! Hosts (app, CLI, TUI) never see this module: the curated facade at the
+ //! crate root is theirs, and the layers above embed re-export no part of it
+ //! (`scripts/ci/check-crate-chain.mjs` enforces that).
pub use openhuman_core::run_core_from_args;
+
+ /// Shared by tinyhumans (hosted controllers) and rpc (`http_host`, `/health`).
+ pub mod core {
+ pub use openhuman_core::core::{
+ unwrap_rpc, ControllerSchema, FieldSchema, Outcome, StructuredRpcError, TypeSchema,
+ };
+
+ pub mod all {
+ // tinyhumans: hosted controller extension; rpc: http_host + `/health`.
+ pub use openhuman_core::core::all::{
+ all_controller_schemas, all_http_method_schemas, cli_handler_for_namespace,
+ namespace_description, register_controller_extension, rpc_method_from_parts,
+ schema_for_rpc_method, ControllerExtension, ControllerFuture, DomainGroup,
+ RegisteredController,
+ };
+ }
+
+ /// Error classification shared by the hosted client (tinyhumans) and the
+ /// RPC handler and classifier (rpc).
+ pub mod observability {
+ pub use openhuman_core::core::observability::{
+ contains_transient_transport_phrase, expected_error_kind, is_api_key_rejected_message,
+ is_session_expired_message, is_suppressed_usage_probe_backoff,
+ is_transient_http_status_code, is_transient_message_failure, report_error_or_expected,
- report_warning_message, API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX,
- REPORT_ERROR_TRACING_TARGET,
+ + report_warning_message, ExpectedErrorKind, API_KEY_REJECTED_PREFIX,
+ + BACKEND_UNAVAILABLE_PREFIX, REPORT_ERROR_TRACING_TARGET,
+ };
+ }
+
+ // rpc server only, below.
+ pub mod auth {
+ pub use openhuman_core::core::auth::{
+ bearer_matches, get_rpc_token, init_rpc_token, init_rpc_token_with_value,
+ verify_bearer_token, CORE_TOKEN_ENV_VAR,
+ };
+ }
+ pub mod bus {
+ pub use openhuman_core::core::bus::{init, BUS};
+ }
+ pub mod cli {
+ pub use openhuman_core::core::cli::load_dotenv_for_cli;
+ }
+ pub mod dispatch {
+ pub use openhuman_core::core::dispatch::{
+ is_known_probe_method, unknown_method_name, UNKNOWN_METHOD_PREFIX,
+ };
+ }
+ pub mod event_bind_tokens {
+ pub use openhuman_core::core::event_bind_tokens::{consume, issue};
+ }
+ pub mod events {
+ // `DomainEvent` is matched variant by variant by the Socket.IO bridge.
+ pub use openhuman_core::core::events::DomainEvent;
+ }
+ pub mod invoke {
+ pub use openhuman_core::core::invoke::{default_state, invoke_method};
+ }
+ pub mod params {
+ pub use openhuman_core::core::params::{
+ is_param_validation_error, missing_required_param_message, unknown_param_message,
+ };
+ }
+ pub mod runtime {
+ pub use openhuman_core::core::runtime::{
+ current_tenant, is_saas, CoreContext, CoreRuntime, Mode, SaasConfig,
+ };
+ pub mod saas {
+ pub use openhuman_core::core::runtime::saas::build;
+ }
+ }
+ pub mod server_launcher {
+ pub use openhuman_core::core::server_launcher::{install_server_launcher, ServeRequest};
+ }
+ pub mod session_expiry {
+ pub use openhuman_core::core::session_expiry::is_session_expired_error;
+ }
+ pub mod shutdown {
+ pub use openhuman_core::core::shutdown::{register, signal};
+ }
+ pub mod types {
+ pub use openhuman_core::core::types::AppState;
+ }
+ }
+
+ /// tinyhumans (backend transport, hosted client, team ops) and rpc (`/health`).
+ pub mod backend {
+ pub use openhuman_core::backend::{
+ base_url, flatten_authed_error, BackendApiError, BackendClient,
+ };
+
+ pub mod transport {
+ pub use openhuman_core::backend::transport::{
+ clear_backend_transport, resolve_backend_transport, BackendTransport,
+ BackendTransportError, TransportProfile,
+ };
+ }
+ }
+
+ /// tinyhumans (every hosted controller loads its config) and rpc (server).
+ pub mod config {
+ pub use openhuman_core::config::{
+ active_workspace_dir, active_workspace_dir_cached, active_workspace_snapshot,
+ load_config_with_timeout, workspace_handle, Config,
+ };
+
+ pub mod app_env {
+ // tinyhumans: backend URL selection.
+ pub use openhuman_core::config::app_env::{
+ app_env_from_env, is_staging_app_env, APP_ENV_VAR, VITE_APP_ENV_VAR,
+ };
+ }
+ pub mod ops {
+ pub use openhuman_core::config::ops::load_config_with_timeout;
+ }
+ pub mod rpc {
+ pub use openhuman_core::config::rpc::load_config_with_timeout;
+ }
+ pub mod schema {
+ pub mod cloud_providers {
+ pub use openhuman_core::config::schema::cloud_providers::{
+ endpoint_host, host_is_builtin_cloud_provider,
+ };
+ }
+ }
+ }
+
+ /// tinyhumans: the Jev tool ranker and the jev route.
+ pub mod agent {
+ pub mod tinyagents {
+ pub mod discovery {
+ pub use openhuman_core::agent::tinyagents::discovery::{
+ embedding_provider_is_usable, embedding_tool_ranker, install_tool_ranker,
+ installed_tool_ranker,
+ };
+ }
+ // rpc: Socket.IO run-mode toggles.
+ pub mod run_mode {
+ pub use openhuman_core::agent::tinyagents::run_mode::{parse_mode_label, set_mode};
+ }
+ }
+ // rpc: shutdown, plan review over Socket.IO, and the session store install.
+ pub mod orchestration {
+ pub use openhuman_core::agent::orchestration::release_background_completion_stores;
+ }
+ pub mod plan_review {
+ pub mod gate {
+ pub use openhuman_core::agent::plan_review::gate::global;
+ }
+ }
+ pub mod session_store {
+ pub use openhuman_core::agent::session_store::{
+ context_workspace_dir, install, installed, restore,
+ };
+ }
+ }
+
+ /// tinyhumans: the channel-link controller schema.
+ pub mod channels {
+ pub mod contract_schema {
+ pub use openhuman_core::channels::contract_schema::contract_controller_schema;
+ }
+ }
+
+ /// tinyhumans: embeddings and provider-key lookup for the Jev ranker; rpc: the
+ /// OpenAI-compatible HTTP router.
+ pub mod inference {
+ pub mod embedding_host {
+ pub use openhuman_core::inference::embedding_host::default_embedding_provider_with_config;
+ }
+ pub mod provider {
+ pub mod factory {
+ pub use openhuman_core::inference::provider::factory::lookup_key_for_slug;
+ }
+ }
+ pub mod http {
+ #[cfg(feature = "http-server")]
+ pub use openhuman_core::inference::http::router;
+ pub use openhuman_core::inference::http::EXTERNAL_OPENAI_COMPAT_PROVIDER;
+ }
+ }
+
+ /// tinyhumans: the team ops budget gate.
+ pub mod integrations {
+ pub mod client {
+ pub use openhuman_core::integrations::client::budget_gate;
+ }
+ }
+
+ /// tinyhumans (credentials for the hosted client) and rpc (server auth,
+ /// Socket.IO approvals, bind policy).
+ pub mod security {
+ pub mod credentials {
+ pub use openhuman_core::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+ };
+ pub mod ops {
+ pub use openhuman_core::security::credentials::ops::{
+ list_provider_credentials, store_provider_credentials,
+ };
+ }
+ pub mod session_support {
+ pub use openhuman_core::security::credentials::session_support::{
+ build_session_state, current_session_is_local, resolve_backend_credential,
+ BackendCredential, LOCAL_SESSION_BACKEND_UNAVAILABLE,
+ };
+ }
+ }
+ pub mod approval {
+ pub use openhuman_core::security::approval::ApprovalGate;
+ }
+ pub mod pairing {
+ pub use openhuman_core::security::pairing::is_public_bind;
+ }
+ }
+
+ /// tinyhumans: TLS, URL and redaction helpers for the backend client.
+ pub mod util {
+ pub use openhuman_core::util::redact_url_for_log;
+
+ pub mod redact {
+ pub use openhuman_core::util::redact::redact_url_for_log;
+ }
+ pub mod tls {
+ pub use openhuman_core::util::tls::tls_client_builder;
+ }
+ pub mod url {
+ pub use openhuman_core::util::url::{
+ host_is_local, join_url, normalize_api_base_url, normalize_backend_api_base_url,
+ };
+ }
+ }
+
+ // The rest is the rpc server alone.
+
+ pub mod desktop {
+ pub mod notifications {
+ pub use openhuman_core::desktop::notifications::subscribe_core_notifications;
+ }
+ pub mod overlay {
+ pub use openhuman_core::desktop::overlay::subscribe_attention_events;
+ }
+ }
+
+ pub mod mcp {
+ pub mod registry {
+ pub mod oauth {
+ pub use openhuman_core::mcp::registry::oauth::complete;
+ }
+ }
+ }
+
+ pub mod platform {
+ pub mod connectivity {
+ pub mod rpc {
+ pub use openhuman_core::platform::connectivity::rpc::{
+ pick_listen_port_for_host_with, OccupiedByCore,
+ };
+ }
+ }
+ pub mod health {
+ pub use openhuman_core::platform::health::{snapshot, verdict};
+ }
+ }
+
+ pub mod storage {
+ pub use openhuman_core::storage::{
+ block_on_anyhow, clear, configured_url, driver_is_shared, install, installed, open,
+ url_from, StorageBackend, STORAGE_URL_VAR,
+ };
+ }
+
+ pub mod profiles {
+ pub mod gateway {
+ pub use openhuman_core::profiles::gateway::{
- resolve_scope, sign, verify, GatewayRefusal, GatewayScope, USER_HEADER, USER_SIG_HEADER,
++ resolve_scope, sign, verify, GatewayRefusal, GatewayScope, HeldBy, PROFILE_HELD,
++ PROFILE_OWNER_HEADER, USER_HEADER, USER_SIG_HEADER,
+ };
+ }
++ pub mod host {
++ pub use openhuman_core::profiles::host::host;
++ }
+ }
+
+ pub mod voice {
+ pub mod dictation_listener {
+ pub use openhuman_core::voice::dictation_listener::{
+ subscribe_dictation_events, subscribe_transcription_results,
+ };
+ }
+ // The core carries the live-voice and dictation sockets only with voice and
+ // the HTTP server compiled in. Where its features differ from embed's (a
+ // workspace build unifies them separately), rpc still names these paths, so
+ // embed supplies a socket-dropping stand-in rather than a missing item.
+ pub mod live {
+ pub mod ws {
+ #[cfg(all(feature = "voice", feature = "http-server"))]
+ pub use openhuman_core::voice::live::ws::handle_live_voice_ws;
+ #[cfg(not(all(feature = "voice", feature = "http-server")))]
+ pub async fn handle_live_voice_ws<S, C>(_socket: S, _config: C) {}
+ }
+ }
+ pub mod streaming {
+ #[cfg(all(feature = "voice", feature = "http-server"))]
+ pub use openhuman_core::voice::streaming::handle_dictation_ws;
+ #[cfg(not(all(feature = "voice", feature = "http-server")))]
+ pub async fn handle_dictation_ws<S, C>(_socket: S, _config: C) {}
+ }
+ }
+
+ pub mod web3 {
+ pub mod wallet {
+ pub use openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE;
+ }
+ }
+
+ pub mod web_chat {
+ pub use openhuman_core::web_chat::{
+ approval_request_event, cancel_chat_scoped, plan_review_request_event,
+ publish_web_channel_event, start_chat, subscribe_web_channel_events, unix_epoch_ms,
+ ChatRequestMetadata, GuardrailPayload, StartChatError, WebChannelEvent,
+ };
+ }
+
+ #[cfg(test)]
+ #[path = "host_internals_tests.rs"]
+ mod tests;
diff --cc scripts/ci/saas-ambient-baseline.json
index e01f346184,b9553e1f00,716f00a919..a73af53a90
--- a/scripts/ci/saas-ambient-baseline.json
+++ b/scripts/ci/saas-ambient-baseline.json
@@@@ -191,7 -184,7 -184,7 +184,7 @@@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/channels/runtime/startup/start_channels.rs",
--- "line": 370,
+++ "line": 225,
"text": "let provider_bridge = AbortOnDropHandle::new(tokio::spawn(async move {",
"occurrence": 1
},
@@@@ -611,7 -632,7 -604,7 +604,7 @@@@
{
"rule": "ambient-config",
"path": "crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs",
--- "line": 49,
+++ "line": 66,
"text": "let config = crate::config::Config::load_or_init()",
"occurrence": 1
},
@@@@ -814,7 -849,7 -807,7 +807,7 @@@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/modules/ops.rs",
--- "line": 256,
+++ "line": 274,
"text": "let found_on_search_path = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},
@@@@ -1059,7 -1129,7 -1059,7 +1059,7 @@@@
{
"rule": "bare-spawn",
"path": "crates/openhuman-core/src/threads/ops/edit.rs",
--- "line": 363,
+++ "line": 379,
"text": "let result = tokio::task::spawn_blocking(move || {",
"occurrence": 1
},