pub struct ServerState {
pub sessions: Arc<DashMap<String, UserSessions>>,
pub ws_tx: Sender<String>,
pub auth: Option<Arc<AuthState>>,
pub config_toml: Option<String>,
pub secrets: Option<HashMap<String, String>>,
pub build_info: Option<BuildInfo>,
pub workflow_semaphore: Arc<Semaphore>,
pub max_sessions_per_user: usize,
pub allow_llm_overlay: bool,
pub mcp_loaders: Arc<DashMap<String, McpLoaderEntry>>,
pub thq_dispatch: Arc<DashMap<String, ThqDispatchEntry>>,
pub agent_dispatch_tokens: Arc<DashMap<String, (String, Instant)>>,
/* private fields */
}Expand description
Shared state accessible by all axum handlers.
Fields§
§sessions: Arc<DashMap<String, UserSessions>>Per-user multi-session registry (MSU).
ws_tx: Sender<String>Broadcast sender for backward compat — delegates to the default user’s channel.
auth: Option<Arc<AuthState>>Auth state (None = auth disabled, all endpoints open).
config_toml: Option<String>Shared config TOML (all users share the same agent config).
secrets: Option<HashMap<String, String>>Shared secrets (injected into every per-user session).
build_info: Option<BuildInfo>Shared build info (injected into every per-user session).
workflow_semaphore: Arc<Semaphore>Global concurrency limiter — limits the number of simultaneous workflows across all users. Default: 8 concurrent workflows.
max_sessions_per_user: usizeMaximum number of concurrent sessions per user. Default: 4.
allow_llm_overlay: boolWhether per-user config overlays may override the [llm] section.
Default: false — overlays are limited to [mcp].
mcp_loaders: Arc<DashMap<String, McpLoaderEntry>>Per-user McpToolLoader cache (16C), keyed by user hash (never the raw key).
thq_dispatch: Arc<DashMap<String, ThqDispatchEntry>>16F: THQ per-agent dispatch table (agent_name → target), boot-populated.
agent_dispatch_tokens: Arc<DashMap<String, (String, Instant)>>16F: cached impersonation Bearers per agent user_key
(token, expires_at) — expiry-buffered, re-minted on 401.
Implementations§
Source§impl ServerState
impl ServerState
Sourcepub fn new(
session: Session,
ws_tx: Sender<String>,
auth: Option<Arc<AuthState>>,
) -> Self
pub fn new( session: Session, ws_tx: Sender<String>, auth: Option<Arc<AuthState>>, ) -> Self
Create new shared state from a default session, broadcast sender, and optional auth.
pub fn with_config_toml(self, config_toml: String) -> Self
Sourcepub fn service_issuer(&self) -> Option<String>
pub fn service_issuer(&self) -> Option<String>
16F: the issuer URL Kanidm accepts SERVICE-ACCOUNT token exchange on.
Kanidm binds exchange to the OAuth2 client’s configured origin: the
[oidc] issuer host serves logins/validation fine but REJECTS token
exchange with invalid_request, while the idp vhost — the issuer
every working [mcp.credentials.*] service-account entry already
uses — accepts it (verified live 2026-08-30: same token, 200 vs 400).
The exchange therefore takes its issuer from the shared config’s
first service-account credential; callers fall back to the auth
issuer when absent.
pub fn with_secrets(self, secrets: HashMap<String, String>) -> Self
pub fn with_build_info(self, build_info: BuildInfo) -> Self
pub fn with_max_concurrent_workflows(self, max: usize) -> Self
Sourcepub fn with_max_sessions_per_user(self, max: usize) -> Self
pub fn with_max_sessions_per_user(self, max: usize) -> Self
Set the max sessions per user.
Sourcepub fn with_allow_llm_overlay(self, allow: bool) -> Self
pub fn with_allow_llm_overlay(self, allow: bool) -> Self
Allow per-user config overlays to override the [llm] section.
Default: false (overlays limited to [mcp]).
Sourcepub async fn create_session(
&self,
user_key: &str,
session_name: Option<String>,
identity: Option<String>,
activate: bool,
) -> Result<String, SessionError>
pub async fn create_session( &self, user_key: &str, session_name: Option<String>, identity: Option<String>, activate: bool, ) -> Result<String, SessionError>
Create a new session for a user. Returns the session_id.
Creates a fresh Session::new(), copies shared config, sets per-user
isolation, creates a broadcast channel, spawns a drain task, and inserts
into the user’s session DashMap. The new session becomes the “active” one.
Sourcepub async fn get_session(
&self,
user_key: &str,
session_id: &str,
) -> Option<(Arc<Mutex<Session>>, Sender<String>)>
pub async fn get_session( &self, user_key: &str, session_id: &str, ) -> Option<(Arc<Mutex<Session>>, Sender<String>)>
Get a specific session by user_key + session_id. Updates last_active on the session entry.
Sourcepub async fn get_session_by_any_id(
&self,
user_key: &str,
id: &str,
) -> Option<(String, Arc<Mutex<Session>>, Sender<String>)>
pub async fn get_session_by_any_id( &self, user_key: &str, id: &str, ) -> Option<(String, Arc<Mutex<Session>>, Sender<String>)>
Get a session by EITHER its live MSU registry key OR its
checkpoint/session identity (session.session_id).
The web frontend tracks currentSessionId from the ResumeInfo WS
message, which carries the auto-derived checkpoint id
(session_YYYY_MM_DD_HH_MM_uuid8) — NOT the live MSU registry key
("default" or the key from create_session()). External clients
like Torpi/THQ pass the live registry key. This resolver accepts both:
- Try registry-key lookup first (precise, used by Torpi/THQ).
- Fall back to scanning the user’s live sessions for one whose
session.session_idmatches the requested id (used by the embedded web UI after a command or resume).
Returns (live_registry_key, session_arc, ws_tx), or None if not
found. The live key is returned so callers that need to set it as
active (or otherwise reference the registry) use the real key.
Sourcepub async fn list_sessions(&self, user_key: &str) -> Vec<SessionListItem>
pub async fn list_sessions(&self, user_key: &str) -> Vec<SessionListItem>
List all active sessions for a user, sorted by last_active desc.
Sourcepub async fn destroy_session(
&self,
user_key: &str,
session_id: &str,
) -> Result<(), SessionError>
pub async fn destroy_session( &self, user_key: &str, session_id: &str, ) -> Result<(), SessionError>
Destroy a session. The session must be Idle.
Sourcepub async fn ensure_active_session(
&self,
user_key: &str,
) -> (String, Arc<Mutex<Session>>, Sender<String>, Arc<MemoryTokenStore>)
pub async fn ensure_active_session( &self, user_key: &str, ) -> (String, Arc<Mutex<Session>>, Sender<String>, Arc<MemoryTokenStore>)
Get or create the user’s “active” session for legacy routes.
Behavior:
- If user has no sessions → create one
- If active session exists → return it
- If active session was destroyed → create a new one
Returns: (session_id, session_arc, ws_tx, token_store)
Sourcepub async fn ensure_user_session(
&self,
user_key: &str,
) -> (Arc<Mutex<Session>>, Sender<String>, Arc<MemoryTokenStore>)
pub async fn ensure_user_session( &self, user_key: &str, ) -> (Arc<Mutex<Session>>, Sender<String>, Arc<MemoryTokenStore>)
DEPRECATED: Use ensure_active_session() instead. Kept for backward compatibility — same 3-tuple return type.
Sourcepub async fn set_active_session(&self, user_key: &str, session_id: &str)
pub async fn set_active_session(&self, user_key: &str, session_id: &str)
Set a session as the user’s active session.
Sourcepub fn get_user_home_dir(&self, user_key: &str) -> Option<PathBuf>
pub fn get_user_home_dir(&self, user_key: &str) -> Option<PathBuf>
Resolve a user’s home_dir without creating an in-memory session.
This is the read-only equivalent of the isolation logic in
apply_user_isolation. Used by endpoints that only need to read
checkpoint data from disk (history, session list, session detail)
and must NOT create ghost sessions as a side effect.
Sourcepub fn get_user_config_and_home(
&self,
user_key: &str,
) -> (Option<String>, Option<PathBuf>)
pub fn get_user_config_and_home( &self, user_key: &str, ) -> (Option<String>, Option<PathBuf>)
Resolve config_toml and home_dir without creating an in-memory session.
Returns (config_toml, home_dir). If config is not loaded,
config_toml will be None.
Sourcepub fn resolve_user_config(&self, user_key: &str) -> Option<String>
pub fn resolve_user_config(&self, user_key: &str) -> Option<String>
Resolve the fully-merged config TOML for a user WITHOUT creating a session.
This is the read-only equivalent of the config resolution in
apply_user_isolation: shared config + per-user overlay + ${VAR}
substitution. Used by endpoints that need to inspect config (e.g.
listing available LLM models) without spawning a ghost session.
Returns None if no shared config is loaded.
Sourcepub async fn get_or_build_mcp_loader(
&self,
user_key: &str,
token_store: &Arc<MemoryTokenStore>,
) -> Result<Option<Arc<McpToolLoader>>, String>
pub async fn get_or_build_mcp_loader( &self, user_key: &str, token_store: &Arc<MemoryTokenStore>, ) -> Result<Option<Arc<McpToolLoader>>, String>
Get or build the per-user MCP tool loader (16C).
Cache semantics:
- fingerprint = content hash of the effective
[mcp]section (shared + allowlist-filtered overlay + ${VAR} substitution, i.e. exactly whatresolve_user_configproduces) — stale on ANY change. - hit + match →
Arcclone, zero network I/O. - miss/stale → single-flight build (one build per user at a time; late arrivals re-check and reuse the winner’s entry).
Ok(None)= MCP disabled for this user → agent runs MCP-less via abkMcpSource::Prebuilt(None)(same semantics as[mcp] enabled = false, no per-task re-evaluation).- build failure → cached degraded entry with
[
MCP_BUILD_RETRY_BACKOFF]; the error is returned so THIS user’s dispatch fails loud while other users are unaffected.
Sourcepub fn spawn_drain_task(self, workflow_rx: UnboundedReceiver<TuiMessage>)
pub fn spawn_drain_task(self, workflow_rx: UnboundedReceiver<TuiMessage>)
Spawn the default user’s drain task (backward compatibility). Called during server startup for the initial session.
Sourcepub async fn resolve_user_key(&self, headers: &HeaderMap) -> String
pub async fn resolve_user_key(&self, headers: &HeaderMap) -> String
Resolve the user key from request headers.
Trait Implementations§
Source§impl Clone for ServerState
impl Clone for ServerState
Source§fn clone(&self) -> ServerState
fn clone(&self) -> ServerState
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreAuto Trait Implementations§
impl !RefUnwindSafe for ServerState
impl !UnwindSafe for ServerState
impl Freeze for ServerState
impl Send for ServerState
impl Sync for ServerState
impl Unpin for ServerState
impl UnsafeUnpin for ServerState
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self to use its Binary implementation when Debug-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self to use its Display implementation when
Debug-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self to use its LowerExp implementation when
Debug-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self to use its LowerHex implementation when
Debug-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self to use its Octal implementation when Debug-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self to use its Pointer implementation when
Debug-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self to use its UpperExp implementation when
Debug-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self to use its UpperHex implementation when
Debug-formatted.Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self, then passes self.as_ref() into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self, then passes self.as_mut() into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self, then passes self.deref() into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B> of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B> of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R> view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R> view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap() only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow() only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut() only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref() only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut() only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref() only in debug builds, and is erased in release
builds.