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
Merge upstream/main into saas-lease-fencing
Steven Enamakele3b57573d38c
diff --cc crates/openhuman-core/src/profiles/README.mdindex 9835c6af61,9995282385..f55cfd4fb0--- a/crates/openhuman-core/src/profiles/README.md+++ b/crates/openhuman-core/src/profiles/README.md@@@ -44,27 -69,113 +69,125 @@@ 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()` |- | `fence.rs` | The profile's lease fence: the scopes its grant guards (its own scope and every `<profile>~<agent>` session scope), the skew margin, and how the host registers, renews, latches and retires it |- | `recovery.rs` | Workspace and session-store recovery after an unclean takeover |- | `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.++ 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.++- **Write fencing.** Opening a profile registers a lease fence++ (`storage::fence`, built by `profiles::fence`) for its grant. Every write++ through the storage ports to the profile's scope or one of its session++ scopes is refused with a typed `FenceError` when the fence is latched, when++ the grant has run out by this node's clock less a skew margin (a sixth of++ the TTL), or when the stored lease record no longer names this node at this++ epoch (which latches it). A takeover therefore stops the old holder's next++ write, before its heartbeat notices. `ensure_hosted` refuses new turns on++ the latch or a locally expired grant, and the background loop checks the++ fence against the record before a profile's jobs and drops them if it++ latches mid-run. A latched fence keeps refusing for as long as the fenced++ profile's context is alive; a clean release retires it.+ - **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@@@ -189,92 -288,55 +300,67 @@@ 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.+ 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.- ## 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.+ 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.- The lease drives the rest:+ ## Files- - **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.+ | 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()` |++| `fence.rs` | The profile's lease fence: the scopes its grant guards (its own scope and every `<profile>~<agent>` session scope), the skew margin, and how the host registers, renews, latches and retires it |++| `recovery.rs` | Workspace and session-store recovery after an unclean takeover |+ | `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) |- - **Write fencing.** Opening a profile registers a lease fence- (`storage::fence`, built by `profiles::fence`) for its grant. Every write- through the storage ports to the profile's scope or one of its session- scopes is refused with a typed `FenceError` when the fence is latched, when- the grant has run out by this node's clock less a skew margin (a sixth of- the TTL), or when the stored lease record no longer names this node at- this epoch (which latches it). A takeover therefore stops the old holder's- next write, before its heartbeat notices. `ensure_hosted` refuses new- turns on the latch or a locally expired grant, and the background loop- checks the fence against the record before a profile's jobs and drops them- if it latches mid-run. A latched fence keeps refusing for as long as the- fenced profile's context is alive; a clean release retires it.+ 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:+ ## 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.+- The fence check and the write are two operations: a holder paused for+ longer than the skew margin right after a passing check can still land one+ write after a takeover. Closing that needs a driver-enforced conditional+ write (see `storage/README.md`).+- Only writes through the storage ports are fenced. Files a profile writes+ directly under `<root>/users/<id>/` (the memory job queue, the classic+ on-disk stores) are not; on a shared volume, stopping turns and jobs on+ fence is the mitigation.+- A node that re-opens a profile after being fenced registers a new fence;- work left over from its older grant is stopped by turn cancellation, not- by the fence.++ work left over from its older grant is stopped by turn cancellation, not by++ the fence.+- With file leases (no backend) nothing goes through the ports, and the- `flock` cannot be lost while the process lives, so the fence only backs- the latch checks.-- 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.++ `flock` cannot be lost while the process lives, so the fence only backs the++ latch checks.+ - 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.