Skip to content

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

Merge remote-tracking branch 'upstream/main' into saas-profile-lifecycle

Steven Enamakelccdae80672bd
diff --cc crates/openhuman-core/src/profiles/README.md
index beb2e704d3,9995282385..4f031f149b
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@@ -12,18 -26,27 +26,27 @@@ Two hosts drive it
```text
<root>/users/<profile-id>/ the desktop's users/<id> shape (config::schema::ProfileLayout)
profile.toml ProfileMeta (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
- .lease, .lease.json the file-lock lease (only without a storage backend)
+ 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>/users/<sha256(id)>/.lease the file-lock lease and its record (only without a storage backend)
<root>/deprovisioned/<id>-<secs>-<uuid>/ an archived profile
<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
@@@ -44,26 -69,113 +69,143 @@@ Provisioning also refuses a profile id
`operator_dir`: keyring secrets are namespaced by their store's directory name,
so such a profile would share the operator's credential slots.
- 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 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. `ProfileRuntime` may include the profile id in debug logs
+ during `provision` and `open`; do not treat debug logs as profile-id-free.
- ## 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 behind the profile lease, LRU and idle eviction (never of a profile in use), release, fencing, each profile's derived `CoreContext`, `current()`, `ensure_hosted()` |
- | `lifecycle.rs` | Provisioning, deprovisioning and credential changes, and `ProfileLocks`: the per-profile lock that keeps one profile's lifecycle operations from interleaving (see [Lifecycle](#lifecycle)) |
- | `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` / `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.
++ `<root>/users/<sha256(id)>/.lease` (outside the profile's own directory,
++ so archiving it leaves the lease in place), 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.
+
++## Lifecycle
++
++Provisioning, opening, credential changes (`profiles.set_credential` /
++`clear_credential`) and deprovisioning of one profile never interleave
++(`lifecycle.rs`):
++
++- **In one process**, each takes the profile's own lock (`ProfileLocks`, one
++ async mutex per profile id, forgotten once nobody holds or waits for it),
++ then the host's gate where it touches open profiles or leases. Different
++ profiles do not wait for each other's lock; lookups of an open profile take
++ neither. A credential change waits for an archive in flight and then finds
++ the profile gone, so a late credential never lands in the keyring slot a
++ re-provisioned profile would inherit.
++- **Deprovisioning** closes the profile in the same step that finds it idle,
++ so no request picks it up in between, and holds its lease from before the
++ credential is cleared until the directory is archived and the record
++ removed. It gives the lease back on every failure.
++- **Provisioning a new profile** lays it out under its lease and refuses
++ while another node holds it.
++- **Opening** reads the registry again once it holds the lease: an open that
++ raced a deprovision on another node answers `NotProvisioned` instead of
++ recreating the archived directory.
++
++Credential changes take no lease: the profile is normally hosted by some node
++while the gateway installs a credential, and must not be refused for it. So
++across nodes they are not ordered against a deprovision running elsewhere.
++That only matters when secrets live in the storage backend; per-node
++keyrings (see [Known limits](#known-limits)) never share a slot across nodes.
++
+ ## 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
@@@ -188,95 -288,55 +318,56 @@@ 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.
-
- 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/<sha256(id)>/.lease` (outside the profile's own directory,
- so archiving it leaves the lease in place), which keeps two processes on
- one root apart and drops when its holder dies.
-
- The lease drives the rest:
-
- - **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.
+ 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.
- ## Lifecycle
+ 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.
- Provisioning, opening, credential changes (`profiles.set_credential` /
- `clear_credential`) and deprovisioning of one profile never interleave
- (`lifecycle.rs`):
+ ## Files
- - **In one process**, each takes the profile's own lock (`ProfileLocks`, one
- async mutex per profile id, forgotten once nobody holds or waits for it),
- then the host's gate where it touches open profiles or leases. Different
- profiles do not wait for each other's lock; lookups of an open profile take
- neither. A credential change waits for an archive in flight and then finds
- the profile gone, so a late credential never lands in the keyring slot a
- re-provisioned profile would inherit.
- - **Deprovisioning** closes the profile in the same step that finds it idle,
- so no request picks it up in between, and holds its lease from before the
- credential is cleared until the directory is archived and the record
- removed. It gives the lease back on every failure.
- - **Provisioning a new profile** lays it out under its lease and refuses
- while another node holds it.
- - **Opening** reads the registry again once it holds the lease: an open that
- raced a deprovision on another node answers `NotProvisioned` instead of
- recreating the archived directory.
+ | 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()` |
++| `lifecycle.rs` | Provisioning, deprovisioning and credential changes, and `ProfileLocks`: the per-profile lock that keeps one profile's lifecycle operations from interleaving (see [Lifecycle](#lifecycle)) |
+ | `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) |
- Credential changes take no lease: the profile is normally hosted by some node
- while the gateway installs a credential, and must not be refused for it. So
- across nodes they are not ordered against a deprovision running elsewhere.
- That only matters when secrets live in the storage backend; per-node
- keyrings (above) never share a slot across nodes.
+ 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`).
+
+ ## Known limits
+
+ - 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.