1use async_trait::async_trait;
9use serde::{Deserialize, Serialize};
10
11#[cfg(feature = "oauth")]
12pub mod manage_auth;
13#[cfg(feature = "oauth")]
14pub mod manage_http_auth;
15#[cfg(feature = "oauth")]
16pub mod manage_oauth;
17#[cfg(feature = "oauth")]
18pub mod oauth;
19
20pub fn validate_identifier(raw: &str, label: &str) -> anyhow::Result<String> {
23 let trimmed = raw.trim();
24 anyhow::ensure!(!trimmed.is_empty(), "{label} name must not be empty");
25 anyhow::ensure!(
26 trimmed
27 .chars()
28 .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')),
29 "{label} name '{trimmed}' is invalid. Use only letters, numbers, '_' or '-'."
30 );
31 Ok(trimmed.to_ascii_lowercase())
32}
33
34pub fn normalize_domains(domains: &[String]) -> anyhow::Result<Vec<String>> {
37 let normalized: Vec<String> = domains
38 .iter()
39 .map(|domain| domain.trim().trim_start_matches('.').to_ascii_lowercase())
40 .filter(|domain| !domain.is_empty())
41 .map(|domain| {
42 anyhow::ensure!(
43 !domain.contains("://")
44 && !domain.contains('/')
45 && !domain.contains(char::is_whitespace),
46 "Allowed domain '{}' must be a bare host/domain, not a URL or path.",
47 domain
48 );
49 Ok(domain)
50 })
51 .collect::<anyhow::Result<_>>()?;
52 anyhow::ensure!(
53 !normalized.is_empty(),
54 "`allowed_domains` must contain at least one hostname."
55 );
56 Ok(normalized)
57}
58
59pub use aidaemon_core::ChannelVisibility;
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct OAuthConnection {
65 pub id: i64,
66 pub service: String,
67 pub auth_type: String,
68 pub username: Option<String>,
69 pub account_id: Option<String>,
73 pub scopes: String,
74 pub token_expires_at: Option<String>,
75 pub created_at: String,
76 pub updated_at: String,
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct PendingOAuthFlow {
82 pub state: String,
83 pub service: String,
84 pub code_verifier: Option<String>,
85 pub session_id: String,
86 pub created_at: String,
87}
88
89#[async_trait]
91pub trait SettingsStore: Send + Sync {
92 async fn get_setting(&self, _key: &str) -> anyhow::Result<Option<String>> {
94 Ok(None)
95 }
96
97 async fn set_setting(&self, _key: &str, _value: &str) -> anyhow::Result<()> {
99 Ok(())
100 }
101
102 async fn delete_setting(&self, _key: &str) -> anyhow::Result<()> {
104 Ok(())
105 }
106}
107
108#[async_trait]
110pub trait OAuthStore: Send + Sync {
111 async fn save_oauth_connection(&self, _conn: &OAuthConnection) -> anyhow::Result<i64> {
113 Ok(0)
114 }
115
116 async fn save_pending_oauth_flow(&self, _flow: &PendingOAuthFlow) -> anyhow::Result<()> {
118 Ok(())
119 }
120
121 async fn get_oauth_connection(
123 &self,
124 _service: &str,
125 ) -> anyhow::Result<Option<OAuthConnection>> {
126 Ok(None)
127 }
128
129 async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
131 Ok(vec![])
132 }
133
134 async fn update_oauth_account_id(
136 &self,
137 _service: &str,
138 _account_id: Option<&str>,
139 ) -> anyhow::Result<bool> {
140 Ok(false)
141 }
142
143 async fn get_pending_oauth_flow(
145 &self,
146 _state: &str,
147 ) -> anyhow::Result<Option<PendingOAuthFlow>> {
148 Ok(None)
149 }
150
151 async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
153 Ok(vec![])
154 }
155
156 async fn delete_oauth_connection(&self, _service: &str) -> anyhow::Result<()> {
158 Ok(())
159 }
160
161 async fn delete_pending_oauth_flow(&self, _state: &str) -> anyhow::Result<()> {
163 Ok(())
164 }
165
166 async fn update_oauth_token_expiry(
168 &self,
169 _service: &str,
170 _expires_at: Option<&str>,
171 ) -> anyhow::Result<()> {
172 Ok(())
173 }
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
178pub struct DynamicCliAgent {
179 pub id: i64,
180 pub name: String,
181 pub command: String,
182 pub args_json: String, pub description: String,
184 pub timeout_secs: Option<u64>,
185 pub max_output_chars: Option<usize>,
186 pub enabled: bool,
187 pub created_at: String,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
192pub struct CliAgentInvocation {
193 pub id: i64,
194 pub task_id: Option<String>,
195 pub session_id: String,
196 pub agent_name: String,
197 pub prompt_summary: String,
198 pub working_dir: Option<String>,
199 pub started_at: String,
200 pub completed_at: Option<String>,
201 pub exit_code: Option<i32>,
202 pub output_summary: Option<String>,
203 pub success: Option<bool>,
204 pub duration_secs: Option<f64>,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct CliAgentEvent {
212 pub seq: i64,
213 pub at: String,
214 pub kind: String,
215 pub data: String,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct CliAgentRun {
223 pub invocation: i64,
224 pub session_id: String,
226 pub agent_name: String,
227 pub agent_session: Option<String>,
229 pub working_dir: Option<String>,
230 pub prompt_summary: String,
231 pub task: Option<String>,
234 pub output_summary: Option<String>,
235 pub success: Option<bool>,
237 pub keeps_session: bool,
240 pub thread: Option<String>,
243 pub run_tag: Option<String>,
246 pub started_at: Option<String>,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct TeamRecord {
257 pub tree_id: String,
258 pub session_id: String,
259 pub lead_agent: String,
262 pub data: String,
265 pub members: Vec<(String, String)>,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct TeamPostRecord {
272 pub tree_id: String,
273 pub seq: u64,
274 pub lead_run: Option<String>,
276 pub at_ms: Option<u64>,
277 pub data: String,
279}
280
281#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct SavedTeam {
284 pub team: TeamRecord,
285 pub posts: Vec<TeamPostRecord>,
286}
287
288#[async_trait]
290pub trait DynamicCliAgentStore: Send + Sync {
291 async fn save_team(&self, _team: &TeamRecord) -> anyhow::Result<()> {
294 Ok(())
295 }
296
297 async fn add_team_post(&self, _post: &TeamPostRecord) -> anyhow::Result<()> {
300 Ok(())
301 }
302
303 async fn conversation_team(
306 &self,
307 _session_id: &str,
308 _lead_agent: &str,
309 _max_posts: usize,
310 ) -> anyhow::Result<Option<SavedTeam>> {
311 Ok(None)
312 }
313
314 async fn save_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<i64> {
316 Ok(0)
317 }
318
319 async fn list_dynamic_cli_agents(&self) -> anyhow::Result<Vec<DynamicCliAgent>> {
321 Ok(vec![])
322 }
323
324 async fn delete_dynamic_cli_agent(&self, _id: i64) -> anyhow::Result<()> {
326 Ok(())
327 }
328
329 async fn update_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<()> {
331 Ok(())
332 }
333
334 async fn log_cli_agent_start(
336 &self,
337 _task_id: Option<&str>,
338 _session_id: &str,
339 _agent_name: &str,
340 _prompt_summary: &str,
341 _working_dir: Option<&str>,
342 ) -> anyhow::Result<i64> {
343 Ok(0)
344 }
345
346 async fn log_cli_agent_complete(
348 &self,
349 _id: i64,
350 _exit_code: Option<i32>,
351 _output_summary: &str,
352 _success: bool,
353 _duration_secs: f64,
354 ) -> anyhow::Result<()> {
355 Ok(())
356 }
357
358 async fn note_cli_agent_run(
361 &self,
362 _id: i64,
363 _run_id: &str,
364 _mode: Option<&str>,
365 ) -> anyhow::Result<()> {
366 Ok(())
367 }
368
369 async fn note_cli_agent_task(&self, _id: i64, _task: &str) -> anyhow::Result<()> {
371 Ok(())
372 }
373
374 async fn set_cli_agent_thread(&self, _id: i64, _thread: &str) -> anyhow::Result<()> {
376 Ok(())
377 }
378
379 async fn set_cli_agent_keeps_session(&self, _id: i64, _kept: bool) -> anyhow::Result<()> {
382 Ok(())
383 }
384
385 async fn set_cli_agent_run_tag(&self, _id: i64, _run_tag: &str) -> anyhow::Result<()> {
389 Ok(())
390 }
391
392 async fn set_cli_agent_session(&self, _id: i64, _agent_session: &str) -> anyhow::Result<()> {
395 Ok(())
396 }
397
398 async fn record_cli_agent_event(
400 &self,
401 _id: i64,
402 _seq: i64,
403 _kind: &str,
404 _data: &str,
405 ) -> anyhow::Result<()> {
406 Ok(())
407 }
408
409 async fn cli_agent_run(&self, _run_id: &str) -> anyhow::Result<Option<CliAgentRun>> {
412 Ok(None)
413 }
414
415 async fn latest_cli_agent_run_in_thread(
418 &self,
419 _session_id: &str,
420 _thread: &str,
421 ) -> anyhow::Result<Option<String>> {
422 Ok(None)
423 }
424
425 async fn latest_kept_cli_agent_run(
428 &self,
429 _session_id: &str,
430 _agent_name: &str,
431 ) -> anyhow::Result<Option<String>> {
432 Ok(None)
433 }
434
435 async fn get_cli_agent_events(&self, _id: i64) -> anyhow::Result<Vec<CliAgentEvent>> {
437 Ok(vec![])
438 }
439
440 async fn get_cli_agent_invocations(
442 &self,
443 _limit: usize,
444 ) -> anyhow::Result<Vec<CliAgentInvocation>> {
445 Ok(vec![])
446 }
447
448 async fn cleanup_stale_cli_agent_invocations(
453 &self,
454 _max_age_hours: i64,
455 ) -> anyhow::Result<u64> {
456 Ok(0)
457 }
458}
459
460pub trait OAuthGatewayStore: OAuthStore {}
462
463impl<T> OAuthGatewayStore for T where T: OAuthStore {}
464
465#[derive(Default)]
468pub struct InMemoryOAuthStore {
469 inner: std::sync::Mutex<InMemoryOAuth>,
470}
471
472#[derive(Default)]
473struct InMemoryOAuth {
474 next_id: i64,
475 connections: std::collections::BTreeMap<String, OAuthConnection>,
476 flows: std::collections::HashMap<String, PendingOAuthFlow>,
477}
478
479impl InMemoryOAuthStore {
480 pub fn new() -> Self {
481 Self::default()
482 }
483
484 fn lock(&self) -> std::sync::MutexGuard<'_, InMemoryOAuth> {
485 self.inner
486 .lock()
487 .unwrap_or_else(std::sync::PoisonError::into_inner)
488 }
489}
490
491#[async_trait]
492impl OAuthStore for InMemoryOAuthStore {
493 async fn save_oauth_connection(&self, conn: &OAuthConnection) -> anyhow::Result<i64> {
494 let now = chrono::Utc::now().to_rfc3339();
495 let mut inner = self.lock();
496 let (id, created_at) = match inner.connections.get(&conn.service) {
497 Some(existing) => (existing.id, existing.created_at.clone()),
498 None => {
499 inner.next_id += 1;
500 (inner.next_id, now.clone())
501 }
502 };
503 inner.connections.insert(
504 conn.service.clone(),
505 OAuthConnection {
506 id,
507 created_at,
508 updated_at: now,
509 ..conn.clone()
510 },
511 );
512 Ok(id)
513 }
514
515 async fn save_pending_oauth_flow(&self, flow: &PendingOAuthFlow) -> anyhow::Result<()> {
516 self.lock().flows.insert(flow.state.clone(), flow.clone());
517 Ok(())
518 }
519
520 async fn get_oauth_connection(&self, service: &str) -> anyhow::Result<Option<OAuthConnection>> {
521 Ok(self.lock().connections.get(service).cloned())
522 }
523
524 async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
525 Ok(self.lock().connections.values().cloned().collect())
526 }
527
528 async fn update_oauth_account_id(
529 &self,
530 service: &str,
531 account_id: Option<&str>,
532 ) -> anyhow::Result<bool> {
533 let mut inner = self.lock();
534 let Some(conn) = inner.connections.get_mut(service) else {
535 return Ok(false);
536 };
537 conn.account_id = account_id.map(str::to_string);
538 conn.updated_at = chrono::Utc::now().to_rfc3339();
539 Ok(true)
540 }
541
542 async fn get_pending_oauth_flow(
543 &self,
544 state: &str,
545 ) -> anyhow::Result<Option<PendingOAuthFlow>> {
546 Ok(self.lock().flows.get(state).cloned())
547 }
548
549 async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
550 let mut flows: Vec<PendingOAuthFlow> = self.lock().flows.values().cloned().collect();
551 flows.sort_by(|a, b| a.created_at.cmp(&b.created_at));
552 Ok(flows)
553 }
554
555 async fn delete_oauth_connection(&self, service: &str) -> anyhow::Result<()> {
556 self.lock().connections.remove(service);
557 Ok(())
558 }
559
560 async fn delete_pending_oauth_flow(&self, state: &str) -> anyhow::Result<()> {
561 self.lock().flows.remove(state);
562 Ok(())
563 }
564
565 async fn update_oauth_token_expiry(
566 &self,
567 service: &str,
568 expires_at: Option<&str>,
569 ) -> anyhow::Result<()> {
570 if let Some(conn) = self.lock().connections.get_mut(service) {
571 conn.token_expires_at = expires_at.map(str::to_string);
572 conn.updated_at = chrono::Utc::now().to_rfc3339();
573 }
574 Ok(())
575 }
576}