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 latest_cli_agent_run_by(
438 &self,
439 _session_id: &str,
440 _agent_name: &str,
441 ) -> anyhow::Result<Option<String>> {
442 Ok(None)
443 }
444
445 async fn get_cli_agent_events(&self, _id: i64) -> anyhow::Result<Vec<CliAgentEvent>> {
447 Ok(vec![])
448 }
449
450 async fn get_cli_agent_invocations(
452 &self,
453 _limit: usize,
454 ) -> anyhow::Result<Vec<CliAgentInvocation>> {
455 Ok(vec![])
456 }
457
458 async fn cleanup_stale_cli_agent_invocations(
463 &self,
464 _max_age_hours: i64,
465 ) -> anyhow::Result<u64> {
466 Ok(0)
467 }
468}
469
470pub trait OAuthGatewayStore: OAuthStore {}
472
473impl<T> OAuthGatewayStore for T where T: OAuthStore {}
474
475#[derive(Default)]
478pub struct InMemoryOAuthStore {
479 inner: std::sync::Mutex<InMemoryOAuth>,
480}
481
482#[derive(Default)]
483struct InMemoryOAuth {
484 next_id: i64,
485 connections: std::collections::BTreeMap<String, OAuthConnection>,
486 flows: std::collections::HashMap<String, PendingOAuthFlow>,
487}
488
489impl InMemoryOAuthStore {
490 pub fn new() -> Self {
491 Self::default()
492 }
493
494 fn lock(&self) -> std::sync::MutexGuard<'_, InMemoryOAuth> {
495 self.inner
496 .lock()
497 .unwrap_or_else(std::sync::PoisonError::into_inner)
498 }
499}
500
501#[async_trait]
502impl OAuthStore for InMemoryOAuthStore {
503 async fn save_oauth_connection(&self, conn: &OAuthConnection) -> anyhow::Result<i64> {
504 let now = chrono::Utc::now().to_rfc3339();
505 let mut inner = self.lock();
506 let (id, created_at) = match inner.connections.get(&conn.service) {
507 Some(existing) => (existing.id, existing.created_at.clone()),
508 None => {
509 inner.next_id += 1;
510 (inner.next_id, now.clone())
511 }
512 };
513 inner.connections.insert(
514 conn.service.clone(),
515 OAuthConnection {
516 id,
517 created_at,
518 updated_at: now,
519 ..conn.clone()
520 },
521 );
522 Ok(id)
523 }
524
525 async fn save_pending_oauth_flow(&self, flow: &PendingOAuthFlow) -> anyhow::Result<()> {
526 self.lock().flows.insert(flow.state.clone(), flow.clone());
527 Ok(())
528 }
529
530 async fn get_oauth_connection(&self, service: &str) -> anyhow::Result<Option<OAuthConnection>> {
531 Ok(self.lock().connections.get(service).cloned())
532 }
533
534 async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
535 Ok(self.lock().connections.values().cloned().collect())
536 }
537
538 async fn update_oauth_account_id(
539 &self,
540 service: &str,
541 account_id: Option<&str>,
542 ) -> anyhow::Result<bool> {
543 let mut inner = self.lock();
544 let Some(conn) = inner.connections.get_mut(service) else {
545 return Ok(false);
546 };
547 conn.account_id = account_id.map(str::to_string);
548 conn.updated_at = chrono::Utc::now().to_rfc3339();
549 Ok(true)
550 }
551
552 async fn get_pending_oauth_flow(
553 &self,
554 state: &str,
555 ) -> anyhow::Result<Option<PendingOAuthFlow>> {
556 Ok(self.lock().flows.get(state).cloned())
557 }
558
559 async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
560 let mut flows: Vec<PendingOAuthFlow> = self.lock().flows.values().cloned().collect();
561 flows.sort_by(|a, b| a.created_at.cmp(&b.created_at));
562 Ok(flows)
563 }
564
565 async fn delete_oauth_connection(&self, service: &str) -> anyhow::Result<()> {
566 self.lock().connections.remove(service);
567 Ok(())
568 }
569
570 async fn delete_pending_oauth_flow(&self, state: &str) -> anyhow::Result<()> {
571 self.lock().flows.remove(state);
572 Ok(())
573 }
574
575 async fn update_oauth_token_expiry(
576 &self,
577 service: &str,
578 expires_at: Option<&str>,
579 ) -> anyhow::Result<()> {
580 if let Some(conn) = self.lock().connections.get_mut(service) {
581 conn.token_expires_at = expires_at.map(str::to_string);
582 conn.updated_at = chrono::Utc::now().to_rfc3339();
583 }
584 Ok(())
585 }
586}