use async_trait::async_trait;
use serde::{Deserialize, Serialize};
#[cfg(feature = "oauth")]
pub mod manage_auth;
#[cfg(feature = "oauth")]
pub mod manage_http_auth;
#[cfg(feature = "oauth")]
pub mod manage_oauth;
#[cfg(feature = "oauth")]
pub mod oauth;
pub fn validate_identifier(raw: &str, label: &str) -> anyhow::Result<String> {
let trimmed = raw.trim();
anyhow::ensure!(!trimmed.is_empty(), "{label} name must not be empty");
anyhow::ensure!(
trimmed
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')),
"{label} name '{trimmed}' is invalid. Use only letters, numbers, '_' or '-'."
);
Ok(trimmed.to_ascii_lowercase())
}
pub fn normalize_domains(domains: &[String]) -> anyhow::Result<Vec<String>> {
let normalized: Vec<String> = domains
.iter()
.map(|domain| domain.trim().trim_start_matches('.').to_ascii_lowercase())
.filter(|domain| !domain.is_empty())
.map(|domain| {
anyhow::ensure!(
!domain.contains("://")
&& !domain.contains('/')
&& !domain.contains(char::is_whitespace),
"Allowed domain '{}' must be a bare host/domain, not a URL or path.",
domain
);
Ok(domain)
})
.collect::<anyhow::Result<_>>()?;
anyhow::ensure!(
!normalized.is_empty(),
"`allowed_domains` must contain at least one hostname."
);
Ok(normalized)
}
pub use aidaemon_core::ChannelVisibility;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuthConnection {
pub id: i64,
pub service: String,
pub auth_type: String,
pub username: Option<String>,
pub account_id: Option<String>,
pub scopes: String,
pub token_expires_at: Option<String>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingOAuthFlow {
pub state: String,
pub service: String,
pub code_verifier: Option<String>,
pub session_id: String,
pub created_at: String,
}
#[async_trait]
pub trait SettingsStore: Send + Sync {
async fn get_setting(&self, _key: &str) -> anyhow::Result<Option<String>> {
Ok(None)
}
async fn set_setting(&self, _key: &str, _value: &str) -> anyhow::Result<()> {
Ok(())
}
async fn delete_setting(&self, _key: &str) -> anyhow::Result<()> {
Ok(())
}
}
#[async_trait]
pub trait OAuthStore: Send + Sync {
async fn save_oauth_connection(&self, _conn: &OAuthConnection) -> anyhow::Result<i64> {
Ok(0)
}
async fn save_pending_oauth_flow(&self, _flow: &PendingOAuthFlow) -> anyhow::Result<()> {
Ok(())
}
async fn get_oauth_connection(
&self,
_service: &str,
) -> anyhow::Result<Option<OAuthConnection>> {
Ok(None)
}
async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
Ok(vec![])
}
async fn update_oauth_account_id(
&self,
_service: &str,
_account_id: Option<&str>,
) -> anyhow::Result<bool> {
Ok(false)
}
async fn get_pending_oauth_flow(
&self,
_state: &str,
) -> anyhow::Result<Option<PendingOAuthFlow>> {
Ok(None)
}
async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
Ok(vec![])
}
async fn delete_oauth_connection(&self, _service: &str) -> anyhow::Result<()> {
Ok(())
}
async fn delete_pending_oauth_flow(&self, _state: &str) -> anyhow::Result<()> {
Ok(())
}
async fn update_oauth_token_expiry(
&self,
_service: &str,
_expires_at: Option<&str>,
) -> anyhow::Result<()> {
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicCliAgent {
pub id: i64,
pub name: String,
pub command: String,
pub args_json: String, pub description: String,
pub timeout_secs: Option<u64>,
pub max_output_chars: Option<usize>,
pub enabled: bool,
pub created_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliAgentInvocation {
pub id: i64,
pub task_id: Option<String>,
pub session_id: String,
pub agent_name: String,
pub prompt_summary: String,
pub working_dir: Option<String>,
pub started_at: String,
pub completed_at: Option<String>,
pub exit_code: Option<i32>,
pub output_summary: Option<String>,
pub success: Option<bool>,
pub duration_secs: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliAgentEvent {
pub seq: i64,
pub at: String,
pub kind: String,
pub data: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliAgentRun {
pub invocation: i64,
pub session_id: String,
pub agent_name: String,
pub agent_session: Option<String>,
pub working_dir: Option<String>,
pub prompt_summary: String,
pub task: Option<String>,
pub output_summary: Option<String>,
pub success: Option<bool>,
pub keeps_session: bool,
pub thread: Option<String>,
pub run_tag: Option<String>,
pub started_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamRecord {
pub tree_id: String,
pub session_id: String,
pub lead_agent: String,
pub data: String,
pub members: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamPostRecord {
pub tree_id: String,
pub seq: u64,
pub lead_run: Option<String>,
pub at_ms: Option<u64>,
pub data: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SavedTeam {
pub team: TeamRecord,
pub posts: Vec<TeamPostRecord>,
}
#[async_trait]
pub trait DynamicCliAgentStore: Send + Sync {
async fn save_team(&self, _team: &TeamRecord) -> anyhow::Result<()> {
Ok(())
}
async fn add_team_post(&self, _post: &TeamPostRecord) -> anyhow::Result<()> {
Ok(())
}
async fn conversation_team(
&self,
_session_id: &str,
_lead_agent: &str,
_max_posts: usize,
) -> anyhow::Result<Option<SavedTeam>> {
Ok(None)
}
async fn save_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<i64> {
Ok(0)
}
async fn list_dynamic_cli_agents(&self) -> anyhow::Result<Vec<DynamicCliAgent>> {
Ok(vec![])
}
async fn delete_dynamic_cli_agent(&self, _id: i64) -> anyhow::Result<()> {
Ok(())
}
async fn update_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<()> {
Ok(())
}
async fn log_cli_agent_start(
&self,
_task_id: Option<&str>,
_session_id: &str,
_agent_name: &str,
_prompt_summary: &str,
_working_dir: Option<&str>,
) -> anyhow::Result<i64> {
Ok(0)
}
async fn log_cli_agent_complete(
&self,
_id: i64,
_exit_code: Option<i32>,
_output_summary: &str,
_success: bool,
_duration_secs: f64,
) -> anyhow::Result<()> {
Ok(())
}
async fn note_cli_agent_run(
&self,
_id: i64,
_run_id: &str,
_mode: Option<&str>,
) -> anyhow::Result<()> {
Ok(())
}
async fn note_cli_agent_task(&self, _id: i64, _task: &str) -> anyhow::Result<()> {
Ok(())
}
async fn set_cli_agent_thread(&self, _id: i64, _thread: &str) -> anyhow::Result<()> {
Ok(())
}
async fn set_cli_agent_keeps_session(&self, _id: i64, _kept: bool) -> anyhow::Result<()> {
Ok(())
}
async fn set_cli_agent_run_tag(&self, _id: i64, _run_tag: &str) -> anyhow::Result<()> {
Ok(())
}
async fn set_cli_agent_session(&self, _id: i64, _agent_session: &str) -> anyhow::Result<()> {
Ok(())
}
async fn record_cli_agent_event(
&self,
_id: i64,
_seq: i64,
_kind: &str,
_data: &str,
) -> anyhow::Result<()> {
Ok(())
}
async fn cli_agent_run(&self, _run_id: &str) -> anyhow::Result<Option<CliAgentRun>> {
Ok(None)
}
async fn latest_cli_agent_run_in_thread(
&self,
_session_id: &str,
_thread: &str,
) -> anyhow::Result<Option<String>> {
Ok(None)
}
async fn latest_kept_cli_agent_run(
&self,
_session_id: &str,
_agent_name: &str,
) -> anyhow::Result<Option<String>> {
Ok(None)
}
async fn get_cli_agent_events(&self, _id: i64) -> anyhow::Result<Vec<CliAgentEvent>> {
Ok(vec![])
}
async fn get_cli_agent_invocations(
&self,
_limit: usize,
) -> anyhow::Result<Vec<CliAgentInvocation>> {
Ok(vec![])
}
async fn cleanup_stale_cli_agent_invocations(
&self,
_max_age_hours: i64,
) -> anyhow::Result<u64> {
Ok(0)
}
}
pub trait OAuthGatewayStore: OAuthStore {}
impl<T> OAuthGatewayStore for T where T: OAuthStore {}
#[derive(Default)]
pub struct InMemoryOAuthStore {
inner: std::sync::Mutex<InMemoryOAuth>,
}
#[derive(Default)]
struct InMemoryOAuth {
next_id: i64,
connections: std::collections::BTreeMap<String, OAuthConnection>,
flows: std::collections::HashMap<String, PendingOAuthFlow>,
}
impl InMemoryOAuthStore {
pub fn new() -> Self {
Self::default()
}
fn lock(&self) -> std::sync::MutexGuard<'_, InMemoryOAuth> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
#[async_trait]
impl OAuthStore for InMemoryOAuthStore {
async fn save_oauth_connection(&self, conn: &OAuthConnection) -> anyhow::Result<i64> {
let now = chrono::Utc::now().to_rfc3339();
let mut inner = self.lock();
let (id, created_at) = match inner.connections.get(&conn.service) {
Some(existing) => (existing.id, existing.created_at.clone()),
None => {
inner.next_id += 1;
(inner.next_id, now.clone())
}
};
inner.connections.insert(
conn.service.clone(),
OAuthConnection {
id,
created_at,
updated_at: now,
..conn.clone()
},
);
Ok(id)
}
async fn save_pending_oauth_flow(&self, flow: &PendingOAuthFlow) -> anyhow::Result<()> {
self.lock().flows.insert(flow.state.clone(), flow.clone());
Ok(())
}
async fn get_oauth_connection(&self, service: &str) -> anyhow::Result<Option<OAuthConnection>> {
Ok(self.lock().connections.get(service).cloned())
}
async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
Ok(self.lock().connections.values().cloned().collect())
}
async fn update_oauth_account_id(
&self,
service: &str,
account_id: Option<&str>,
) -> anyhow::Result<bool> {
let mut inner = self.lock();
let Some(conn) = inner.connections.get_mut(service) else {
return Ok(false);
};
conn.account_id = account_id.map(str::to_string);
conn.updated_at = chrono::Utc::now().to_rfc3339();
Ok(true)
}
async fn get_pending_oauth_flow(
&self,
state: &str,
) -> anyhow::Result<Option<PendingOAuthFlow>> {
Ok(self.lock().flows.get(state).cloned())
}
async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
let mut flows: Vec<PendingOAuthFlow> = self.lock().flows.values().cloned().collect();
flows.sort_by(|a, b| a.created_at.cmp(&b.created_at));
Ok(flows)
}
async fn delete_oauth_connection(&self, service: &str) -> anyhow::Result<()> {
self.lock().connections.remove(service);
Ok(())
}
async fn delete_pending_oauth_flow(&self, state: &str) -> anyhow::Result<()> {
self.lock().flows.remove(state);
Ok(())
}
async fn update_oauth_token_expiry(
&self,
service: &str,
expires_at: Option<&str>,
) -> anyhow::Result<()> {
if let Some(conn) = self.lock().connections.get_mut(service) {
conn.token_expires_at = expires_at.map(str::to_string);
conn.updated_at = chrono::Utc::now().to_rfc3339();
}
Ok(())
}
}