Skip to content

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

chore: remove dead code and unused imports from staging and credentials modules

Steven Enamakel93307bf9fc4a
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
index a8b3d8c3c3..1f0693a3af 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/staging.rs
@@ -1,7 +1,7 @@
-//! Turning a validated task batch into staged [`SpawnParallelWorker`] values:
-//! OpenHuman policy admission (identity, allowlist, toolkit requirement,
-//! shared-workspace write claims), crate-side arbitration over those claims,
-//! worktree preflight, and progress/event projection for the `dispatch` phase.
+//! OpenHuman policy admission for a `spawn_parallel_agents` task batch:
+//! identity, the parent's subagent allowlist, the integrations toolkit
+//! requirement, and whether a worker can write the shared workspace at all —
+//! plus the crate-side arbitration over the resulting workspace claims.
//!
//! **Write safety.** Whether a worker *needs* a claim on the shared workspace is
//! an OpenHuman decision — it reads sandbox mode, tool permissions and the
@@ -11,27 +11,22 @@
//! The rejection sentences stay here, which is why the crate reports conflicts
//! as data.
+use std::path::PathBuf;
use std::collections::HashMap;
-use std::path::{Path, PathBuf};
use tinyagents_graph::parallel::{
parse_relative_claim_paths, plan_shared_workspace_dispatch, ClaimConflict, ClaimPathError,
DispatchMode, WorkspaceClaim,
};
-use tinyagents_harness::workspace::WorkspaceDescriptor;
-use tokio::sync::mpsc::Sender;
-use crate::agent::file_state;
use crate::agent::harness::definition::{
AgentDefinition, AgentDefinitionRegistry, SandboxMode, ToolScope,
};
use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::worktree::{self, BaseRef};
-use crate::agent::progress::AgentProgress;
+use crate::agent::orchestration::worktree::BaseRef;
use crate::tools::PermissionLevel;
use super::request::ParallelAgentTask;
-use super::types::{ParallelAgentLineage, ParallelAgentResult, SpawnParallelWorker};
/// Prepared worker ready for the live dispatch/worker phases.
pub(crate) struct PreparedParallelTask {
@@ -82,12 +77,12 @@ pub(crate) enum WorkerDispatchMode {
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ParallelWorktreeRequest {
+pub(crate) enum ParallelWorktreeRequest {
SharedWorkspace,
Isolated { base_ref: BaseRef },
}
-fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWorktreeRequest {
+pub(crate) fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWorktreeRequest {
let isolated = task
.isolation
.as_deref()
@@ -230,111 +225,6 @@ fn shared_workspace_write_claim(
Ok(Some(paths))
}
-pub(crate) fn spawn_parallel_lineage(
- parent_session: &str,
- session_parent_prefix: Option<&str>,
- task_id: &str,
-) -> ParallelAgentLineage {
- let root_session = session_parent_prefix
- .and_then(|prefix| prefix.split("__").next())
- .filter(|root| !root.is_empty())
- .unwrap_or(parent_session);
- ParallelAgentLineage {
- parent_session: parent_session.to_string(),
- root_session: root_session.to_string(),
- child_task_id: task_id.to_string(),
- }
-}
-
-async fn create_spawn_parallel_worktree(
- parent_session: &str,
- action_root: Option<&Path>,
- task_id: &str,
- definition: &AgentDefinition,
- task: &ParallelAgentTask,
- session_parent_prefix: Option<&str>,
-) -> Result<Option<WorkspaceDescriptor>, ParallelAgentResult> {
- match worktree_request_for_task(task) {
- ParallelWorktreeRequest::SharedWorkspace => Ok(None),
- ParallelWorktreeRequest::Isolated { base_ref } => match action_root {
- Some(repo_root) => {
- let sandbox = match definition.sandbox_mode {
- SandboxMode::Sandboxed => tinyagents_harness::tool::SandboxMode::Required,
- SandboxMode::None | SandboxMode::ReadOnly => {
- tinyagents_harness::tool::SandboxMode::Inherit
- }
- };
- let isolation = worktree::OpenHumanWorktreeIsolation::new(repo_root)
- .with_base_ref(base_ref)
- .with_sandbox(sandbox);
- match isolation.prepare(task_id, Some(&definition.id)).await {
- Ok(descriptor) => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- worktree = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- base_ref = base_ref.as_str(),
- "[spawn_parallel_agents] prepared isolated workspace descriptor"
- );
- Ok(Some(descriptor))
- }
- Err(err) => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %task_id,
- error = %err,
- "[spawn_parallel_agents] workspace_prepare_failed"
- );
- Err(ParallelAgentResult {
- task_id: task_id.to_string(),
- agent_id: definition.id.clone(),
- lineage: spawn_parallel_lineage(
- parent_session,
- session_parent_prefix,
- task_id,
- ),
- success: false,
- output: None,
- error: Some(format!("worktree isolation failed: {err}")),
- ownership: task.ownership.clone(),
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- }
- }
- }
- None => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %task_id,
- "[spawn_parallel_agents] worktree_requested_but_no_action_dir"
- );
- Err(ParallelAgentResult {
- task_id: task_id.to_string(),
- agent_id: definition.id.clone(),
- lineage: spawn_parallel_lineage(parent_session, session_parent_prefix, task_id),
- success: false,
- output: None,
- error: Some(
- "worktree isolation requested but action_dir is unavailable".to_string(),
- ),
- ownership: task.ownership.clone(),
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- })
- }
- },
- }
-}
pub(crate) fn snapshot_agent_definitions(
registry: &AgentDefinitionRegistry,
@@ -565,209 +455,3 @@ pub(crate) fn with_ownership_boundary(prompt: &str, ownership: Option<&str>) ->
}
}
-pub(crate) async fn stage_spawn_parallel_workers_from_defs(
- parent_session: &str,
- progress_sink: Option<&Sender<AgentProgress>>,
- tasks: Vec<ParallelAgentTask>,
- definitions: &HashMap<String, AgentDefinition>,
- parent: &ParentExecutionContext,
- action_root: Option<&Path>,
- parent_workspace_descriptor: Option<&WorkspaceDescriptor>,
-) -> (Vec<SpawnParallelWorker>, Vec<ParallelAgentResult>) {
- let mut immediate_results = Vec::new();
- let mut prepared = Vec::new();
-
- for preflight in prepare_spawn_parallel_tasks_from_defs(tasks, definitions, parent) {
- let (definition, prompt, task, task_id, dispatch_mode) = match preflight {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- match rejection.kind {
- ParallelTaskRejectionKind::MissingAgentOrPrompt => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- "[spawn_parallel_agents] invalid_task_missing_agent_or_prompt"
- );
- }
- ParallelTaskRejectionKind::UnknownAgent => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- "[spawn_parallel_agents] invalid_task_unknown_agent"
- );
- }
- ParallelTaskRejectionKind::OutsideAllowlist => {
- tracing::warn!(
- parent_session = %parent_session,
- parent_agent = %parent.agent_definition_id,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- allowed = ?parent.allowed_subagent_ids,
- "[spawn_parallel_agents] rejected_task_outside_subagent_allowlist"
- );
- }
- ParallelTaskRejectionKind::MissingToolkit => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- "[spawn_parallel_agents] invalid_task_missing_toolkit"
- );
- }
- ParallelTaskRejectionKind::RequiresIsolation => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- ownership = rejection.ownership.as_deref().unwrap_or(""),
- "[spawn_parallel_agents] rejected_shared_workspace_write_capable_task"
- );
- }
- }
- let lineage = spawn_parallel_lineage(
- parent_session,
- parent.session_parent_prefix.as_deref(),
- &rejection.task_id,
- );
- immediate_results.push(ParallelAgentResult {
- task_id: rejection.task_id,
- agent_id: rejection.agent_id,
- lineage,
- success: false,
- output: None,
- error: Some(rejection.error),
- ownership: rejection.ownership,
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- });
- continue;
- }
- SpawnParallelTaskPreflight::Prepared(prepared_task) => (
- prepared_task.definition,
- prepared_task.prompt,
- prepared_task.task,
- prepared_task.task_id,
- prepared_task.dispatch_mode,
- ),
- };
- project_spawn_parallel_spawned(
- parent_session,
- progress_sink,
- &definition,
- &task_id,
- &prompt,
- task.ownership
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .is_some(),
- )
- .await;
- let workspace_descriptor = match create_spawn_parallel_worktree(
- parent_session,
- action_root,
- &task_id,
- &definition,
- &task,
- parent.session_parent_prefix.as_deref(),
- )
- .await
- {
- Ok(descriptor) => descriptor,
- Err(result) => {
- immediate_results.push(result);
- continue;
- }
- };
- let worktree_path = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- let worker_workspace_descriptor = workspace_descriptor
- .clone()
- .or_else(|| parent_workspace_descriptor.cloned());
- let lineage = spawn_parallel_lineage(
- parent_session,
- parent.session_parent_prefix.as_deref(),
- &task_id,
- );
- prepared.push(SpawnParallelWorker {
- definition,
- prompt,
- task,
- task_id,
- lineage,
- worktree_path,
- workspace_descriptor: worker_workspace_descriptor,
- dispatch_mode,
- });
- }
-
- tracing::debug!(
- parent_session = %parent_session,
- prepared_count = prepared.len(),
- immediate_count = immediate_results.len(),
- serial_write_count = prepared
- .iter()
- .filter(|worker| matches!(
- worker.dispatch_mode,
- WorkerDispatchMode::SerialSharedWorkspaceWrite
- ))
- .count(),
- "[spawn_parallel_agents] prepared_tasks"
- );
- (prepared, immediate_results)
-}
-
-async fn project_spawn_parallel_spawned(
- parent_session: &str,
- progress_sink: Option<&Sender<AgentProgress>>,
- definition: &AgentDefinition,
- task_id: &str,
- prompt: &str,
- has_ownership: bool,
-) {
- let prompt_chars = prompt.chars().count();
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %definition.id,
- prompt_chars,
- has_ownership,
- "[spawn_parallel_agents] publishing_subagent_spawned"
- );
- crate::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.to_string(),
- definition.id.clone(),
- "typed".to_string(),
- task_id.to_string(),
- prompt_chars,
- );
- if let Some(tx) = progress_sink {
- if let Err(err) = tx
- .send(AgentProgress::SubagentSpawned {
- agent_id: definition.id.clone(),
- task_id: task_id.to_string(),
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars,
- prompt: prompt.to_string(),
- worker_thread_id: None,
- display_name: Some(definition.display_name().to_string()),
- })
- .await
- {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %definition.id,
- error = %err,
- "[spawn_parallel_agents] progress_send_failed spawned"
- );
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily/search_tool.rs b/crates/openhuman-core/src/search/tools/tavily/search_tool.rs
index 1646e3ee30..102c4233e0 100644
--- a/crates/openhuman-core/src/search/tools/tavily/search_tool.rs
+++ b/crates/openhuman-core/src/search/tools/tavily/search_tool.rs
@@ -217,4 +217,3 @@ impl Tool for TavilySearchTool {
}
}
-/// Retrieve full page contents for a list of URLs (`POST /extract`).
diff --git a/crates/openhuman-core/src/security/credentials/ops_part_01.rs b/crates/openhuman-core/src/security/credentials/ops_part_01.rs
deleted file mode 100644
index 4a64a3b1a0..0000000000
--- a/crates/openhuman-core/src/security/credentials/ops_part_01.rs
+++ /dev/null
@@ -1,675 +0,0 @@
-use serde_json::{json, Value};
-use std::time::Duration;
-
-use crate::api::config::effective_backend_api_url;
-use crate::api::jwt::{decode_jwt_exp, get_session_token};
-use crate::api::rest::{user_id_from_profile_payload, BackendOAuthClient};
-use crate::config::Config;
-use crate::security::credentials::session_support::{
- build_session_state, is_local_session_token, local_session_user_id, parse_fields_value,
- profile_name_or_default, summarize_auth_profile, LOCAL_SESSION_USER_ID,
-};
-use crate::security::keyring::SecretStore;
-use crate::rpc::RpcOutcome;
-
-use super::{normalize_provider, AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};
-use crate::config::{
- default_root_openhuman_dir, pre_login_user_dir, read_active_user_id, user_openhuman_dir,
- write_active_user_id,
-};
-use crate::memory::conversations;
-
-const AUTH_ME_STORE_RETRY_DELAY: Duration = Duration::from_millis(150);
-const AUTH_ME_STORE_TRANSIENT_STATUSES: &[u16] = &[408, 429, 500, 502, 503, 504, 520];
-
-/// Wall-clock budget for the store-time `GET /auth/me` validation (issue #5166).
-///
-/// The shared backend client allows a 120s request timeout + 15s connect timeout
-/// (`api::rest`), but the desktop sign-in RPC that drives `auth_store_session`
-/// gives up far sooner — `AUTH_STORE_TIMEOUT_MS` (25s) × `AUTH_STORE_RETRIES` in
-/// `desktopDeepLinkListener.ts`. If the backend is reachable but slow, that 120s
-/// ceiling lets `/auth/me` hang past the frontend's patience: the RPC times out
-/// and bounces a genuinely-authenticated user back to sign-in *before* the
-/// deferred-validation fallback in `store_session_inner` ever gets a chance to
-/// fire (the exact `auth_me_timeout` bounce in Sentry `TAURI-REACT-1V`).
-///
-/// Capping store-time validation well under the frontend budget makes a slow
-/// backend fail *fast* into the caller-authorized pending-session path (for a
-/// live-`exp` JWT), so the user lands in the app with deferred revalidation
-/// instead of being bounced. Overridable via `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS`
-/// for ops tuning and tests.
-const AUTH_ME_STORE_VALIDATION_BUDGET: Duration = Duration::from_secs(12);
-const AUTH_ME_STORE_VALIDATION_BUDGET_ENV: &str = "OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS";
-
-/// Whether this dispatch is running under an embedder-hosted core (the library
-/// `Harness`) rather than the desktop shell or CLI.
-///
-/// An embedder supplies its own scoped [`Config`] via `CoreBuilder::config`,
-/// so its `auth_store_session` must keep activation and credential state under
-/// that config's path and never touch the operator's global
-/// `~/.openhuman/active_user.toml` / `users/` tree.
-fn is_embedder_host() -> bool {
- crate::core::runtime::context::CoreContext::current_embedder_config().is_some()
-}
-
-/// Start all login-gated background services (local AI and voice). Called both
-/// from the initial boot path (when an existing
-/// session is detected) and from `store_session()` on fresh login.
-pub async fn start_login_gated_services(config: &Config) {
- // These login-gated services are mutually independent — the ONLY ordering
- // constraint is voice-server → standalone-dictation-listener (they contend
- // for the single rdev global listener on macOS). Previously each was
- // `.await`ed in series, so their cold-start costs SUMMED: the local-AI
- // bootstrap (Ollama/embeddings) + the Windows WASAPI microphone init
- // (a synchronous readiness handshake in `always_on::spawn_capture_thread`)
- // stacked into the ~10s stall users hit before hotkeys/commands were usable
- // — worst on Windows (#3490). Worse,
- // the hotkey/command registration (steps 2–3) sat
- // *after* the local-AI bootstrap in the series, so commands could not
- // register until Ollama finished warming.
- //
- // Run them concurrently on independent tasks instead: readiness is bounded
- // by the slowest single service rather than their sum, and command
- // registration no longer waits behind local-AI warm-up. Each task logs its
- // own elapsed time so a future regression can be attributed to one stage; a
- // panic in one service is logged on join and never aborts the others.
-
- // Unit tests must not launch the real login-gated background services: they
- // include detached, long-lived continuous audio capture that outlives the
- // test that spawned it and interleaves with the
- // shared process state (HOME / active_user.toml) of the parallel `cargo
- // test` run. Once startup became concurrent (#3490) that interleaving made
- // the session-isolation tests order-dependent. `cfg!(test)` is compiled out
- // of every production/release build, so this gate never affects shipped
- // behavior; the one test that verifies this function's concurrency opts back
- // in via `OPENHUMAN_RUN_LOGIN_GATED_SERVICES_IN_TEST`.
- if cfg!(test) && std::env::var_os("OPENHUMAN_RUN_LOGIN_GATED_SERVICES_IN_TEST").is_none() {
- log::debug!("[services] login-gated services skipped under unit test");
- return;
- }
-
- let started = std::time::Instant::now();
- // (service label, task) pairs so a panic surfaced on join is attributed to
- // the specific stage rather than an anonymous "a service failed".
- let mut tasks: Vec<(&'static str, tokio::task::JoinHandle<()>)> = Vec::new();
-
- // 1. Local AI (Ollama, embeddings) — the heaviest single warm-up,
- // so keeping it off the critical path for the others is the biggest win.
- {
- let config = config.clone();
- tasks.push((
- "local_ai",
- tokio::spawn(async move {
- if config.local_ai.runtime_enabled {
- let step = std::time::Instant::now();
- log::debug!("[services] local AI bootstrap starting");
- crate::inference::local::global(&config)
- .bootstrap(&config)
- .await;
- log::debug!(
- "[services] local AI bootstrapped after login ({} ms)",
- step.elapsed().as_millis()
- );
- } else {
- log::debug!("[services] local AI disabled — skipping bootstrap");
- }
- }),
- ));
- }
-
- // 2+3. Voice hotkey services — the user-facing command registration. The
- // embedded voice server owns the single rdev listener; the standalone
- // dictation listener only starts when the server is NOT auto-starting,
- // so keep these two ordered *relative to each other* (but concurrent
- // with everything else).
- {
- let config = config.clone();
- tasks.push((
- "voice_hotkey",
- tokio::spawn(async move {
- let step = std::time::Instant::now();
- crate::voice::server::start_if_enabled(&config).await;
- if !config.voice_server.auto_start {
- crate::voice::dictation_listener::start_if_enabled(&config).await;
- }
- log::debug!(
- "[services] voice hotkey services registered ({} ms)",
- step.elapsed().as_millis()
- );
- }),
- ));
- }
-
- // 3b. Always-on listening (Phase 2): continuous mic + VAD → STT → agent.
- // Its cold WASAPI init (`always_on::spawn_capture_thread`) is the
- // Windows-specific blocker; it now runs the blocking capture-readiness
- // handshake on the blocking pool (see `always_on::start_if_enabled`), so
- // on its own task it neither stalls an async worker nor the hotkey /
- // command registration above.
- {
- let config = config.clone();
- tasks.push((
- "always_on",
- tokio::spawn(async move {
- let step = std::time::Instant::now();
- crate::voice::always_on::start_if_enabled(&config).await;
- log::debug!(
- "[services] always-on listening started ({} ms)",
- step.elapsed().as_millis()
- );
- }),
- ));
- }
-
- let total = tasks.len();
- let mut failed = 0usize;
- for (name, task) in tasks {
- if let Err(err) = task.await {
- failed += 1;
- log::warn!("[services] login-gated service '{name}' panicked during startup: {err}");
- }
- }
- let elapsed_ms = started.elapsed().as_millis();
- if failed == 0 {
- log::info!(
- "[services] all {total} login-gated services started concurrently ({elapsed_ms} ms)"
- );
- } else {
- log::warn!(
- "[services] {failed}/{total} login-gated services failed to start ({elapsed_ms} ms)"
- );
- }
-}
-
-/// Stop all login-gated background services. Called from `clear_session()`
-/// on logout so orphan processes don't consume resources.
-pub async fn stop_login_gated_services(config: &Config) {
- // 2. Voice server
- if let Some(server) = crate::voice::server::try_global_server() {
- server.stop().await;
- log::info!("[services] voice server stopped on logout");
- }
-
- // 4. Local AI — reset state to idle. We don't kill the Ollama process
- // (it may be serving other clients or mid-download), but we clear
- // the internal state so it re-bootstraps on next login.
- if config.local_ai.runtime_enabled {
- let service = crate::inference::local::global(config);
- service.reset_to_idle(config);
- log::info!("[services] local AI reset to idle on logout");
- }
-
- // 5. Dictation listener — abort the hotkey forwarder task so it doesn't
- // accumulate duplicate rdev listeners across logout → login cycles.
- crate::voice::dictation_listener::stop();
-
- // 6. Always-on listening — disable the runtime gate so the mic capture loop
- // stops transcribing/delivering after logout (no audio processed while
- // logged out). Symmetric with start_login_gated_services step 3b.
- crate::voice::always_on::stop();
-
- log::info!("[services] all login-gated services stopped");
-}
-
-fn secret_store_for_config(config: &Config) -> SecretStore {
- let data_dir = config
- .config_path
- .parent()
- .map_or_else(|| std::path::PathBuf::from("."), std::path::PathBuf::from);
- SecretStore::new(&data_dir, true)
-}
-
-pub async fn encrypt_secret(
- config: &Config,
- plaintext: &str,
-) -> Result<RpcOutcome<String>, String> {
- let store = secret_store_for_config(config);
- let ciphertext = store.encrypt(plaintext).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(ciphertext, "secret encrypted"))
-}
-
-pub async fn decrypt_secret(
- config: &Config,
- ciphertext: &str,
-) -> Result<RpcOutcome<String>, String> {
- let store = secret_store_for_config(config);
- let plaintext = store.decrypt(ciphertext).map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(plaintext, "secret decrypted"))
-}
-
-pub async fn store_session(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
-) -> Result<RpcOutcome<super::responses::AuthProfileSummary>, String> {
- store_session_inner(config, token, user_id, user, false).await
-}
-
-/// Store a session from a callback flow that already exchanged a backend
-/// login token. Generic callers should use `store_session`, which requires
-/// immediate `/auth/me` proof before persisting remote JWTs.
-pub async fn store_session_with_deferred_validation(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
-) -> Result<RpcOutcome<super::responses::AuthProfileSummary>, String> {
- store_session_inner(config, token, user_id, user, true).await
-}
-
-async fn store_session_inner(
- config: &Config,
- token: &str,
- user_id: Option<String>,
- user: Option<serde_json::Value>,
- allow_pending_backend_validation: bool,
-) -> Result<RpcOutcome<super::responses::AuthProfileSummary>, String> {
- let trimmed_token = token.trim();
- if trimmed_token.is_empty() {
- return Err("token is required".to_string());
- }
-
- let api_url = effective_backend_api_url(&config.api_url);
- let local_session = is_local_session_token(trimmed_token);
- let local_user_id = local_session.then(local_session_user_id);
- let mut session_validation_logs = Vec::new();
- let settings = if local_session {
- sanitize_stored_session_user(user.clone())
- .map(|value| {
- normalize_local_session_user(
- value,
- local_user_id.as_deref().unwrap_or(LOCAL_SESSION_USER_ID),
- )
- })
- .ok_or_else(|| "local session requires a user payload".to_string())?
- } else {
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- match fetch_current_user_for_session_store(&client, trimmed_token).await {
- Ok(fetched_user) => {
- session_validation_logs.push(format!(
- "session JWT verified via GET /auth/me on {}",
- api_url.trim_end_matches('/')
- ));
- fetched_user
- }
- Err(reason) => {
- // This is the store-time validation gate: if it fails the profile
- // is NEVER persisted, so the user bounces straight back to the
- // signin page after a "successful" OAuth. Timeouts/gateway 5xx are
- // otherwise dropped by the Sentry transient classifier, so log an
- // explicit, grep-friendly WARN to the app log regardless.
- if !auth_me_store_failure_is_transient(&reason) {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me validation FAILED on {} — session NOT persisted; user will bounce to signin: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- }
-
- if !allow_pending_backend_validation {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me transient validation failed on {} — session NOT persisted; backend proof required before storing remote JWT: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- }
-
- let Some(exp) = jwt_exp_live_at(trimmed_token, chrono::Utc::now()) else {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] GET /auth/me transient validation failed on {} but JWT has no live local exp — session NOT persisted: {reason}",
- api_url.trim_end_matches('/')
- );
- return Err(format!(
- "Session validation failed (GET /auth/me): {reason}"
- ));
- };
-
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- exp = %exp,
- "[credentials][auth-store] GET /auth/me transient validation failed on {} — persisting caller-authorized pending session for backend revalidation: {reason}",
- api_url.trim_end_matches('/')
- );
- session_validation_logs.push(format!(
- "session JWT accepted with deferred GET /auth/me validation on {} after transient failure",
- api_url.trim_end_matches('/')
- ));
- fallback_session_user_for_deferred_validation()
- }
- }
- };
-
- let mut metadata = std::collections::HashMap::new();
- if let Some(uid) = if local_session {
- local_user_id.clone()
- } else {
- user_id
- .and_then(|v| {
- let t = v.trim().to_string();
- (!t.is_empty()).then_some(t)
- })
- .or_else(|| user_id_from_profile_payload(&settings))
- } {
- metadata.insert("user_id".to_string(), uid);
- }
- let pending_backend_validation = settings
- .as_object()
- .and_then(|map| map.get("pendingBackendValidation"))
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let user_for_store = if local_session || pending_backend_validation {
- settings.clone()
- } else {
- sanitize_stored_session_user(user).unwrap_or(settings)
- };
- metadata.insert("user_json".to_string(), user_for_store.to_string());
-
- // Record the JWT `exp` so `require_live_session_token` can reject an expired
- // token locally instead of firing a doomed backend 401 (#3297 RCA — the
- // TAURI-RUST-8WY/8WZ flood). Local offline sessions aren't JWTs and carry no
- // `exp`; `decode_jwt_exp` returns None for them and the key is simply omitted
- // (presence-only check + the `flatten_authed_error` 401 net still apply).
- if !local_session {
- match decode_jwt_exp(trimmed_token) {
- Some(exp) => {
- metadata.insert(
- crate::security::credentials::session_support::SESSION_EXPIRES_AT_META
- .to_string(),
- exp.to_rfc3339(),
- );
- tracing::info!(
- domain = "credentials",
- operation = "store_session",
- "[credentials] recorded app-session expiry exp={exp} for local precheck"
- );
- }
- None => tracing::debug!(
- domain = "credentials",
- operation = "store_session",
- "[credentials] app-session token has no decodable `exp`; local expiry precheck disabled (falls back to 401 net)"
- ),
- }
- }
-
- // Determine user_id so we can scope the openhuman directory to this user.
- let resolved_user_id = metadata.get("user_id").cloned();
- if pending_backend_validation && resolved_user_id.is_none() && !is_embedder_host() {
- if let Ok(root_dir) = default_root_openhuman_dir() {
- if let Some(active_user_id) = read_active_user_id(&root_dir) {
- let active_user_dir = user_openhuman_dir(&root_dir, &active_user_id);
- if config.config_path.parent() == Some(active_user_dir.as_path()) {
- tracing::warn!(
- domain = "credentials",
- operation = "store_session",
- active_user_id = %active_user_id,
- "[credentials][auth-store] unresolved pending session would replace active user's app-session; session NOT persisted"
- );
- return Err(
- "Session validation failed (GET /auth/me): backend user id required before replacing the active session"
- .to_string(),
- );
- }
- }
- }
- }
-
- // If we know the user_id, activate the user-scoped directory BEFORE storing
- // the auth profile so that credentials land in the correct place.
- let mut logs = if local_session {
- vec!["local session accepted without backend validation".to_string()]
- } else {
- session_validation_logs
- };
-
- // An embedder host (the harness) keeps session state under its own
- // `config_path` scope and must never touch the operator's global
- // `~/.openhuman/active_user.toml` or `users/` tree. Writing it would change
- // which user the operator's real install believes is active purely by
- // virtue of running a library call — the exact global side effect an
- // ephemeral harness exists to avoid. The scoped auth profile is still
- // stored below; only the global activation is skipped.
- let operator_user_activation = !is_embedder_host();
-
- if let Some(ref uid) = resolved_user_id
- .as_ref()
- .filter(|_| operator_user_activation)
- {
- if let Ok(root_dir) = default_root_openhuman_dir() {
- // Snapshot before we overwrite `active_user.toml` so we can tell
- // first activation from signed-out vs an in-place account switch.
- let previous_active = read_active_user_id(&root_dir);
- let user_dir = user_openhuman_dir(&root_dir, uid);
- if let Err(e) = std::fs::create_dir_all(&user_dir) {
- tracing::warn!(
- user_id = %uid,
- error = %e,
- "failed to create user directory"
- );
- } else if let Err(e) = write_active_user_id(&root_dir, uid) {
- tracing::warn!(
- user_id = %uid,
- error = %e,
- "failed to write active_user.toml"
- );
- } else {
- logs.push(format!("user directory activated for {uid}"));
- tracing::info!(
- user_id = %uid,
- user_dir = %user_dir.display(),
- "User-scoped directory activated"
- );
- // Onboarding and other pre-auth flows write threads under the
- // `users/local/workspace` tree. After the first successful login
- // there was no previous `active_user.toml`, wipe that anonymous
- // conversation store so a fresh account never inherits demo or
- // scratch threads from the pre-login bucket (#1157).
- //
- // This shares `memory::conversations`' process-wide mutex with
- // `list_threads` / `purge_threads` on any workspace, so purge and
- // concurrent thread RPC in this process cannot interleave.
- if previous_active.is_none() {
- let pre_ws = pre_login_user_dir(&root_dir).join("workspace");
- let pre_ws_log = pre_ws.display().to_string();
- match conversations::purge_threads(pre_ws) {
- Ok(stats) => {
- tracing::info!(
- pre_login_workspace = %pre_ws_log,
- threads = stats.thread_count,
- messages = stats.message_count,
- "[credentials] purged pre-login conversation threads after first session activation"
- );
- logs.push(format!(
- "purged pre-login conversation history (threads={}, messages={})",
- stats.thread_count, stats.message_count
- ));
- }
- Err(e) => {
- tracing::debug!(
- error = %e,
- pre_login_workspace = %pre_ws_log,
- "[credentials] pre-login conversation purge skipped (non-fatal)"
- );
- }
- }
- }
- }
- }
- }
-
- // Reload config so it picks up the newly activated user directory.
- // This ensures auth-profiles.json, encryption key, etc. are written
- // to the user-scoped location.
- let effective_config = if resolved_user_id.is_some() {
- match crate::config::load_config_with_timeout().await {
- Ok(c) => c,
- Err(_) => config.clone(),
- }
- } else {
- config.clone()
- };
-
- if let Err(error) = crate::cron::seed::prune_retired_jobs(&effective_config) {
- tracing::warn!(
- error = %error,
- "[credentials] failed to prune retired cron jobs after user workspace activation"
- );
- }
-
- if local_session {
- match crate::config::ops::set_onboarding_completed(false).await {
- Ok(_) => logs.push("onboarding left incomplete for local session setup".to_string()),
- Err(error) => logs.push(format!(
- "onboarding setup warning for local session: {error}"
- )),
- }
- }
-
- let auth = AuthService::from_config(&effective_config);
- let profile = auth
- .store_provider_token(
- APP_SESSION_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- trimmed_token,
- metadata,
- true,
- )
- .map_err(|e| e.to_string())?;
-
- logs.push("session stored".to_string());
-
- // ── No explicit memory re-point here any more (#5560) ──────────────────
- //
- // This site used to call `tinymemory_core::global::init(...)` before the
- // context rebind below. That was load-bearing for the *engine singleton*: a
- // single process-global slot that keeps writing into the pre-login
- // workspace until something re-points it, which is why it needed its own
- // call at every login / logout / revalidation site.
- //
- // `memory::binding` is a workspace-keyed cache, not a slot, and
- // `CoreContext::memory_binding`'s own docs already state the consequence:
- // "there is **no** explicit 'rebind the memory driver' call at the login /
- // logout / revalidation sites the way `memory::global::init` needs one: the
- // accessor keys on the workspace dir and the subsystem config, both of
- // which those sites already re-point." The `rebind_default_workspace` call
- // immediately below re-points both, so memory follows it by construction.
- //
- // The binding is resolved lazily on the next memory call rather than warmed
- // here. Warming it would mean naming `binding::for_workspace` at a site
- // that never touches memory content, which the memory-guard bypass ratchet
- // is right to treat as reach-through.
- match crate::core::runtime::context::CoreContext::rebind_default_workspace(
- &effective_config.workspace_dir,
- effective_config.subsystems.memory.clone(),
- ) {
- Ok(_) => logs.push(format!(
- "core context bound to workspace {}",
- effective_config.workspace_dir.display()
- )),
- Err(e) => {
- tracing::warn!(error = %e, "[credentials] failed to rebind core context after login");
- logs.push(format!("core context bind warning: {e}"));
- }
- }
- // No people-store rebind here any more: people is served by the bound
- // memory driver, and `rebind_default_workspace` above already moved that
- // binding to the per-user workspace. Seeding a host-side global as well
- // opened the engine's database a second time in this process (#4378 fixed
- // the workspace it pointed at; the module port removes the second reader).
- crate::memory::conversations::register_conversation_persistence_subscriber(
- effective_config.workspace_dir.clone(),
- );
- logs.push("conversation persistence bound to active workspace".to_string());
-
- // Start all login-gated services (voice and local AI).
- // Uses the effective config so services see the user-scoped workspace
- // directory.
- start_login_gated_services(&effective_config).await;
- logs.push("login-gated services started".to_string());
-
- // Clear the scheduler-gate signed-out override now that a fresh JWT is
- // in place. Workers that were sleeping in the paused poll loop will
- // pick this up at their next iteration and resume LLM-bound work.
- crate::cron::scheduler_gate::set_signed_out(false);
- tracing::debug!(
- domain = "credentials",
- operation = "store_session",
- "[credentials][auth-store] scheduler gate cleared; ensuring re-embed backfill after login"
- );
- crate::memory::ops::maintenance::reembed_best_effort(
- &effective_config,
- "session stored",
- )
- .await;
- logs.push("memory re-embed backfill checked after login".to_string());
-
- // Bind the Sentry scope to this user so background events that fire
- // before the frontend's `app_state_snapshot` warms the user cache still
- // carry `user.id` — issue #3135. The `before_send` filter is now a
- // fallback for legacy cache-warming paths; setting scope here is the
- // primary source.
- if let Some(ref uid) = resolved_user_id {
- super::sentry_scope::bind(uid);
- }
-
- Ok(RpcOutcome::new(summarize_auth_profile(&profile), logs))
-}
-
-/// Store-time `GET /auth/me` budget resolver. Reads the
-/// `OPENHUMAN_AUTH_ME_STORE_TIMEOUT_MS` override (positive integer milliseconds),
-/// otherwise the `AUTH_ME_STORE_VALIDATION_BUDGET` default.
-fn auth_me_store_validation_budget() -> Duration {
- std::env::var(AUTH_ME_STORE_VALIDATION_BUDGET_ENV)
- .ok()
- .and_then(|raw| raw.trim().parse::<u64>().ok())
- .filter(|ms| *ms > 0)
- .map(Duration::from_millis)
- .unwrap_or(AUTH_ME_STORE_VALIDATION_BUDGET)
-}
-
-/// Validate the freshly minted session token against `GET /auth/me`, bounded by
-/// `auth_me_store_validation_budget()`. On budget exhaustion returns a
-/// transient-classified timeout error so `store_session_inner` routes a
-/// live-`exp` JWT into the deferred-validation fallback rather than hanging until
-/// the desktop sign-in RPC times out and bounces the user (issue #5166).
-async fn fetch_current_user_for_session_store(
- client: &BackendOAuthClient,
- token: &str,
-) -> Result<Value, String> {
- let budget = auth_me_store_validation_budget();
- match tokio::time::timeout(
- budget,
- fetch_current_user_for_session_store_inner(client, token),
- )
- .await
- {
- Ok(result) => result,
- Err(_elapsed) => {
- // Message must contain a `TRANSIENT_TRANSPORT_PHRASES` phrase
- // ("timeout") so `auth_me_store_failure_is_transient` buckets it as
- // transient and the deferred-validation path can take over.
- let reason = format!(
- "GET /auth/me validation timeout after {}ms (store-time budget exceeded)",
- budget.as_millis()
- );
- tracing::warn!(
- domain = "credentials",
- operation = "fetch_current_user_for_session_store",
- budget_ms = budget.as_millis() as u64,
- "[credentials][auth-store] {reason}"
- );
- Err(reason)
- }
- }
-}
diff --git a/crates/openhuman-core/src/security/credentials/ops_part_02.rs b/crates/openhuman-core/src/security/credentials/ops_part_02.rs
deleted file mode 100644
index ce55fb508d..0000000000
--- a/crates/openhuman-core/src/security/credentials/ops_part_02.rs
+++ /dev/null
@@ -1,593 +0,0 @@
-
-async fn fetch_current_user_for_session_store_inner(
- client: &BackendOAuthClient,
- token: &str,
-) -> Result<Value, String> {
- match client.fetch_current_user(token).await {
- Ok(user) => Ok(user),
- Err(first) => {
- let first_reason = format!("{first:#}");
- if !auth_me_store_failure_is_transient(&first_reason) {
- return Err(first_reason);
- }
-
- tokio::time::sleep(AUTH_ME_STORE_RETRY_DELAY).await;
- tracing::debug!(
- domain = "credentials",
- operation = "fetch_current_user_for_session_store",
- reason = %first_reason,
- "[credentials][auth-store] retrying GET /auth/me after transient failure"
- );
- client
- .fetch_current_user(token)
- .await
- .map_err(|second| format!("{second:#}"))
- }
- }
-}
-
-fn auth_me_store_failure_is_transient(reason: &str) -> bool {
- if let Some(status) = auth_me_failure_status(reason) {
- return AUTH_ME_STORE_TRANSIENT_STATUSES.contains(&status);
- }
-
- crate::core::observability::contains_transient_transport_phrase(reason)
-}
-
-fn auth_me_failure_status(reason: &str) -> Option<u16> {
- let lower = reason.to_ascii_lowercase();
- (100..600).find(|status| {
- let status = status.to_string();
- lower.contains(&format!("({status}"))
- || lower.contains(&format!("http {status}"))
- || lower.contains(&format!("status {status}"))
- || lower.contains(&format!("status code {status}"))
- })
-}
-
-fn jwt_exp_live_at(
- token: &str,
- now: chrono::DateTime<chrono::Utc>,
-) -> Option<chrono::DateTime<chrono::Utc>> {
- let exp = decode_jwt_exp(token)?;
- (exp > now).then_some(exp)
-}
-
-fn fallback_session_user_for_deferred_validation() -> Value {
- json!({ "pendingBackendValidation": true })
-}
-
-fn sanitize_stored_session_user(user: Option<serde_json::Value>) -> Option<serde_json::Value> {
- match user {
- Some(serde_json::Value::Object(map)) if map.is_empty() => None,
- Some(serde_json::Value::Null) => None,
- other => other,
- }
-}
-
-fn normalize_local_session_user(user: serde_json::Value, local_user_id: &str) -> serde_json::Value {
- let mut map = match user {
- serde_json::Value::Object(map) => map,
- other => return other,
- };
- map.insert(
- "id".to_string(),
- serde_json::Value::String(local_user_id.to_string()),
- );
- map.insert(
- "_id".to_string(),
- serde_json::Value::String(local_user_id.to_string()),
- );
- serde_json::Value::Object(map)
-}
-
-pub async fn clear_session(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {
- let mut logs = Vec::new();
- let removed = {
- let _session_mutation_lock = crate::desktop::app_state::
- CURRENT_USER_SESSION_MUTATION_LOCK
- .lock()
- .await;
- // Flip the scheduler-gate override first so any background worker that
- // is mid-iteration (or wakes up while we tear down) stalls at its next
- // `wait_for_capacity()` call instead of firing requests at a backend
- // we're about to invalidate. Idempotent.
- crate::cron::scheduler_gate::set_signed_out(true);
-
- // Invalidate before removing the profile so a pending revalidation cannot
- // recreate it after logout has finished the removal.
- crate::desktop::app_state::forget_current_user_caches();
-
- let auth = AuthService::from_config(config);
- auth.remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
- .map_err(|e| e.to_string())?
- };
-
- // The core process stays alive on logout. Tear down its authenticated
- // Socket.IO transport and the user-pinned workflow bridge so neither can
- // keep serving the signed-out account until a later reconnect.
- if let Some(manager) = crate::platform::socket::global_socket_manager() {
- if let Err(error) = manager.disconnect().await {
- tracing::warn!(%error, "failed to disconnect backend socket on logout");
- }
- }
- crate::platform::socket::medulla::workflows::clear_workflow_bridge();
-
- // Clear the active user marker so subsequent config loads fall back to the
- // default (unauthenticated) openhuman directory.
- if let Ok(root_dir) = default_root_openhuman_dir() {
- if let Err(e) = crate::config::clear_active_user(&root_dir) {
- tracing::warn!(error = %e, "failed to clear active_user.toml on logout");
- }
- }
-
- // Stop all login-gated services (voice and local AI) so
- // they don't run as orphan processes after logout, consuming RAM/CPU with
- // no user context to operate against.
- stop_login_gated_services(config).await;
-
- // The process stays alive after desktop/TUI logout, so every process-global
- // store must follow the now-active pre-login workspace. Without this, a
- // signed-out caller can keep reading the previous account's context until
- // the process restarts.
- match crate::config::load_config_with_timeout().await {
- Ok(signed_out_config) => {
- let workspace = signed_out_config.workspace_dir.clone();
- // No `memory::global::init` twin here either — see the login site.
- // The context rebind below carries the signed-out workspace and its
- // `[subsystems.memory]` block, and the memory binding is keyed on
- // exactly that pair, so it follows without a second call.
- if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(
- &workspace,
- signed_out_config.subsystems.memory.clone(),
- ) {
- tracing::warn!(%error, "failed to rebind core context after logout");
- }
- crate::memory::conversations::register_conversation_persistence_subscriber(
- workspace.clone(),
- );
- logs.push(format!(
- "process globals rebound to signed-out workspace {}",
- workspace.display()
- ));
- }
- Err(error) => {
- tracing::warn!(%error, "failed to resolve signed-out workspace after logout");
- logs.push(format!("signed-out workspace rebind warning: {error}"));
- }
- }
-
- // Drop the Sentry scope user so events surfaced during/after teardown
- // (and before the next login) are no longer attributed to the
- // signed-out account — issue #3135.
- super::sentry_scope::clear();
-
- logs.push("session cleared".to_string());
- Ok(RpcOutcome::new(json!({ "removed": removed }), logs))
-}
-
-pub async fn auth_get_state(
- config: &Config,
-) -> Result<RpcOutcome<super::responses::AuthStateResponse>, String> {
- let state = build_session_state(config)?;
- Ok(RpcOutcome::single_log(state, "session state fetched"))
-}
-
-pub async fn auth_get_session_token_json(
- config: &Config,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let token = get_session_token(config)?;
- Ok(RpcOutcome::single_log(
- json!({ "token": token }),
- "session token fetched",
- ))
-}
-
-pub async fn auth_get_me(config: &Config) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let user = client
- .fetch_current_user(&token)
- .await
- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`
- // onto the `SESSION_EXPIRED:` sentinel and falls through to `{e:#}` for
- // everything else, so both properties this call site needs are kept:
- //
- // * Non-401s still render the full anyhow context chain, so the
- // underlying reqwest transport error (timeout / connection reset /
- // TLS / DNS) reaches `observability::is_transient_message_failure`.
- // Bare `e.to_string()` renders only the top context layer
- // ("GET /auth/me") and collapsed every transient transport failure
- // into Sentry TAURI-RUST-10.
- // * A 401 is recognised by `jsonrpc::is_session_expired_error`, which
- // skips the Sentry report AND publishes `DomainEvent::SessionExpired`
- // so `SessionExpiredSubscriber` clears the dead JWT.
- //
- // Until #5232 routed `fetch_current_user` through `authed_json`, a 401
- // here surfaced as `"GET /auth/me failed (401 Unauthorized): …"`, which
- // `is_session_expired_error` matched on its HTTP-verb prefix. The typed
- // error renders as `"backend rejected session token on GET /auth/me"`,
- // which matches neither classifier — so on 0.63.9 every lapsed session
- // reported to Sentry as a code defect (TAURI-RUST-RYD) and, because the
- // stale token was never cleared, re-fired the same 401 on the next
- // revalidation: the forced sign-out loop in #5307.
- .map_err(crate::api::flatten_authed_error)?;
-
- Ok(RpcOutcome::single_log(user, "current user fetched"))
-}
-
-pub async fn consume_login_token(
- config: &Config,
- login_token: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let token = login_token.trim();
- if token.is_empty() {
- return Err("loginToken is required".to_string());
- }
-
- let api_url = effective_backend_api_url(&config.api_url);
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let jwt_token = client
- .consume_login_token(token)
- .await
- // See `auth_get_me` above for why we walk the full anyhow chain.
- .map_err(|e| format!("{e:#}"))?;
-
- Ok(RpcOutcome::new(
- serde_json::json!({ "jwtToken": jwt_token }),
- vec![
- format!(
- "login token consumed via POST /auth/login-token/consume on {}",
- api_url.trim_end_matches('/')
- ),
- "session JWT received".to_string(),
- ],
- ))
-}
-
-pub async fn auth_create_channel_link_token(
- config: &Config,
- channel: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let channel = channel.trim();
- if channel.is_empty() {
- return Err("channel is required".to_string());
- }
- let channel = channel.to_lowercase();
- if !matches!(channel.as_str(), "telegram" | "discord") {
- return Err(format!("unsupported channel: {channel}"));
- }
-
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let payload = client
- .create_channel_link_token(&channel, &token)
- .await
- // See `auth_get_me` above: same authed backend route, same need to keep
- // the typed 401 classifiable while non-401s keep their full anyhow chain.
- .map_err(crate::api::flatten_authed_error)?;
-
- Ok(RpcOutcome::single_log(
- payload,
- "channel link token created",
- ))
-}
-
-pub async fn store_provider_credentials(
- config: &Config,
- provider: &str,
- profile: Option<&str>,
- token: Option<String>,
- fields: Option<serde_json::Value>,
- set_active: Option<bool>,
-) -> Result<RpcOutcome<super::responses::AuthProfileSummary>, String> {
- let provider = provider.trim().to_string();
- if provider.is_empty() {
- return Err("provider is required".to_string());
- }
-
- let profile_name = profile_name_or_default(profile);
- let mut metadata = parse_fields_value(fields)?;
- let token = token
- .as_ref()
- .map(|v| v.trim().to_string())
- .filter(|v| !v.is_empty())
- .or_else(|| metadata.get("token").cloned())
- .or_else(|| metadata.get("api_key").cloned())
- .unwrap_or_default();
- if token.is_empty() && metadata.is_empty() {
- return Err("provide at least one credential via token or fields".to_string());
- }
- metadata.remove("token");
-
- let auth = AuthService::from_config(config);
- let stored = auth
- .store_provider_token(
- &provider,
- profile_name,
- &token,
- metadata,
- set_active.unwrap_or(true),
- )
- .map_err(|e| e.to_string())?;
- // A freshly-stored key supersedes any prior auth rejection for this
- // provider — clear the recorded BYO auth error so the AI-settings notice
- // disappears and the notification latch re-arms (a future rejection will
- // notify again). Credentials are keyed `provider:<slug>`; the auth-error
- // registry is keyed by the bare provider slug used by the chat factory.
- clear_provider_auth_error(&provider);
- Ok(RpcOutcome::single_log(
- summarize_auth_profile(&stored),
- "provider credentials stored",
- ))
-}
-
-/// Clear any recorded BYO provider auth error for a credentials `provider`
-/// key. Strips the `provider:` namespace prefix so the lookup matches the
-/// bare slug (`openrouter`) the inference classifier records under.
-fn clear_provider_auth_error(provider: &str) {
- let slug = provider.strip_prefix("provider:").unwrap_or(provider);
- crate::inference::auth_error_registry::clear(slug);
-}
-
-pub async fn remove_provider_credentials(
- config: &Config,
- provider: &str,
- profile: Option<&str>,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let profile_name = profile_name_or_default(profile);
- let auth = AuthService::from_config(config);
- let removed = auth
- .remove_profile(provider, profile_name)
- .map_err(|e| e.to_string())?;
- // Removing the key clears any recorded BYO auth error for this provider —
- // there is no longer a key to be "rejected", so the stale notice must go.
- clear_provider_auth_error(provider);
- Ok(RpcOutcome::single_log(
- json!({
- "removed": removed,
- "provider": provider,
- "profile": profile_name,
- }),
- "provider credentials removed",
- ))
-}
-
-pub async fn list_provider_credentials(
- config: &Config,
- provider_filter: Option<String>,
-) -> Result<RpcOutcome<Vec<super::responses::AuthProfileSummary>>, String> {
- let auth = AuthService::from_config(config);
- let provider_filter = provider_filter
- .map(|provider| normalize_provider(&provider))
- .transpose()
- .map_err(|e| e.to_string())?;
- let profiles = auth.load_profiles().map_err(|e| e.to_string())?;
- let mut items = profiles
- .profiles
- .values()
- .filter(|profile| profile.provider != APP_SESSION_PROVIDER)
- .filter(|profile| {
- provider_filter
- .as_ref()
- .is_none_or(|provider| profile.provider == *provider)
- })
- .map(summarize_auth_profile)
- .collect::<Vec<_>>();
- items.sort_by(|a, b| {
- a.provider
- .cmp(&b.provider)
- .then_with(|| a.profile_name.cmp(&b.profile_name))
- });
-
- Ok(RpcOutcome::single_log(items, "provider credentials listed"))
-}
-
-/// List credentials whose provider key starts with `prefix`.
-///
-/// Pure prefix variant of [`list_provider_credentials`] for namespaces
-/// that group multiple providers under a common stem (e.g.
-/// `"channel:"` covers `channel:telegram:managed_dm`,
-/// `channel:slack:bot_token`, …). The exact-match filter on
-/// `list_provider_credentials` cannot express this without enumerating
-/// every concrete provider key up front.
-pub async fn list_provider_credentials_by_prefix(
- config: &Config,
- prefix: &str,
-) -> Result<Vec<super::responses::AuthProfileSummary>, String> {
- let auth = AuthService::from_config(config);
- let profiles = auth.load_profiles().map_err(|e| e.to_string())?;
- let mut items = profiles
- .profiles
- .values()
- .filter(|profile| profile.provider != APP_SESSION_PROVIDER)
- .filter(|profile| profile.provider.starts_with(prefix))
- .map(summarize_auth_profile)
- .collect::<Vec<_>>();
- items.sort_by(|a, b| {
- a.provider
- .cmp(&b.provider)
- .then_with(|| a.profile_name.cmp(&b.profile_name))
- });
- Ok(items)
-}
-
-pub async fn oauth_connect(
- config: &Config,
- provider: &str,
- skill_id: Option<&str>,
- response_type: Option<&str>,
- encryption_mode: Option<&str>,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| {
- "session JWT required; complete login and store_session first".to_string()
- })?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let r = client
- .connect(provider, &token, skill_id, response_type, encryption_mode)
- .await
- .map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(
- serde_json::json!({ "oauthUrl": r.oauth_url, "state": r.state }),
- "oauth connect URL ready",
- ))
-}
-
-pub async fn oauth_list_integrations(
- config: &Config,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let list = client
- .list_integrations(&token)
- .await
- .map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(
- serde_json::to_value(&list).map_err(|e| e.to_string())?,
- "integrations listed",
- ))
-}
-
-pub async fn oauth_fetch_integration_tokens(
- config: &Config,
- integration_id: &str,
- encryption_key: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let tokens = client
- .fetch_integration_tokens_handoff(integration_id, &token, encryption_key)
- .await
- .map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(
- serde_json::to_value(&tokens).map_err(|e| e.to_string())?,
- "integration tokens retrieved",
- ))
-}
-
-pub async fn oauth_fetch_client_key(
- config: &Config,
- integration_id: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- let client_key = client
- .fetch_client_key(integration_id, &token)
- .await
- .map_err(|e| e.to_string())?;
- log::debug!(
- "[credentials] client key retrieved for integration {}",
- integration_id
- );
- Ok(RpcOutcome::single_log(
- json!({ "clientKey": client_key, "integrationId": integration_id }),
- "client key retrieved (one-time handoff)",
- ))
-}
-
-pub async fn oauth_revoke_integration(
- config: &Config,
- integration_id: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let api_url = effective_backend_api_url(&config.api_url);
- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;
- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;
- client
- .revoke_integration(integration_id, &token)
- .await
- .map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(
- serde_json::json!({ "revoked": true, "integrationId": integration_id }),
- "integration revoked",
- ))
-}
-
-/// Provider slot for the user-provided Composio API key when running in
-/// direct mode (BYO key).
-///
-/// Parallel to [`APP_SESSION_PROVIDER`] but completely independent — the
-/// app-session JWT authenticates the user against `api.tinyhumans.ai`,
-/// while this slot authenticates the user against
-/// `backend.composio.dev`. Stored via the same
-/// [`super::profiles::AuthProfilesStore`] backend (encrypted on disk
-/// when `secrets.encrypt = true`).
-pub const COMPOSIO_DIRECT_PROVIDER: &str = "composio-direct";
-
-/// Persist the user-provided Composio API key to the encrypted credential
-/// store under [`COMPOSIO_DIRECT_PROVIDER`].
-///
-/// **Never log the API key itself** — the debug line below records only
-/// length and a length-of-stored marker. This honours the CLAUDE.md
-/// debug-logging rule (`Never log secrets … redact or omit`).
-pub async fn store_composio_api_key(
- config: &Config,
- api_key: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- let trimmed = api_key.trim();
- if trimmed.is_empty() {
- return Err("composio api_key must not be empty".to_string());
- }
- tracing::debug!(
- len = trimmed.len(),
- "[composio-direct] storing api key (redacted)"
- );
- let auth = AuthService::from_config(config);
- auth.store_provider_token(
- COMPOSIO_DIRECT_PROVIDER,
- DEFAULT_AUTH_PROFILE_NAME,
- trimmed,
- std::collections::HashMap::new(),
- true,
- )
- .map_err(|e| e.to_string())?;
-
- Ok(RpcOutcome::single_log(
- json!({ "stored": true, "provider": COMPOSIO_DIRECT_PROVIDER }),
- "composio direct api key stored",
- ))
-}
-
-/// Read the user-provided Composio API key from the encrypted credential
-/// store. Returns `Ok(None)` when no key has been stored yet.
-///
-/// Used by [`crate::integrations::composio::client::create_composio_client`]
-/// to decide whether direct mode can actually be activated.
-pub fn get_composio_api_key(config: &Config) -> Result<Option<String>, String> {
- let auth = AuthService::from_config(config);
- let key = auth
- .get_provider_bearer_token(COMPOSIO_DIRECT_PROVIDER, None)
- .map_err(|e| e.to_string())?;
- Ok(key.map(|k| k.trim().to_string()).filter(|k| !k.is_empty()))
-}
-
-/// RPC wrapper around [`store_composio_api_key`] — accepts plain string
-/// for symmetry with `store_provider_credentials` while only persisting
-/// the trimmed value.
-pub async fn rpc_store_composio_api_key(
- config: &Config,
- api_key: &str,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- store_composio_api_key(config, api_key).await
-}
-
-/// Remove the stored Composio direct-mode API key. Used when the user
-/// switches back to backend mode and explicitly clears their key.
-pub async fn clear_composio_api_key(
- config: &Config,
-) -> Result<RpcOutcome<serde_json::Value>, String> {
- tracing::debug!("[composio-direct] clearing stored api key");
- let auth = AuthService::from_config(config);
- let removed = auth
- .remove_profile(COMPOSIO_DIRECT_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
- .map_err(|e| e.to_string())?;
- Ok(RpcOutcome::single_log(
- json!({ "removed": removed }),
- "composio direct api key cleared",
- ))
-}
diff --git a/crates/openhuman-core/src/tools/ops_tests_part_04_tests.rs b/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/tools/ops_tests_part_04_tests.rs
rename to crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs
diff --git a/crates/openhuman-core/src/tools/ops_tests_part_01_tests.rs b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/tools/ops_tests_part_01_tests.rs
rename to crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs
diff --git a/crates/openhuman-core/src/tools/ops_tests_part_03_tests.rs b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/tools/ops_tests_part_03_tests.rs
rename to crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs
diff --git a/crates/openhuman-core/src/tools/ops_tests_part_02_tests.rs b/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/tools/ops_tests_part_02_tests.rs
rename to crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs