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
fix(hosted): handle missing team member in ops
Steven Enamakel448b85dabe15
diff --git a/crates/openhuman-tinyhumans/src/hosted/team/ops.rs b/crates/openhuman-tinyhumans/src/hosted/team/ops.rsindex 5102cf1a2a..2722751fb8 100644--- a/crates/openhuman-tinyhumans/src/hosted/team/ops.rs+++ b/crates/openhuman-tinyhumans/src/hosted/team/ops.rs@@ -1,31 +1,28 @@-//! Team management RPC ops — thin adapters that call the hosted API.+//! Team management RPC ops — thin adapters over the SDK's typed `teams()`+//! client.//!//! # Security-//! All methods require a valid app-session JWT stored via `auth_store_session`.-//! The JWT is sent as `Authorization: Bearer …` to the backend.-//! **No server-side authorization is replicated here**: the backend enforces team-//! ownership, role permissions, and tenant isolation on every request.-//! Callers without the required role (e.g. non-owner trying to remove a member)-//! receive a backend 401/403 surfaced verbatim as an RPC error string.-//! API keys / JWTs are never written to logs.+//! Every call authenticates with the core's resolved backend credential+//! ([`HostedClient`]). **No server-side authorization is replicated here**:+//! the backend enforces team ownership, role permissions and tenant isolation+//! on every request. Callers without the required role receive the backend's+//! error surfaced as an RPC error string. Credentials are never logged.+//!+//! Input validation always runs before the credential is resolved, so a bad+//! argument reports the argument, never "not signed in".++use std::time::{Duration, Instant};-use reqwest::{Method, Url};-use serde::Serialize;+use reqwest::Method;use serde_json::{json, Value};+use tinyhumans_sdk::api::types::{CodeRequest, CreateTeamInviteRequest};use openhuman_core::api::config::effective_backend_api_url;-use openhuman_core::api::BackendOAuthClient;use openhuman_core::config::Config;+use openhuman_core::integrations::client::budget_gate;use openhuman_core::rpc::RpcOutcome;-/// Canonical authed-session guard. Delegates to `require_live_session_token`,-/// which rejects an expired token locally (publishing `SessionExpired`) instead-/// of firing a doomed backend 401 — see #3297 / `session_support`.-fn require_token(- config: &Config,-) -> Result<openhuman_core::security::credentials::session_support::BackendCredential, String> {- openhuman_core::security::credentials::session_support::resolve_backend_credential(config)-}+use crate::hosted::client::HostedClient;fn normalize_id(input: &str, field: &str) -> Result<String, String> {let trimmed = input.trim();@@ -35,54 +32,45 @@ fn normalize_id(input: &str, field: &str) -> Result<String, String> {Ok(trimmed.to_string())}-fn build_api_path(segments: &[&str]) -> Result<String, String> {- let mut url = Url::parse("https://openhuman.invalid")- .map_err(|e| format!("failed to initialize URL path builder: {e}"))?;- {- let mut path_segments = url- .path_segments_mut()- .map_err(|_| "failed to initialize URL path builder".to_string())?;- path_segments.clear();- for segment in segments {- path_segments.push(segment);- }- }- Ok(url.path().to_string())+fn clamp_u32(value: Option<u64>, field: &str) -> Result<Option<u32>, String> {+ value+ .map(|v| u32::try_from(v).map_err(|_| format!("{field} is out of range")))+ .transpose()}-async fn get_authed_value(- config: &Config,- method: Method,- path: &str,- body: Option<Value>,-) -> Result<Value, String> {- let token = require_token(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| format!("{e:#}"))?;- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- // (expected session-lapse 401) onto the `SESSION_EXPIRED` sentinel so the- // JSON-RPC layer classifies it as session expiry and skips Sentry (#3297,- // TAURI-RUST-8WY on `/teams/me/usage`); every other error keeps its full- // `{e:#}` anyhow chain. `authed_json` wraps the underlying reqwest error- // with `.context(format!("backend request {} {}", …))`- // (`api/rest.rs::authed_json`), so `{e:#}` (not `e.to_string()`) is required- // to surface the cause (connect timeout, DNS failure, TLS handshake, non-2xx- // status, …) before the JSON-RPC layer reports it to Sentry.- // OPENHUMAN-TAURI-AD is the canonical instance: 2 events on `0.53.35` from a- // Russia user, all with the truncated label and elapsed_ms=49 — far too- // short for a real timeout, so the underlying cause is the only signal worth- // surfacing. Same failure mode the `report_error` doc-string in- // `core/observability.rs` calls out (TAURI-B2).- client- .authed_json(&token, method, path, body)- .await- .map_err(openhuman_core::api::flatten_authed_error)+/// `GET /teams/me/usage` — the usage document behind the frontend's usage+/// poll. Wrapped in the core's shared failure backoff+/// ([`budget_gate::usage_with_failure_backoff`]) so a persistent backend+/// fault collapses to about one probe a minute across this RPC *and* the+/// managed-tool budget gate (GH #4153).+///+/// The credential is resolved first: a user with no TinyHumans account gets+/// the core's `BACKEND_UNAVAILABLE:` sentinel without a request and without+/// opening a backoff streak (Sentry 36649).+pub async fn get_usage(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let backend_key = effective_backend_api_url(&config.api_url);+ budget_gate::usage_with_failure_backoff(+ &backend_key,+ Duration::ZERO,+ Instant::now(),+ || async {+ client.finish_value(+ "GET /teams/me/usage",+ client.sdk().teams().get_my_usage().await,+ )+ },+ )+ .await}pub async fn list_members(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "members"])?;- let data = get_authed_value(config, Method::GET, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /teams/{teamId}/members",+ client.sdk().teams().list_members(&team_id).await,+ )?;Ok(RpcOutcome::single_log(data,"team members fetched from backend",@@ -90,34 +78,40 @@ pub async fn list_members(config: &Config, team_id: &str) -> Result<RpcOutcome<V}pub async fn list_teams(config: &Config) -> Result<RpcOutcome<Value>, String> {- let data = get_authed_value(config, Method::GET, "/teams", None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value("GET /teams", client.sdk().teams().list_teams().await)?;Ok(RpcOutcome::single_log(data, "teams fetched from backend"))}pub async fn get_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;- let data = get_authed_value(config, Method::GET, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /teams/{teamId}",+ client.sdk().teams().get_team(&team_id).await,+ )?;Ok(RpcOutcome::single_log(data, "team fetched from backend"))}-#[derive(Debug, Serialize)]-struct TeamNameBody<'a> {- name: &'a str,-}-+/// `POST /teams`. **Not a deployed backend route** (teams were folded into+/// users; the SDK's generated public-route registry has no entry and no typed+/// method), so this rides the SDK's raw primitive to keep the RPC contract+/// until the RPC is retired or the route is added to the SDK.pub async fn create_team(config: &Config, name: &str) -> Result<RpcOutcome<Value>, String> {let trimmed = name.trim();if trimmed.is_empty() {return Err("name is required".to_string());}- let data = get_authed_value(- config,- Method::POST,- "/teams",- Some(json!(TeamNameBody { name: trimmed })),- )- .await?;+ let client = HostedClient::from_config(config)?;+ let body = json!({ "name": trimmed });+ let data = client.finish(+ "POST /teams",+ client+ .sdk()+ .raw()+ .send(Method::POST, "/teams", &[], Some(&body), true)+ .await,+ )?;Ok(RpcOutcome::single_log(data, "team created via backend"))}@@ -127,26 +121,46 @@ pub async fn update_team(name: Option<&str>,) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;let mut body = serde_json::Map::new();if let Some(name) = name.map(str::trim).filter(|value| !value.is_empty()) {body.insert("name".to_string(), Value::String(name.to_string()));}- let data = get_authed_value(config, Method::PUT, &path, Some(Value::Object(body))).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "PUT /teams/{teamId}",+ client+ .sdk()+ .teams()+ .update_team(&team_id, &Value::Object(body))+ .await,+ )?;Ok(RpcOutcome::single_log(data, "team updated via backend"))}+/// `DELETE /teams/{teamId}`. **Not a deployed backend route** — see+/// [`create_team`].pub async fn delete_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let path = format!("/teams/{}", tinyhumans_sdk::enc(&team_id));+ let data = client.finish(+ "DELETE /teams/{teamId}",+ client+ .sdk()+ .raw()+ .send(Method::DELETE, &path, &[], None, true)+ .await,+ )?;Ok(RpcOutcome::single_log(data, "team deleted via backend"))}pub async fn switch_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "switch"])?;- let data = get_authed_value(config, Method::POST, &path, Some(json!({}))).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/switch",+ client.sdk().teams().switch_team(&team_id).await,+ )?;Ok(RpcOutcome::single_log(data,"active team switched via backend",@@ -155,8 +169,11 @@ pub async fn switch_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Vapub async fn leave_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "leave"])?;- let data = get_authed_value(config, Method::POST, &path, Some(json!({}))).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/leave",+ client.sdk().teams().leave_team(&team_id).await,+ )?;Ok(RpcOutcome::single_log(data, "team left via backend"))}@@ -165,25 +182,17 @@ pub async fn join_team(config: &Config, code: &str) -> Result<RpcOutcome<Value>,if trimmed.is_empty() {return Err("code is required".to_string());}- let data = get_authed_value(- config,- Method::POST,- "/teams/join",- Some(json!({ "code": trimmed })),- )- .await?;+ let client = HostedClient::from_config(config)?;+ let request = CodeRequest {+ code: trimmed.to_string(),+ };+ let data = client.finish_value(+ "POST /teams/join",+ client.sdk().teams().join_team(&request).await,+ )?;Ok(RpcOutcome::single_log(data, "team joined via backend"))}-#[derive(Debug, Serialize)]-#[serde(rename_all = "camelCase")]-struct InviteBody {- #[serde(skip_serializing_if = "Option::is_none")]- max_uses: Option<u64>,- #[serde(skip_serializing_if = "Option::is_none")]- expires_in_days: Option<u64>,-}-pub async fn create_invite(config: &Config,team_id: &str,@@ -191,12 +200,15 @@ pub async fn create_invite(expires_in_days: Option<u64>,) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "invites"])?;- let body = json!(InviteBody {- max_uses,- expires_in_days,- });- let data = get_authed_value(config, Method::POST, &path, Some(body)).await?;+ let request = CreateTeamInviteRequest {+ max_uses: clamp_u32(max_uses, "maxUses")?,+ expires_in_days: clamp_u32(expires_in_days, "expiresInDays")?,+ };+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/invites",+ client.sdk().teams().create_invite(&team_id, &request).await,+ )?;Ok(RpcOutcome::single_log(data,"team invite created via backend",@@ -210,8 +222,11 @@ pub async fn remove_member() -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;let user_id = normalize_id(user_id, "userId")?;- let path = build_api_path(&["teams", &team_id, "members", &user_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "DELETE /teams/{teamId}/members/{userId}",+ client.sdk().teams().remove_member(&team_id, &user_id).await,+ )?;Ok(RpcOutcome::single_log(data,"team member removed via backend",@@ -227,29 +242,36 @@ pub async fn change_member_role(let team_id = normalize_id(team_id, "teamId")?;let user_id = normalize_id(user_id, "userId")?;let role = normalize_id(role, "role")?;- let path = build_api_path(&["teams", &team_id, "members", &user_id, "role"])?;- let body = json!({ "role": role });- let data = get_authed_value(config, Method::PUT, &path, Some(body)).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "PUT /teams/{teamId}/members/{userId}/role",+ client+ .sdk()+ .teams()+ .update_member_role(&team_id, &user_id, &json!({ "role": role }))+ .await,+ )?;Ok(RpcOutcome::single_log(data,"team member role updated via backend",))}-/// List all active invites for a team.-/// Maps to `GET /teams/:teamId/invites` — matches `teamApi.getInvites`.+/// List all active invites for a team (`GET /teams/:teamId/invites`).pub async fn list_invites(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "invites"])?;- let data = get_authed_value(config, Method::GET, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /teams/{teamId}/invites",+ client.sdk().teams().list_invites(&team_id).await,+ )?;Ok(RpcOutcome::single_log(data,"team invites listed from backend",))}-/// Revoke (delete) an existing invite by id.-/// Maps to `DELETE /teams/:teamId/invites/:inviteId` — matches `teamApi.revokeInvite`.+/// Revoke an invite (`DELETE /teams/:teamId/invites/:inviteId`).pub async fn revoke_invite(config: &Config,team_id: &str,@@ -257,8 +279,15 @@ pub async fn revoke_invite() -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;let invite_id = normalize_id(invite_id, "inviteId")?;- let path = build_api_path(&["teams", &team_id, "invites", &invite_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "DELETE /teams/{teamId}/invites/{inviteId}",+ client+ .sdk()+ .teams()+ .revoke_invite(&team_id, &invite_id)+ .await,+ )?;Ok(RpcOutcome::single_log(data,"team invite revoked via backend",