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
refactor(user_agents): rename profiles module to user_agents
Steven Enamakela3d7a5146375
diff --git a/crates/openhuman-core/src/user_agents/README.md b/crates/openhuman-core/src/profiles/README.mdsimilarity index 100%rename from crates/openhuman-core/src/user_agents/README.mdrename to crates/openhuman-core/src/profiles/README.mddiff --git a/crates/openhuman-core/src/user_agents/background.rs b/crates/openhuman-core/src/profiles/background.rssimilarity index 82%rename from crates/openhuman-core/src/user_agents/background.rsrename to crates/openhuman-core/src/profiles/background.rsindex 27164c5532..2fb60ef8ef 100644--- a/crates/openhuman-core/src/user_agents/background.rs+++ b/crates/openhuman-core/src/profiles/background.rs@@ -19,7 +19,7 @@use std::sync::Arc;use std::time::Duration;-use super::host::AgentHost;+use super::host::ProfileHost;use crate::core::runtime::CoreContext;use crate::memory::lifecycle::jobs::{self, Selection};@@ -36,10 +36,10 @@ pub struct TickReport {}/// Start the loop. It runs until the process exits.-pub fn spawn(host: Arc<AgentHost>) -> tokio::task::JoinHandle<()> {+pub fn spawn(host: Arc<ProfileHost>) -> tokio::task::JoinHandle<()> {crate::core::runtime::spawn_scoped(async move {log::info!(- "[user_agents][background] started (every {}s)",+ "[profiles][background] started (every {}s)",TICK_INTERVAL.as_secs());let mut interval = tokio::time::interval(TICK_INTERVAL);@@ -49,7 +49,7 @@ pub fn spawn(host: Arc<AgentHost>) -> tokio::task::JoinHandle<()> {let report = tick(&host).await;if report != TickReport::default() {log::debug!(- "[user_agents][background] tick ran={} skipped={}",+ "[profiles][background] tick ran={} skipped={}",report.ran,report.skipped);@@ -59,25 +59,25 @@ pub fn spawn(host: Arc<AgentHost>) -> tokio::task::JoinHandle<()> {}/// One visit to every provisioned agent.-pub async fn tick(host: &AgentHost) -> TickReport {+pub async fn tick(host: &ProfileHost) -> TickReport {host.evict_idle();let mut report = TickReport::default();let agents = match host.list() {Ok(agents) => agents,Err(error) => {- log::warn!("[user_agents][background] listing agents failed: {error}");+ log::warn!("[profiles][background] listing agents failed: {error}");return report;}};for summary in agents {- let id = summary.agent_id;+ let id = summary.profile_id;if !jobs::has_pending(&host.layout_of(&id).workspace_dir) {continue;}let state = match host.open(&id) {Ok(state) => state,Err(error) => {- log::debug!("[user_agents][background] agent={id} not opened: {error}");+ log::debug!("[profiles][background] agent={id} not opened: {error}");report.skipped += 1;continue;}@@ -90,13 +90,13 @@ pub async fn tick(host: &AgentHost) -> TickReport {match result {Ok(runs) => {log::debug!(- "[user_agents][background] agent={id} ran {} memory job(s)",+ "[profiles][background] agent={id} ran {} memory job(s)",runs.len());report.ran += 1;}Err(error) => {- log::debug!("[user_agents][background] agent={id} memory jobs not run: {error}");+ log::debug!("[profiles][background] agent={id} memory jobs not run: {error}");report.skipped += 1;}}diff --git a/crates/openhuman-core/src/user_agents/background_tests.rs b/crates/openhuman-core/src/profiles/background_tests.rssimilarity index 76%rename from crates/openhuman-core/src/user_agents/background_tests.rsrename to crates/openhuman-core/src/profiles/background_tests.rsindex 0bf77fe0e6..5c234630af 100644--- a/crates/openhuman-core/src/user_agents/background_tests.rs+++ b/crates/openhuman-core/src/profiles/background_tests.rs@@ -1,15 +1,15 @@use super::*;use crate::core::runtime::{CoreContext, DomainSet, SaasConfig};use crate::memory::lifecycle::jobs::enqueue;-use crate::user_agents::layout::agent_config;-use crate::user_agents::UserAgentId;+use crate::profiles::layout::profile_config;+use crate::profiles::ProfileId;use tinymemory_api::{ConsolidateRequest, ItemKind, Namespace, Reach};use tinymemory_tools::BackgroundJob;-fn host(tmp: &tempfile::TempDir, idle_secs: u64) -> AgentHost {+fn host(tmp: &tempfile::TempDir, idle_secs: u64) -> ProfileHost {let mut saas = SaasConfig::new(tmp.path());saas.idle_evict_secs = idle_secs;- AgentHost::new(saas, CoreContext::for_test(DomainSet::full(), None))+ ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None))}fn build_job() -> BackgroundJob {@@ -24,7 +24,7 @@ async fn nothing_to_do_does_nothing() {let tmp = tempfile::tempdir().unwrap();let host = host(&tmp, 3600);assert_eq!(tick(&host).await, TickReport::default());- let id = UserAgentId::for_user(&format!("idle-{}", uuid::Uuid::new_v4())).unwrap();+ let id = ProfileId::for_user(&format!("idle-{}", uuid::Uuid::new_v4())).unwrap();host.provision(&id).unwrap();assert_eq!(tick(&host).await, TickReport::default());assert!(@@ -37,12 +37,12 @@ async fn nothing_to_do_does_nothing() {async fn only_agents_with_queued_memory_jobs_are_run() {let tmp = tempfile::tempdir().unwrap();let host = host(&tmp, 3600);- let busy = UserAgentId::for_user(&format!("busy-{}", uuid::Uuid::new_v4())).unwrap();- let quiet = UserAgentId::for_user(&format!("quiet-{}", uuid::Uuid::new_v4())).unwrap();+ let busy = ProfileId::for_user(&format!("busy-{}", uuid::Uuid::new_v4())).unwrap();+ let quiet = ProfileId::for_user(&format!("quiet-{}", uuid::Uuid::new_v4())).unwrap();host.provision(&busy).unwrap();host.provision(&quiet).unwrap();- let config = agent_config(&host.layout_of(&busy), &busy);+ let config = profile_config(&host.layout_of(&busy), &busy);crate::memory::test_fixtures::bind_reference(&config);enqueue(&config, &Namespace::ROOT, vec![build_job()]).await;assert!(jobs::has_pending(&config.workspace_dir));@@ -60,7 +60,7 @@ async fn only_agents_with_queued_memory_jobs_are_run() {async fn a_tick_sweeps_idle_agents() {let tmp = tempfile::tempdir().unwrap();let host = host(&tmp, 0);- let id = UserAgentId::for_user(&format!("sweep-{}", uuid::Uuid::new_v4())).unwrap();+ let id = ProfileId::for_user(&format!("sweep-{}", uuid::Uuid::new_v4())).unwrap();host.provision(&id).unwrap();drop(host.open(&id).unwrap());assert!(host.is_open(&id));diff --git a/crates/openhuman-core/src/user_agents/credentials.rs b/crates/openhuman-core/src/profiles/credentials.rssimilarity index 96%rename from crates/openhuman-core/src/user_agents/credentials.rsrename to crates/openhuman-core/src/profiles/credentials.rsindex 2f39aedc0c..ab2cefc859 100644--- a/crates/openhuman-core/src/user_agents/credentials.rs+++ b/crates/openhuman-core/src/profiles/credentials.rs@@ -81,13 +81,13 @@ pub fn store(UserCredentialKind::ApiKey => remove_provider(config, APP_SESSION_PROVIDER),};if let Err(error) = replaced {- log::warn!("[user_agents][credentials] stored {kind:?} but could not remove the other kind: {error}");+ log::warn!("[profiles][credentials] stored {kind:?} but could not remove the other kind: {error}");return Err(format!("stored the new credential but could not remove the previous one: {error}"));}log::debug!(- "[user_agents][credentials] stored {kind:?} credential in {}",+ "[profiles][credentials] stored {kind:?} credential in {}",config.config_path.parent()diff --git a/crates/openhuman-core/src/user_agents/credentials_tests.rs b/crates/openhuman-core/src/profiles/credentials_tests.rssimilarity index 92%rename from crates/openhuman-core/src/user_agents/credentials_tests.rsrename to crates/openhuman-core/src/profiles/credentials_tests.rsindex 8b0129ba76..5dad7e6857 100644--- a/crates/openhuman-core/src/user_agents/credentials_tests.rs+++ b/crates/openhuman-core/src/profiles/credentials_tests.rs@@ -2,16 +2,16 @@ use super::*;use crate::security::credentials::session_support::{resolve_backend_credential, BackendCredential,};-use crate::user_agents::layout::{agent_config, UserAgentLayout};-use crate::user_agents::UserAgentId;+use crate::profiles::layout::{profile_config, ProfileLayout};+use crate::profiles::ProfileId;/// Credential secrets live in the process keyring keyed by agent id, which/// every test in this binary shares; each test therefore uses its own users.fn agent(tmp: &tempfile::TempDir, user: &str) -> Config {- let id = UserAgentId::for_user(&format!("{user}-{}", uuid::Uuid::new_v4())).unwrap();- let layout = UserAgentLayout::new(tmp.path(), &id);+ let id = ProfileId::for_user(&format!("{user}-{}", uuid::Uuid::new_v4())).unwrap();+ let layout = ProfileLayout::new(tmp.path(), &id);std::fs::create_dir_all(&layout.workspace_dir).unwrap();- agent_config(&layout, &id)+ profile_config(&layout, &id)}#[test]diff --git a/crates/openhuman-core/src/user_agents/gateway.rs b/crates/openhuman-core/src/profiles/gateway.rssimilarity index 92%rename from crates/openhuman-core/src/user_agents/gateway.rsrename to crates/openhuman-core/src/profiles/gateway.rsindex 3598b5cf8b..8619442ee1 100644--- a/crates/openhuman-core/src/user_agents/gateway.rs+++ b/crates/openhuman-core/src/profiles/gateway.rs@@ -22,8 +22,8 @@ use std::sync::Arc;use hmac::{Hmac, KeyInit, Mac};use sha2_011::Sha256;-use super::host::{self, UserAgentState};-use super::types::UserAgentId;+use super::host::{self, Profile};+use super::types::ProfileId;/// The gateway's user header.pub const USER_HEADER: &str = "x-openhuman-user";@@ -92,7 +92,7 @@ pub enum GatewayScope {/// No user header: the operator plane.Operator,/// One user's agent.- User(Arc<UserAgentState>),+ User(Arc<Profile>),}/// Pick the scope for a request that already presented the service bearer.@@ -108,18 +108,18 @@ pub fn resolve_scope(return Ok(GatewayScope::Operator);};let host = host::host().ok_or_else(|| GatewayRefusal::new(503, "this core serves no users"))?;- let agent = UserAgentId::for_user(user_id).map_err(|e| GatewayRefusal::new(400, e))?;+ let agent = ProfileId::for_user(user_id).map_err(|e| GatewayRefusal::new(400, e))?;if host.saas().require_user_signature {let signature = signature.ok_or_else(|| GatewayRefusal::new(401, format!("missing {USER_SIG_HEADER}")))?;verify(secret, user_id, signature, now).map_err(|e| {- log::warn!("[user_agents][gateway] refused agent={agent}: {e}");+ log::warn!("[profiles][gateway] refused agent={agent}: {e}");GatewayRefusal::new(401, e)})?;}match host.open(&agent) {Ok(state) => {- log::debug!("[user_agents][gateway] scoped request to agent={agent}");+ log::debug!("[profiles][gateway] scoped request to agent={agent}");Ok(GatewayScope::User(state))}Err(e) if e.contains("not provisioned") => Err(GatewayRefusal::new(403, e)),diff --git a/crates/openhuman-core/src/user_agents/gateway_tests.rs b/crates/openhuman-core/src/profiles/gateway_tests.rssimilarity index 100%rename from crates/openhuman-core/src/user_agents/gateway_tests.rsrename to crates/openhuman-core/src/profiles/gateway_tests.rsdiff --git a/crates/openhuman-core/src/user_agents/host.rs b/crates/openhuman-core/src/profiles/host.rssimilarity index 73%rename from crates/openhuman-core/src/user_agents/host.rsrename to crates/openhuman-core/src/profiles/host.rsindex c51a6c30ad..dd799d5d95 100644--- a/crates/openhuman-core/src/user_agents/host.rs+++ b/crates/openhuman-core/src/profiles/host.rs@@ -1,9 +1,9 @@-//! [`AgentHost`]: the user agents a SaaS process has open.+//! [`ProfileHost`]: the user agents a SaaS process has open.//!//! A user agent is opened lazily on first use and kept until it has been idle//! for [`SaasConfig::idle_evict_secs`] or the host needs its slot-//! ([`SaasConfig::max_agents_open`]). An agent still in use — anyone holding-//! its [`UserAgentState`] — is never evicted.+//! ([`SaasConfig::max_profiles_open`]). An agent still in use — anyone holding+//! its [`Profile`] — is never evicted.//!//! Each open agent carries its own [`CoreContext`], derived from the operator//! context with the agent's forced config and `session_agent` set to its id.@@ -14,29 +14,29 @@ use std::collections::HashMap;use std::sync::{Arc, Mutex, OnceLock, PoisonError};use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};-use super::layout::{self, UserAgentLayout};-use super::types::{UserAgentId, UserAgentMeta, UserAgentSummary, LAYOUT_VERSION};+use super::layout::{self, ProfileLayout};+use super::types::{ProfileId, ProfileMeta, ProfileSummary, LAYOUT_VERSION};use crate::config::Config;use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet, SaasConfig};use crate::tools::toolpacks::ToolGroups;/// One open user agent.-pub struct UserAgentState {- pub id: UserAgentId,- pub layout: UserAgentLayout,+pub struct Profile {+ pub id: ProfileId,+ pub layout: ProfileLayout,pub config: Config,context: Arc<CoreContext>,}-impl std::fmt::Debug for UserAgentState {+impl std::fmt::Debug for Profile {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("UserAgentState")+ f.debug_struct("Profile").field("id", &self.id).finish()}}-impl UserAgentState {+impl Profile {/// The context every piece of this agent's work runs under.pub fn context(&self) -> &Arc<CoreContext> {&self.context@@ -44,25 +44,25 @@ impl UserAgentState {}struct Slot {- state: Arc<UserAgentState>,+ state: Arc<Profile>,last_used: Instant,}/// The open user agents of one SaaS process.-pub struct AgentHost {+pub struct ProfileHost {saas: SaasConfig,operator: Arc<CoreContext>,- open: Mutex<HashMap<UserAgentId, Slot>>,+ open: Mutex<HashMap<ProfileId, Slot>>,/// Agents whose leftovers from a previous process were already swept/// (see [`recover_workspace`]). Kept across evictions: a re-open after an/// eviction must not mark a turn this process is still running as/// interrupted.- recovered: Mutex<std::collections::HashSet<UserAgentId>>,+ recovered: Mutex<std::collections::HashSet<ProfileId>>,}-impl std::fmt::Debug for AgentHost {+impl std::fmt::Debug for ProfileHost {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("AgentHost")+ f.debug_struct("ProfileHost").field("root", &self.saas.root).field("open", &self.open_count()).finish()@@ -80,7 +80,7 @@ pub fn user_domains() -> DomainSet {}}-impl AgentHost {+impl ProfileHost {pub fn new(saas: SaasConfig, operator: Arc<CoreContext>) -> Self {Self {saas,@@ -96,36 +96,36 @@ impl AgentHost {}/// Where agent `id`'s state lives, provisioned or not.- pub fn layout_of(&self, id: &UserAgentId) -> UserAgentLayout {+ pub fn layout_of(&self, id: &ProfileId) -> ProfileLayout {self.layout(id)}- fn layout(&self, id: &UserAgentId) -> UserAgentLayout {- UserAgentLayout::new(&self.saas.root, id)+ fn layout(&self, id: &ProfileId) -> ProfileLayout {+ ProfileLayout::new(&self.saas.root, id)}/// Create agent `id`'s directories. Returns whether it was new.- pub fn provision(&self, id: &UserAgentId) -> Result<bool, String> {+ pub fn provision(&self, id: &ProfileId) -> Result<bool, String> {// Under the open-agent lock, like `deprovision`, so the two never// interleave on one agent's directory.let _guard = self.lock();let layout = self.layout(id);if layout.meta_path.exists() {- log::debug!("[user_agents] provision agent={id}: already provisioned");+ log::debug!("[profiles] provision agent={id}: already provisioned");return Ok(false);}for dir in [&layout.workspace_dir, &layout.sandbox_dir] {std::fs::create_dir_all(dir).map_err(|e| format!("creating {}: {e}", dir.display()))?;}- let meta = UserAgentMeta {- agent_id: id.clone(),+ let meta = ProfileMeta {+ profile_id: id.clone(),created_at: unix_now(),layout_version: LAYOUT_VERSION,};let raw = toml::to_string(&meta).map_err(|e| format!("encoding agent meta: {e}"))?;std::fs::write(&layout.meta_path, raw).map_err(|e| format!("writing {}: {e}", layout.meta_path.display()))?;- log::info!("[user_agents] provisioned agent={id}");+ log::info!("[profiles] provisioned agent={id}");Ok(true)}@@ -136,7 +136,7 @@ impl AgentHost {/// re-open the agent between closing it and moving its directory. An/// agent still in use (a request holds its state) is not archived from/// under it: deprovisioning fails and can be retried.- pub fn deprovision(&self, id: &UserAgentId) -> Result<bool, String> {+ pub fn deprovision(&self, id: &ProfileId) -> Result<bool, String> {let mut open = self.lock();if let Some(slot) = open.get(id) {if Arc::strong_count(&slot.state) > 1 {@@ -151,8 +151,8 @@ impl AgentHost {// Credential secrets live in the process keyring under the agent id,// not only in the agent's directory, so archiving the directory alone// would let a re-provisioned agent pick the old credential back up.- if let Err(e) = super::credentials::clear(&layout::agent_config(&layout, id)) {- log::warn!("[user_agents] clearing credentials of agent={id} before archiving: {e}");+ if let Err(e) = super::credentials::clear(&layout::profile_config(&layout, id)) {+ log::warn!("[profiles] clearing credentials of agent={id} before archiving: {e}");}let archive = layout::archive_dir(&self.saas.root);std::fs::create_dir_all(&archive)@@ -166,22 +166,22 @@ impl AgentHost {std::fs::rename(&layout.dir, &dest).map_err(|e| format!("archiving {}: {e}", layout.dir.display()))?;drop(open);- log::info!("[user_agents] deprovisioned agent={id} (archived)");+ log::info!("[profiles] deprovisioned agent={id} (archived)");Ok(true)}/// The forced config of provisioned agent `id`, without opening it (and/// so without taking an agent slot).- pub fn provisioned_config(&self, id: &UserAgentId) -> Result<crate::config::Config, String> {+ pub fn provisioned_config(&self, id: &ProfileId) -> Result<crate::config::Config, String> {let layout = self.layout(id);if !layout.meta_path.exists() {return Err(format!("agent {id} is not provisioned"));}- Ok(layout::agent_config(&layout, id))+ Ok(layout::profile_config(&layout, id))}/// Agent `id`, opening it if it is provisioned and not open yet.- pub fn open(&self, id: &UserAgentId) -> Result<Arc<UserAgentState>, String> {+ pub fn open(&self, id: &ProfileId) -> Result<Arc<Profile>, String> {let now = Instant::now();let mut open = self.lock();if let Some(slot) = open.get_mut(id) {@@ -199,10 +199,10 @@ impl AgentHost {return Err(format!("agent {id} is not provisioned"));}self.evict_locked(&mut open, now);- if open.len() >= self.saas.max_agents_open.max(1) {+ if open.len() >= self.saas.max_profiles_open.max(1) {return Err(format!("all {} agent slots are in use; try again shortly",- self.saas.max_agents_open+ self.saas.max_profiles_open));}@@ -214,13 +214,13 @@ impl AgentHost {if first_open {recover_workspace(id, &layout.workspace_dir);}- let config = layout::agent_config(&layout, id);+ let config = layout::profile_config(&layout, id);let context = self.operator.derive_with(ContextOverlay::new(config.clone(), user_domains(), ToolGroups::none()).without_user_skill_roots().session_agent(id.as_str()),);- let state = Arc::new(UserAgentState {+ let state = Arc::new(Profile {id: id.clone(),layout,config,@@ -233,16 +233,16 @@ impl AgentHost {last_used: now,},);- log::debug!("[user_agents] opened agent={id} ({} open)", open.len());+ log::debug!("[profiles] opened agent={id} ({} open)", open.len());Ok(state)}/// Agent `id` if it is open.- pub fn get(&self, id: &UserAgentId) -> Option<Arc<UserAgentState>> {+ pub fn get(&self, id: &ProfileId) -> Option<Arc<Profile>> {self.lock().get(id).map(|slot| Arc::clone(&slot.state))}- pub fn is_open(&self, id: &UserAgentId) -> bool {+ pub fn is_open(&self, id: &ProfileId) -> bool {self.lock().contains_key(id)}@@ -251,7 +251,7 @@ impl AgentHost {}/// Every provisioned agent, open or not.- pub fn list(&self) -> Result<Vec<UserAgentSummary>, String> {+ pub fn list(&self) -> Result<Vec<ProfileSummary>, String> {let dir = layout::agents_dir(&self.saas.root);let entries = match std::fs::read_dir(&dir) {Ok(entries) => entries,@@ -263,7 +263,7 @@ impl AgentHost {let Some(name) = entry.file_name().to_str().map(str::to_owned) else {continue;};- let Ok(id) = UserAgentId::parse(&name) else {+ let Ok(id) = ProfileId::parse(&name) else {continue;};// One unreadable agent must not hide the rest (or stop the@@ -271,28 +271,28 @@ impl AgentHost {match self.summary(&id) {Ok(Some(summary)) => found.push(summary),Ok(None) => {}- Err(error) => log::warn!("[user_agents] skipping agent={id} in listing: {error}"),+ Err(error) => log::warn!("[profiles] skipping agent={id} in listing: {error}"),}}- found.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));+ found.sort_by(|a, b| a.profile_id.cmp(&b.profile_id));Ok(found)}/// Agent `id`, or `None` when it is not provisioned.- pub fn summary(&self, id: &UserAgentId) -> Result<Option<UserAgentSummary>, String> {+ pub fn summary(&self, id: &ProfileId) -> Result<Option<ProfileSummary>, String> {let layout = self.layout(id);let raw = match std::fs::read_to_string(&layout.meta_path) {Ok(raw) => raw,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),Err(e) => return Err(format!("reading {}: {e}", layout.meta_path.display())),};- let meta: UserAgentMeta = toml::from_str(&raw)+ let meta: ProfileMeta = toml::from_str(&raw).map_err(|e| format!("parsing {}: {e}", layout.meta_path.display()))?;- Ok(Some(UserAgentSummary {- agent_id: id.clone(),+ Ok(Some(ProfileSummary {+ profile_id: id.clone(),created_at: meta.created_at,open: self.is_open(id),- has_credential: super::credentials::has(&layout::agent_config(&layout, id)),+ has_credential: super::credentials::has(&layout::profile_config(&layout, id)),}))}@@ -303,23 +303,23 @@ impl AgentHost {}/// Close agents idle past `idle_evict_secs` that nothing is using.- fn sweep_idle_locked(&self, open: &mut HashMap<UserAgentId, Slot>, now: Instant) {+ fn sweep_idle_locked(&self, open: &mut HashMap<ProfileId, Slot>, now: Instant) {let idle_limit = Duration::from_secs(self.saas.idle_evict_secs);open.retain(|id, slot| {let keep = Arc::strong_count(&slot.state) > 1|| now.duration_since(slot.last_used) < idle_limit;if !keep {- log::debug!("[user_agents] evicted idle agent={id}");+ log::debug!("[profiles] evicted idle agent={id}");}keep});}- fn evict_locked(&self, open: &mut HashMap<UserAgentId, Slot>, now: Instant) {+ fn evict_locked(&self, open: &mut HashMap<ProfileId, Slot>, now: Instant) {let in_use = |slot: &Slot| Arc::strong_count(&slot.state) > 1;self.sweep_idle_locked(open, now);// Still full: make room by closing the least recently used idle one.- if open.len() >= self.saas.max_agents_open.max(1) {+ if open.len() >= self.saas.max_profiles_open.max(1) {let victim = open.iter().filter(|(_, slot)| !in_use(slot))@@ -327,12 +327,12 @@ impl AgentHost {.map(|(id, _)| id.clone());if let Some(id) = victim {open.remove(&id);- log::debug!("[user_agents] evicted least recently used agent={id}");+ log::debug!("[profiles] evicted least recently used agent={id}");}}}- fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<UserAgentId, Slot>> {+ fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<ProfileId, Slot>> {self.open.lock().unwrap_or_else(PoisonError::into_inner)}}@@ -341,42 +341,42 @@ impl AgentHost {/// were mid-flight become interrupted and run-ledger rows left running are/// closed. The sweep a single-user core runs at boot, run per agent on its/// first open in this process. Failures are logged; the agent still opens.-pub(crate) fn recover_workspace(id: &UserAgentId, workspace_dir: &std::path::Path) {+pub(crate) fn recover_workspace(id: &ProfileId, workspace_dir: &std::path::Path) {let now = chrono::Utc::now().to_rfc3339();match tinyagents_session::turn_state::store::mark_all_interrupted(workspace_dir.to_path_buf(),&now,) {Ok(0) => {}- Ok(turns) => log::info!("[user_agents] agent={id} recovered {turns} interrupted turn(s)"),- Err(error) => log::warn!("[user_agents] agent={id} turn recovery failed: {error}"),+ Ok(turns) => log::info!("[profiles] agent={id} recovered {turns} interrupted turn(s)"),+ Err(error) => log::warn!("[profiles] agent={id} turn recovery failed: {error}"),}match tinyagents_session::run_ledger::interrupt_orphaned_agent_runs(workspace_dir) {Ok(0) => {}- Ok(runs) => log::info!("[user_agents] agent={id} settled {runs} orphaned run(s)"),- Err(error) => log::warn!("[user_agents] agent={id} run recovery failed: {error:#}"),+ Ok(runs) => log::info!("[profiles] agent={id} settled {runs} orphaned run(s)"),+ Err(error) => log::warn!("[profiles] agent={id} run recovery failed: {error:#}"),}}-static HOST: OnceLock<Arc<AgentHost>> = OnceLock::new();+static HOST: OnceLock<Arc<ProfileHost>> = OnceLock::new();/// Install the process's agent host. A SaaS boot does this once; later calls/// are ignored.-pub fn install(host: Arc<AgentHost>) {+pub fn install(host: Arc<ProfileHost>) {if HOST.set(host).is_err() {- log::warn!("[user_agents] agent host already installed; keeping the first");+ log::warn!("[profiles] agent host already installed; keeping the first");}}/// The process's agent host, when this is a SaaS process.-pub fn host() -> Option<Arc<AgentHost>> {+pub fn host() -> Option<Arc<ProfileHost>> {HOST.get().cloned()}/// The user agent the current work runs for, if any.-pub fn current() -> Option<Arc<UserAgentState>> {+pub fn current() -> Option<Arc<Profile>> {let agent = CoreContext::current()?.session_agent()?.to_owned();- let id = UserAgentId::parse(&agent).ok()?;+ let id = ProfileId::parse(&agent).ok()?;host()?.get(&id)}diff --git a/crates/openhuman-core/src/user_agents/host_tests.rs b/crates/openhuman-core/src/profiles/host_tests.rssimilarity index 95%rename from crates/openhuman-core/src/user_agents/host_tests.rsrename to crates/openhuman-core/src/profiles/host_tests.rsindex aeff78d688..dce3a69750 100644--- a/crates/openhuman-core/src/user_agents/host_tests.rs+++ b/crates/openhuman-core/src/profiles/host_tests.rs@@ -1,14 +1,14 @@use super::*;-fn host(tmp: &tempfile::TempDir, max_open: usize, idle_secs: u64) -> AgentHost {+fn host(tmp: &tempfile::TempDir, max_open: usize, idle_secs: u64) -> ProfileHost {let mut saas = SaasConfig::new(tmp.path());- saas.max_agents_open = max_open;+ saas.max_profiles_open = max_open;saas.idle_evict_secs = idle_secs;- AgentHost::new(saas, CoreContext::for_test(DomainSet::full(), None))+ ProfileHost::new(saas, CoreContext::for_test(DomainSet::full(), None))}-fn agent(name: &str) -> UserAgentId {- UserAgentId::for_user(name).unwrap()+fn agent(name: &str) -> ProfileId {+ ProfileId::for_user(name).unwrap()}#[test]@@ -18,10 +18,10 @@ fn provisioning_creates_the_layout_once() {let id = agent("alice");assert!(host.provision(&id).unwrap());assert!(!host.provision(&id).unwrap(), "second provision is a no-op");- let layout = UserAgentLayout::new(tmp.path(), &id);+ let layout = ProfileLayout::new(tmp.path(), &id);assert!(layout.workspace_dir.is_dir() && layout.sandbox_dir.is_dir());let summary = host.summary(&id).unwrap().unwrap();- assert_eq!(summary.agent_id, id);+ assert_eq!(summary.profile_id, id);assert!(!summary.open);}@@ -133,7 +133,7 @@ fn list_reports_provisioned_agents_only() {let open: Vec<_> = listed.iter().filter(|s| s.open)- .map(|s| &s.agent_id)+ .map(|s| &s.profile_id).collect();assert_eq!(open, vec![&b]);}@@ -240,13 +240,13 @@ fn one_unreadable_agent_does_not_hide_the_rest() {host.provision(&a).unwrap();host.provision(&b).unwrap();std::fs::write(- UserAgentLayout::new(tmp.path(), &a).meta_path,+ ProfileLayout::new(tmp.path(), &a).meta_path,"not toml = [",).unwrap();let listed = host.list().unwrap();assert_eq!(listed.len(), 1);- assert_eq!(listed[0].agent_id, b);+ assert_eq!(listed[0].profile_id, b);}#[test]diff --git a/crates/openhuman-core/src/user_agents/layout.rs b/crates/openhuman-core/src/profiles/layout.rssimilarity index 90%rename from crates/openhuman-core/src/user_agents/layout.rsrename to crates/openhuman-core/src/profiles/layout.rsindex 0318071c0c..910b2ec0f7 100644--- a/crates/openhuman-core/src/user_agents/layout.rs+++ b/crates/openhuman-core/src/profiles/layout.rs@@ -2,7 +2,7 @@//!//! ```text//! <root>/agents/<agent-id>/-//! agent.toml UserAgentMeta+//! agent.toml ProfileMeta//! config.toml the agent's config_path//! workspace/ sessions, memory, threads, cron, cost — internal state//! sandbox/ the agent's action_dir: the only place it may act@@ -15,13 +15,13 @@use std::path::{Path, PathBuf};-use super::types::UserAgentId;+use super::types::ProfileId;use crate::config::Config;use crate::security::AutonomyLevel;/// Resolved paths of one user agent.#[derive(Debug, Clone, PartialEq, Eq)]-pub struct UserAgentLayout {+pub struct ProfileLayout {pub dir: PathBuf,pub meta_path: PathBuf,pub config_path: PathBuf,@@ -29,8 +29,8 @@ pub struct UserAgentLayout {pub sandbox_dir: PathBuf,}-impl UserAgentLayout {- pub fn new(saas_root: &Path, id: &UserAgentId) -> Self {+impl ProfileLayout {+ pub fn new(saas_root: &Path, id: &ProfileId) -> Self {let dir = agents_dir(saas_root).join(id.as_str());Self {meta_path: dir.join("agent.toml"),@@ -53,7 +53,7 @@ pub fn archive_dir(saas_root: &Path) -> PathBuf {}/// The memory namespace root of agent `id`.-pub fn memory_root(id: &UserAgentId) -> String {+pub fn memory_root(id: &ProfileId) -> String {format!("user:{id}")}@@ -69,7 +69,7 @@ pub fn memory_root(id: &UserAgentId) -> String {/// - the autonomy policy is on and supervised, with no auto-approval, no tool/// installation, no trusted roots beyond the sandbox, and workspace-only/// paths.-pub fn agent_config(layout: &UserAgentLayout, id: &UserAgentId) -> Config {+pub fn profile_config(layout: &ProfileLayout, id: &ProfileId) -> Config {let mut config = Config {config_path: layout.config_path.clone(),workspace_dir: layout.workspace_dir.clone(),diff --git a/crates/openhuman-core/src/user_agents/layout_tests.rs b/crates/openhuman-core/src/profiles/layout_tests.rssimilarity index 72%rename from crates/openhuman-core/src/user_agents/layout_tests.rsrename to crates/openhuman-core/src/profiles/layout_tests.rsindex e4d85dc64e..7c3fa16294 100644--- a/crates/openhuman-core/src/user_agents/layout_tests.rs+++ b/crates/openhuman-core/src/profiles/layout_tests.rs@@ -1,12 +1,12 @@use super::*;-fn id() -> UserAgentId {- UserAgentId::for_user("layout-user").unwrap()+fn id() -> ProfileId {+ ProfileId::for_user("layout-user").unwrap()}#[test]fn every_path_sits_under_the_agent_directory() {- let layout = UserAgentLayout::new(Path::new("/srv/oh"), &id());+ let layout = ProfileLayout::new(Path::new("/srv/oh"), &id());assert_eq!(layout.dir, Path::new("/srv/oh/agents").join(id().as_str()));for path in [&layout.meta_path,@@ -20,8 +20,8 @@ fn every_path_sits_under_the_agent_directory() {#[test]fn the_config_is_rooted_in_the_agent_and_bound_to_its_memory() {- let layout = UserAgentLayout::new(Path::new("/srv/oh"), &id());- let config = agent_config(&layout, &id());+ let layout = ProfileLayout::new(Path::new("/srv/oh"), &id());+ let config = profile_config(&layout, &id());assert_eq!(config.config_path, layout.config_path);assert_eq!(config.workspace_dir, layout.workspace_dir);assert_eq!(config.action_dir, layout.sandbox_dir);@@ -37,8 +37,8 @@ fn the_memory_root_is_a_valid_layout_root() {#[test]fn the_memory_binding_wins_over_pins_and_teams() {use crate::memory::scope::MemoryIdentity;- let layout = UserAgentLayout::new(Path::new("/srv/oh"), &id());- let mut config = agent_config(&layout, &id());+ let layout = ProfileLayout::new(Path::new("/srv/oh"), &id());+ let mut config = profile_config(&layout, &id());config.memory.agents.insert("planner".into(),toml::from_str("agent_id = \"other\"\nroot = \"team:shared\"").unwrap(),@@ -50,8 +50,8 @@ fn the_memory_binding_wins_over_pins_and_teams() {#[test]fn the_policy_is_on_and_closed() {- let layout = UserAgentLayout::new(Path::new("/srv/oh"), &id());- let autonomy = agent_config(&layout, &id()).autonomy;+ let layout = ProfileLayout::new(Path::new("/srv/oh"), &id());+ let autonomy = profile_config(&layout, &id()).autonomy;assert!(autonomy.enabled);assert_eq!(autonomy.level, AutonomyLevel::Supervised);assert!(autonomy.workspace_only);@@ -62,8 +62,8 @@ fn the_policy_is_on_and_closed() {#[test]fn artifacts_land_in_the_agents_sandbox() {- let id = UserAgentId::for_user("alice").unwrap();- let layout = UserAgentLayout::new(std::path::Path::new("/srv/oh"), &id);- let config = agent_config(&layout, &id);+ let id = ProfileId::for_user("alice").unwrap();+ let layout = ProfileLayout::new(std::path::Path::new("/srv/oh"), &id);+ let config = profile_config(&layout, &id);assert!(config.files_dir().starts_with(&layout.sandbox_dir));}diff --git a/crates/openhuman-core/src/user_agents/mod.rs b/crates/openhuman-core/src/profiles/mod.rssimilarity index 59%rename from crates/openhuman-core/src/user_agents/mod.rsrename to crates/openhuman-core/src/profiles/mod.rsindex 1b89f5132b..e0908d742f 100644--- a/crates/openhuman-core/src/user_agents/mod.rs+++ b/crates/openhuman-core/src/profiles/mod.rs@@ -1,11 +1,11 @@//! User agents: in SaaS mode, each user is served as one agent.//!//! The gateway authenticates users; this domain turns a gateway user id into-//! the agent that serves that user ([`UserAgentId`]), lays out the agent's+//! the agent that serves that user ([`ProfileId`]), lays out the agent's//! private state ([`layout`]), forces the config it runs with-//! ([`layout::agent_config`]), and keeps the open agents of the process-//! ([`AgentHost`]). The operator plane provisions and inspects them through-//! the `user_agents.*` controllers ([`schemas`]).+//! ([`layout::profile_config`]), and keeps the open agents of the process+//! ([`ProfileHost`]). The operator plane provisions and inspects them through+//! the `profiles.*` controllers ([`schemas`]).//!//! The isolation boundary is the agent's own [`CoreContext`]: its config,//! workspace and `session_agent`. Work for one user runs under that context,@@ -25,6 +25,6 @@ pub mod surface;pub mod tools;pub mod types;-pub use host::{current, AgentHost, UserAgentState};-pub use schemas::{all_user_agents_controller_schemas, all_user_agents_registered_controllers};-pub use types::{UserAgentId, UserAgentSummary};+pub use host::{current, ProfileHost, Profile};+pub use schemas::{all_profiles_controller_schemas, all_profiles_registered_controllers};+pub use types::{ProfileId, ProfileSummary};diff --git a/crates/openhuman-core/src/profiles/ops.rs b/crates/openhuman-core/src/profiles/ops.rsnew file mode 100644index 0000000000..2fe46f4278--- /dev/null+++ b/crates/openhuman-core/src/profiles/ops.rs@@ -0,0 +1,148 @@+//! Operator-plane operations on user agents.+//!+//! Gateway user ids are taken here and turned into agent ids at once; they+//! are never logged, stored or returned.++use super::credentials::{self, UserCredentialKind};+use super::host::{self, ProfileHost};+use super::types::{+ CredentialResult, DeprovisionResult, ProvisionResult, ProfileId, ProfileSummary,+};+use crate::core::Outcome;++fn require_host() -> Result<std::sync::Arc<ProfileHost>, String> {+ host::host().ok_or_else(|| "user agents exist only in SaaS mode".to_string())+}++/// Create the agent for gateway user `user_id`, if it does not exist yet.+pub fn provision(user_id: &str) -> Result<Outcome<ProvisionResult>, String> {+ provision_on(&*require_host()?, user_id)+}++pub(crate) fn provision_on(+ host: &ProfileHost,+ user_id: &str,+) -> Result<Outcome<ProvisionResult>, String> {+ let profile_id = ProfileId::for_user(user_id)?;+ let created = host.provision(&profile_id)?;+ let log = if created {+ format!("provisioned {profile_id}")+ } else {+ format!("{profile_id} was already provisioned")+ };+ Ok(Outcome::single_log(+ ProvisionResult { profile_id, created },+ log,+ ))+}++/// Close agent `profile_id` and archive its state.+pub fn deprovision(profile_id: &str) -> Result<Outcome<DeprovisionResult>, String> {+ deprovision_on(&*require_host()?, profile_id)+}++pub(crate) fn deprovision_on(+ host: &ProfileHost,+ profile_id: &str,+) -> Result<Outcome<DeprovisionResult>, String> {+ let profile_id = ProfileId::parse(profile_id)?;+ let removed = host.deprovision(&profile_id)?;+ let log = if removed {+ format!("archived {profile_id}")+ } else {+ format!("{profile_id} was not provisioned")+ };+ Ok(Outcome::single_log(+ DeprovisionResult { profile_id, removed },+ log,+ ))+}++/// Every provisioned agent.+pub fn list() -> Result<Outcome<Vec<ProfileSummary>>, String> {+ let agents = require_host()?.list()?;+ let log = format!("{} user agent(s)", agents.len());+ Ok(Outcome::single_log(agents, log))+}++/// One agent, or an error when it is not provisioned.+pub fn status(profile_id: &str) -> Result<Outcome<ProfileSummary>, String> {+ status_on(&*require_host()?, profile_id)+}++pub(crate) fn status_on(+ host: &ProfileHost,+ profile_id: &str,+) -> Result<Outcome<ProfileSummary>, String> {+ let profile_id = ProfileId::parse(profile_id)?;+ let summary = host+ .summary(&profile_id)?+ .ok_or_else(|| format!("agent {profile_id} is not provisioned"))?;+ Ok(Outcome::single_log(+ summary,+ format!("status of {profile_id}"),+ ))+}++/// Install the backend credential the gateway holds for agent `profile_id`.+pub fn set_credential(+ profile_id: &str,+ kind: UserCredentialKind,+ token: &str,+ expires_at: Option<&str>,+) -> Result<Outcome<CredentialResult>, String> {+ set_credential_on(&*require_host()?, profile_id, kind, token, expires_at)+}++pub(crate) fn set_credential_on(+ host: &ProfileHost,+ profile_id: &str,+ kind: UserCredentialKind,+ token: &str,+ expires_at: Option<&str>,+) -> Result<Outcome<CredentialResult>, String> {+ let profile_id = ProfileId::parse(profile_id)?;+ // From the layout, not `open`: installing or revoking a credential must+ // work even when every agent slot is busy.+ let config = host.provisioned_config(&profile_id)?;+ credentials::store(&config, kind, token, expires_at)?;+ log::info!("[profiles] credential installed for agent={profile_id} kind={kind:?}");+ Ok(Outcome::single_log(+ CredentialResult {+ profile_id: profile_id.clone(),+ has_credential: true,+ },+ format!("credential installed for {profile_id}"),+ ))+}++/// Remove every credential agent `profile_id` holds.+pub fn clear_credential(profile_id: &str) -> Result<Outcome<CredentialResult>, String> {+ clear_credential_on(&*require_host()?, profile_id)+}++pub(crate) fn clear_credential_on(+ host: &ProfileHost,+ profile_id: &str,+) -> Result<Outcome<CredentialResult>, String> {+ let profile_id = ProfileId::parse(profile_id)?;+ let config = host.provisioned_config(&profile_id)?;+ let removed = credentials::clear(&config)?;+ log::info!("[profiles] credential cleared for agent={profile_id} removed={removed}");+ let log = if removed {+ format!("credential cleared for {profile_id}")+ } else {+ format!("{profile_id} held no credential")+ };+ Ok(Outcome::single_log(+ CredentialResult {+ profile_id,+ has_credential: false,+ },+ log,+ ))+}++#[cfg(test)]+#[path = "ops_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/user_agents/ops_tests.rs b/crates/openhuman-core/src/profiles/ops_tests.rssimilarity index 91%rename from crates/openhuman-core/src/user_agents/ops_tests.rsrename to crates/openhuman-core/src/profiles/ops_tests.rsindex 4111b9a158..7a8af9752e 100644--- a/crates/openhuman-core/src/user_agents/ops_tests.rs+++ b/crates/openhuman-core/src/profiles/ops_tests.rs@@ -1,8 +1,8 @@use super::*;use crate::core::runtime::{CoreContext, DomainSet, SaasConfig};-fn host(tmp: &tempfile::TempDir) -> AgentHost {- AgentHost::new(+fn host(tmp: &tempfile::TempDir) -> ProfileHost {+ ProfileHost::new(SaasConfig::new(tmp.path()),CoreContext::for_test(DomainSet::full(), None),)@@ -31,7 +31,7 @@ fn status_and_deprovision_take_agent_ids_only() {assert!(status_on(&host, "[email protected]").is_err());assert!(deprovision_on(&host, "../operator").is_err());- let id = UserAgentId::for_user("alice").unwrap();+ let id = ProfileId::for_user("alice").unwrap();assert!(status_on(&host, id.as_str()).unwrap_err().contains("not provisioned"));@@ -48,8 +48,8 @@ fn credentials_are_set_and_cleared_per_agent_and_never_echoed() {// The keyring holding credential secrets is shared by every test here.let alice_user = format!("alice-{}", uuid::Uuid::new_v4());let bob_user = format!("bob-{}", uuid::Uuid::new_v4());- let alice = UserAgentId::for_user(&alice_user).unwrap();- let bob = UserAgentId::for_user(&bob_user).unwrap();+ let alice = ProfileId::for_user(&alice_user).unwrap();+ let bob = ProfileId::for_user(&bob_user).unwrap();assert!(set_credential_on(&host,alice.as_str(),diff --git a/crates/openhuman-core/src/user_agents/schemas.rs b/crates/openhuman-core/src/profiles/schemas.rssimilarity index 77%rename from crates/openhuman-core/src/user_agents/schemas.rsrename to crates/openhuman-core/src/profiles/schemas.rsindex 2f0f6d5802..739d550f99 100644--- a/crates/openhuman-core/src/user_agents/schemas.rs+++ b/crates/openhuman-core/src/profiles/schemas.rs@@ -1,4 +1,4 @@-//! `user_agents.*` controllers: the SaaS operator plane.+//! `profiles.*` controllers: the SaaS operator plane.//!//! Tagged [`DomainGroup::Operator`](crate::core::all::DomainGroup::Operator),//! which only `DomainSet::saas()` enables, so a single-user core never serves@@ -19,12 +19,12 @@ struct UserParams {#[derive(Debug, Deserialize)]struct AgentParams {- agent_id: String,+ profile_id: String,}#[derive(Deserialize)]struct CredentialParams {- agent_id: String,+ profile_id: String,kind: super::credentials::UserCredentialKind,token: String,#[serde(default)]@@ -40,80 +40,80 @@ const FUNCTIONS: [&str; 6] = ["clear_credential",];-pub fn all_user_agents_controller_schemas() -> Vec<ControllerSchema> {- FUNCTIONS.iter().map(|f| user_agents_schemas(f)).collect()+pub fn all_profiles_controller_schemas() -> Vec<ControllerSchema> {+ FUNCTIONS.iter().map(|f| profiles_schemas(f)).collect()}-pub fn all_user_agents_registered_controllers() -> Vec<RegisteredController> {+pub fn all_profiles_registered_controllers() -> Vec<RegisteredController> {vec![RegisteredController {- schema: user_agents_schemas("provision"),+ schema: profiles_schemas("provision"),handler: handle_provision,},RegisteredController {- schema: user_agents_schemas("deprovision"),+ schema: profiles_schemas("deprovision"),handler: handle_deprovision,},RegisteredController {- schema: user_agents_schemas("list"),+ schema: profiles_schemas("list"),handler: handle_list,},RegisteredController {- schema: user_agents_schemas("status"),+ schema: profiles_schemas("status"),handler: handle_status,},RegisteredController {- schema: user_agents_schemas("set_credential"),+ schema: profiles_schemas("set_credential"),handler: handle_set_credential,},RegisteredController {- schema: user_agents_schemas("clear_credential"),+ schema: profiles_schemas("clear_credential"),handler: handle_clear_credential,},]}-pub fn user_agents_schemas(function: &str) -> ControllerSchema {+pub fn profiles_schemas(function: &str) -> ControllerSchema {match function {"provision" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "provision",description: "Create the agent that serves a gateway user, if it does not exist.",inputs: vec![string_field("user_id", "The gateway's id for the user.")],outputs: vec![- string_field("agent_id", "The user's agent id, derived from the user id."),+ string_field("profile_id", "The user's agent id, derived from the user id."),bool_field("created", "False when the agent already existed."),],},"deprovision" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "deprovision",description: "Close a user agent and archive its state. Nothing is deleted.",- inputs: vec![string_field("agent_id", "The agent to deprovision.")],+ inputs: vec![string_field("profile_id", "The agent to deprovision.")],outputs: vec![- string_field("agent_id", "The agent."),+ string_field("profile_id", "The agent."),bool_field("removed", "False when there was no such agent."),],},"list" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "list",description: "List every provisioned user agent.",inputs: vec![],outputs: vec![FieldSchema {name: "agents",ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "agent_id, created_at and whether it is open.",+ comment: "profile_id, created_at and whether it is open.",required: true,}],},"status" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "status",description: "Report one provisioned user agent.",- inputs: vec![string_field("agent_id", "The agent to report.")],+ inputs: vec![string_field("profile_id", "The agent to report.")],outputs: vec![- string_field("agent_id", "The agent."),+ string_field("profile_id", "The agent."),FieldSchema {name: "created_at",ty: TypeSchema::U64,@@ -125,12 +125,12 @@ pub fn user_agents_schemas(function: &str) -> ControllerSchema {],},"set_credential" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "set_credential",description: "Install the TinyHumans credential the gateway holds for a user agent. \The core stores it beside the agent's state and never validates or echoes it.",inputs: vec![- string_field("agent_id", "The agent the credential belongs to."),+ string_field("profile_id", "The agent the credential belongs to."),FieldSchema {name: "kind",ty: TypeSchema::Enum {@@ -148,22 +148,22 @@ pub fn user_agents_schemas(function: &str) -> ControllerSchema {},],outputs: vec![- string_field("agent_id", "The agent."),+ string_field("profile_id", "The agent."),bool_field("has_credential", "Always true on success."),],},"clear_credential" => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "clear_credential",description: "Remove every credential a user agent holds.",- inputs: vec![string_field("agent_id", "The agent.")],+ inputs: vec![string_field("profile_id", "The agent.")],outputs: vec![- string_field("agent_id", "The agent."),+ string_field("profile_id", "The agent."),bool_field("has_credential", "Always false on success."),],},_ => ControllerSchema {- namespace: "user_agents",+ namespace: "profiles",function: "unknown",description: "Unknown user_agents controller.",inputs: vec![],@@ -182,7 +182,7 @@ fn handle_provision(params: Map<String, Value>) -> ControllerFuture {fn handle_deprovision(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<AgentParams>(params)?;- to_json(super::ops::deprovision(&payload.agent_id)?)+ to_json(super::ops::deprovision(&payload.profile_id)?)})}@@ -193,7 +193,7 @@ fn handle_list(_params: Map<String, Value>) -> ControllerFuture {fn handle_status(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<AgentParams>(params)?;- to_json(super::ops::status(&payload.agent_id)?)+ to_json(super::ops::status(&payload.profile_id)?)})}@@ -201,7 +201,7 @@ fn handle_set_credential(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<CredentialParams>(params)?;to_json(super::ops::set_credential(- &payload.agent_id,+ &payload.profile_id,payload.kind,&payload.token,payload.expires_at.as_deref(),@@ -212,7 +212,7 @@ fn handle_set_credential(params: Map<String, Value>) -> ControllerFuture {fn handle_clear_credential(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let payload = deserialize_params::<AgentParams>(params)?;- to_json(super::ops::clear_credential(&payload.agent_id)?)+ to_json(super::ops::clear_credential(&payload.profile_id)?)})}diff --git a/crates/openhuman-core/src/user_agents/schemas_tests.rs b/crates/openhuman-core/src/profiles/schemas_tests.rssimilarity index 87%rename from crates/openhuman-core/src/user_agents/schemas_tests.rsrename to crates/openhuman-core/src/profiles/schemas_tests.rsindex 4f1b75848c..474ac3adb8 100644--- a/crates/openhuman-core/src/user_agents/schemas_tests.rs+++ b/crates/openhuman-core/src/profiles/schemas_tests.rs@@ -2,8 +2,8 @@ use super::*;#[test]fn every_controller_has_a_schema_and_a_handler() {- let schemas = all_user_agents_controller_schemas();- let controllers = all_user_agents_registered_controllers();+ let schemas = all_profiles_controller_schemas();+ let controllers = all_profiles_registered_controllers();assert_eq!(schemas.len(), FUNCTIONS.len());assert_eq!(controllers.len(), FUNCTIONS.len());for (schema, controller) in schemas.iter().zip(&controllers) {@@ -34,7 +34,7 @@ fn the_operator_plane_is_its_own_domain_family() {#[tokio::test]async fn outside_saas_the_controllers_refuse() {- let controllers = all_user_agents_registered_controllers();+ let controllers = all_profiles_registered_controllers();let list = controllers.iter().find(|c| c.schema.function == "list")diff --git a/crates/openhuman-core/src/user_agents/surface.rs b/crates/openhuman-core/src/profiles/surface.rssimilarity index 100%rename from crates/openhuman-core/src/user_agents/surface.rsrename to crates/openhuman-core/src/profiles/surface.rsdiff --git a/crates/openhuman-core/src/user_agents/surface_tests.rs b/crates/openhuman-core/src/profiles/surface_tests.rssimilarity index 96%rename from crates/openhuman-core/src/user_agents/surface_tests.rsrename to crates/openhuman-core/src/profiles/surface_tests.rsindex 126e8476bc..f533a5ddeb 100644--- a/crates/openhuman-core/src/user_agents/surface_tests.rs+++ b/crates/openhuman-core/src/profiles/surface_tests.rs@@ -15,7 +15,7 @@ fn single_user_processes_are_not_narrowed() {#[test]fn the_saas_planes_never_overlap() {- let provision = "openhuman.user_agents_provision";+ let provision = "openhuman.profiles_provision";let threads = "openhuman.threads_list";assert!(visible_in(true, Scope::Operator, provision, true),@@ -111,7 +111,7 @@ fn user_thread_ids() {#[test]fn a_saas_task_without_scope_sees_nothing() {for (method, operator) in [- ("openhuman.user_agents_provision", true),+ ("openhuman.profiles_provision", true),("openhuman.threads_list", false),] {assert!(!visible_in(true, Scope::None, method, operator), "{method}");diff --git a/crates/openhuman-core/src/user_agents/tools.rs b/crates/openhuman-core/src/profiles/tools.rssimilarity index 96%rename from crates/openhuman-core/src/user_agents/tools.rsrename to crates/openhuman-core/src/profiles/tools.rsindex c3f69af874..c63138768b 100644--- a/crates/openhuman-core/src/user_agents/tools.rs+++ b/crates/openhuman-core/src/profiles/tools.rs@@ -8,7 +8,7 @@//! [`SaasToolGroup`] at a time://!//! - `host_files`: the file tools. They run in-process, confined by the-//! user's policy (`layout::agent_config`: autonomy on, workspace-only,+//! user's policy (`layout::profile_config`: autonomy on, workspace-only,//! `action_dir` = the user's `sandbox/`, no other trusted roots).//! - `host_shell`: the shell. Every command runs in a fresh container//! ([`sandbox_policy`]) whose only writable mount is the user's `sandbox/`.@@ -166,7 +166,7 @@ pub fn admits(tool: &str, domain_ok: bool) -> bool {}let admitted = admits_with(tool, domain_ok, &allowlisted());if !admitted && domain_ok {- log::debug!("[user_agents][tools] withholding `{tool}` from user agents");+ log::debug!("[profiles][tools] withholding `{tool}` from user agents");}admitted}@@ -186,7 +186,7 @@ pub fn gate_verdict_with(tool: &str, groups: &[SaasToolGroup]) -> Result<(), Strpub fn gate_verdict(tool: &str) -> Result<(), String> {let verdict = gate_verdict_with(tool, &allowlisted());log::debug!(- "[user_agents][tools] approval gate tool={tool} allowed={}",+ "[profiles][tools] approval gate tool={tool} allowed={}",verdict.is_ok());verdict@@ -213,7 +213,7 @@ pub fn sandbox_policy_with(&& agent_dir.and_then(Path::file_name).and_then(|name| name.to_str())- .is_some_and(|name| super::types::UserAgentId::parse(name).is_ok())+ .is_some_and(|name| super::types::ProfileId::parse(name).is_ok())&& action_dir.file_name().is_some_and(|name| name == "sandbox");if !is_user_sandbox {return Err(format!(diff --git a/crates/openhuman-core/src/user_agents/tools_tests.rs b/crates/openhuman-core/src/profiles/tools_tests.rssimilarity index 100%rename from crates/openhuman-core/src/user_agents/tools_tests.rsrename to crates/openhuman-core/src/profiles/tools_tests.rsdiff --git a/crates/openhuman-core/src/user_agents/types.rs b/crates/openhuman-core/src/profiles/types.rssimilarity index 88%rename from crates/openhuman-core/src/user_agents/types.rsrename to crates/openhuman-core/src/profiles/types.rsindex 5bb74b35cf..971e65b40a 100644--- a/crates/openhuman-core/src/user_agents/types.rs+++ b/crates/openhuman-core/src/profiles/types.rs@@ -14,12 +14,12 @@ pub const MAX_USER_ID_LEN: usize = 256;/// memory namespaces.#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]#[serde(try_from = "String", into = "String")]-pub struct UserAgentId(String);+pub struct ProfileId(String);const PREFIX: &str = "u-";const HASH_HEX_LEN: usize = 32;-impl UserAgentId {+impl ProfileId {/// The agent for gateway user `user_id`.pub fn for_user(user_id: &str) -> Result<Self, String> {if user_id.is_empty() {@@ -56,13 +56,13 @@ impl UserAgentId {}}-impl std::fmt::Display for UserAgentId {+impl std::fmt::Display for ProfileId {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.write_str(&self.0)}}-impl TryFrom<String> for UserAgentId {+impl TryFrom<String> for ProfileId {type Error = String;fn try_from(raw: String) -> Result<Self, Self::Error> {@@ -70,8 +70,8 @@ impl TryFrom<String> for UserAgentId {}}-impl From<UserAgentId> for String {- fn from(id: UserAgentId) -> Self {+impl From<ProfileId> for String {+ fn from(id: ProfileId) -> Self {id.0}}@@ -79,21 +79,21 @@ impl From<UserAgentId> for String {/// Written beside a provisioned agent's state, so the operator plane can list/// agents without opening them.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-pub struct UserAgentMeta {- pub agent_id: UserAgentId,+pub struct ProfileMeta {+ pub profile_id: ProfileId,/// Unix seconds.pub created_at: u64,/// Layout version, for future migrations.pub layout_version: u32,}-/// The current [`UserAgentMeta::layout_version`].+/// The current [`ProfileMeta::layout_version`].pub const LAYOUT_VERSION: u32 = 1;/// What [`provision`](super::ops::provision) did.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct ProvisionResult {- pub agent_id: UserAgentId,+ pub profile_id: ProfileId,/// `false` when the agent already existed.pub created: bool,}@@ -101,15 +101,15 @@ pub struct ProvisionResult {/// What [`deprovision`](super::ops::deprovision) did.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct DeprovisionResult {- pub agent_id: UserAgentId,+ pub profile_id: ProfileId,/// `false` when there was no such agent.pub removed: bool,}/// One provisioned agent, as the operator plane sees it.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]-pub struct UserAgentSummary {- pub agent_id: UserAgentId,+pub struct ProfileSummary {+ pub profile_id: ProfileId,pub created_at: u64,/// Whether it is loaded in this process right now.pub open: bool,@@ -122,7 +122,7 @@ pub struct UserAgentSummary {/// itself is never echoed.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct CredentialResult {- pub agent_id: UserAgentId,+ pub profile_id: ProfileId,pub has_credential: bool,}diff --git a/crates/openhuman-core/src/profiles/types_tests.rs b/crates/openhuman-core/src/profiles/types_tests.rsnew file mode 100644index 0000000000..733760c7eb--- /dev/null+++ b/crates/openhuman-core/src/profiles/types_tests.rs@@ -0,0 +1,51 @@+use super::*;++#[test]+fn a_user_maps_to_one_stable_agent() {+ let a = ProfileId::for_user("user-123").unwrap();+ assert_eq!(a, ProfileId::for_user("user-123").unwrap());+ assert_ne!(a, ProfileId::for_user("user-124").unwrap());+}++#[test]+fn the_id_fits_the_agent_charset_and_hides_the_user_id() {+ let id = ProfileId::for_user("[email protected]").unwrap();+ let raw = id.as_str();+ assert!(raw.len() <= 64);+ assert!(raw+ .bytes()+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_'));+ assert!(!raw.contains("alice"));+}++#[test]+fn bad_user_ids_are_refused() {+ assert!(ProfileId::for_user("").is_err());+ assert!(ProfileId::for_user(&"x".repeat(MAX_USER_ID_LEN + 1)).is_err());+ assert!(ProfileId::for_user("a\nb").is_err());+ assert!(ProfileId::for_user(&"x".repeat(MAX_USER_ID_LEN)).is_ok());+}++#[test]+fn only_derived_ids_parse() {+ let id = ProfileId::for_user("u").unwrap();+ assert_eq!(ProfileId::parse(id.as_str()).unwrap(), id);+ for bad in [+ "orchestrator",+ "u-",+ "u-XYZ",+ "u-../../etc",+ "u-0123456789abcdef0123456789abcdeg",+ "u-0123456789abcdef0123456789abcdef0",+ ] {+ assert!(ProfileId::parse(bad).is_err(), "{bad}");+ }+}++#[test]+fn serde_round_trips_and_validates() {+ let id = ProfileId::for_user("u").unwrap();+ let json = serde_json::to_string(&id).unwrap();+ assert_eq!(serde_json::from_str::<ProfileId>(&json).unwrap(), id);+ assert!(serde_json::from_str::<ProfileId>("\"orchestrator\"").is_err());+}diff --git a/crates/openhuman-core/src/user_agents/ops.rs b/crates/openhuman-core/src/user_agents/ops.rsdeleted file mode 100644index 31b57227d4..0000000000--- a/crates/openhuman-core/src/user_agents/ops.rs+++ /dev/null@@ -1,148 +0,0 @@-//! Operator-plane operations on user agents.-//!-//! Gateway user ids are taken here and turned into agent ids at once; they-//! are never logged, stored or returned.--use super::credentials::{self, UserCredentialKind};-use super::host::{self, AgentHost};-use super::types::{- CredentialResult, DeprovisionResult, ProvisionResult, UserAgentId, UserAgentSummary,-};-use crate::core::Outcome;--fn require_host() -> Result<std::sync::Arc<AgentHost>, String> {- host::host().ok_or_else(|| "user agents exist only in SaaS mode".to_string())-}--/// Create the agent for gateway user `user_id`, if it does not exist yet.-pub fn provision(user_id: &str) -> Result<Outcome<ProvisionResult>, String> {- provision_on(&*require_host()?, user_id)-}--pub(crate) fn provision_on(- host: &AgentHost,- user_id: &str,-) -> Result<Outcome<ProvisionResult>, String> {- let agent_id = UserAgentId::for_user(user_id)?;- let created = host.provision(&agent_id)?;- let log = if created {- format!("provisioned {agent_id}")- } else {- format!("{agent_id} was already provisioned")- };- Ok(Outcome::single_log(- ProvisionResult { agent_id, created },- log,- ))-}--/// Close agent `agent_id` and archive its state.-pub fn deprovision(agent_id: &str) -> Result<Outcome<DeprovisionResult>, String> {- deprovision_on(&*require_host()?, agent_id)-}--pub(crate) fn deprovision_on(- host: &AgentHost,- agent_id: &str,-) -> Result<Outcome<DeprovisionResult>, String> {- let agent_id = UserAgentId::parse(agent_id)?;- let removed = host.deprovision(&agent_id)?;- let log = if removed {- format!("archived {agent_id}")- } else {- format!("{agent_id} was not provisioned")- };- Ok(Outcome::single_log(- DeprovisionResult { agent_id, removed },- log,- ))-}--/// Every provisioned agent.-pub fn list() -> Result<Outcome<Vec<UserAgentSummary>>, String> {- let agents = require_host()?.list()?;- let log = format!("{} user agent(s)", agents.len());- Ok(Outcome::single_log(agents, log))-}--/// One agent, or an error when it is not provisioned.-pub fn status(agent_id: &str) -> Result<Outcome<UserAgentSummary>, String> {- status_on(&*require_host()?, agent_id)-}--pub(crate) fn status_on(- host: &AgentHost,- agent_id: &str,-) -> Result<Outcome<UserAgentSummary>, String> {- let agent_id = UserAgentId::parse(agent_id)?;- let summary = host- .summary(&agent_id)?- .ok_or_else(|| format!("agent {agent_id} is not provisioned"))?;- Ok(Outcome::single_log(- summary,- format!("status of {agent_id}"),- ))-}--/// Install the backend credential the gateway holds for agent `agent_id`.-pub fn set_credential(- agent_id: &str,- kind: UserCredentialKind,- token: &str,- expires_at: Option<&str>,-) -> Result<Outcome<CredentialResult>, String> {- set_credential_on(&*require_host()?, agent_id, kind, token, expires_at)-}--pub(crate) fn set_credential_on(- host: &AgentHost,- agent_id: &str,- kind: UserCredentialKind,- token: &str,- expires_at: Option<&str>,-) -> Result<Outcome<CredentialResult>, String> {- let agent_id = UserAgentId::parse(agent_id)?;- // From the layout, not `open`: installing or revoking a credential must- // work even when every agent slot is busy.- let config = host.provisioned_config(&agent_id)?;- credentials::store(&config, kind, token, expires_at)?;- log::info!("[user_agents] credential installed for agent={agent_id} kind={kind:?}");- Ok(Outcome::single_log(- CredentialResult {- agent_id: agent_id.clone(),- has_credential: true,- },- format!("credential installed for {agent_id}"),- ))-}--/// Remove every credential agent `agent_id` holds.-pub fn clear_credential(agent_id: &str) -> Result<Outcome<CredentialResult>, String> {- clear_credential_on(&*require_host()?, agent_id)-}--pub(crate) fn clear_credential_on(- host: &AgentHost,- agent_id: &str,-) -> Result<Outcome<CredentialResult>, String> {- let agent_id = UserAgentId::parse(agent_id)?;- let config = host.provisioned_config(&agent_id)?;- let removed = credentials::clear(&config)?;- log::info!("[user_agents] credential cleared for agent={agent_id} removed={removed}");- let log = if removed {- format!("credential cleared for {agent_id}")- } else {- format!("{agent_id} held no credential")- };- Ok(Outcome::single_log(- CredentialResult {- agent_id,- has_credential: false,- },- log,- ))-}--#[cfg(test)]-#[path = "ops_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/user_agents/types_tests.rs b/crates/openhuman-core/src/user_agents/types_tests.rsdeleted file mode 100644index e466a68eed..0000000000--- a/crates/openhuman-core/src/user_agents/types_tests.rs+++ /dev/null@@ -1,51 +0,0 @@-use super::*;--#[test]-fn a_user_maps_to_one_stable_agent() {- let a = UserAgentId::for_user("user-123").unwrap();- assert_eq!(a, UserAgentId::for_user("user-123").unwrap());- assert_ne!(a, UserAgentId::for_user("user-124").unwrap());-}--#[test]-fn the_id_fits_the_agent_charset_and_hides_the_user_id() {- let id = UserAgentId::for_user("[email protected]").unwrap();- let raw = id.as_str();- assert!(raw.len() <= 64);- assert!(raw- .bytes()- .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_'));- assert!(!raw.contains("alice"));-}--#[test]-fn bad_user_ids_are_refused() {- assert!(UserAgentId::for_user("").is_err());- assert!(UserAgentId::for_user(&"x".repeat(MAX_USER_ID_LEN + 1)).is_err());- assert!(UserAgentId::for_user("a\nb").is_err());- assert!(UserAgentId::for_user(&"x".repeat(MAX_USER_ID_LEN)).is_ok());-}--#[test]-fn only_derived_ids_parse() {- let id = UserAgentId::for_user("u").unwrap();- assert_eq!(UserAgentId::parse(id.as_str()).unwrap(), id);- for bad in [- "orchestrator",- "u-",- "u-XYZ",- "u-../../etc",- "u-0123456789abcdef0123456789abcdeg",- "u-0123456789abcdef0123456789abcdef0",- ] {- assert!(UserAgentId::parse(bad).is_err(), "{bad}");- }-}--#[test]-fn serde_round_trips_and_validates() {- let id = UserAgentId::for_user("u").unwrap();- let json = serde_json::to_string(&id).unwrap();- assert_eq!(serde_json::from_str::<UserAgentId>(&json).unwrap(), id);- assert!(serde_json::from_str::<UserAgentId>("\"orchestrator\"").is_err());-}