Skip to main content

aidaemon_tools/
services.rs

1//! Narrow store services that tools hold: settings, OAuth connections and
2//! runtime-managed CLI agents,
3//! plus the plain data those traits carry. The daemon's SQLite store
4//! implements them; a tool receives an `Arc<dyn ...>` of the slice it needs
5//! through its constructor. Memory stores (facts, episodes, history, people)
6//! live in `aidaemon-memory`.
7
8use 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
20/// A service or profile name (`label`: "Service", "Profile"): letters,
21/// digits, `_` and `-`, kept lowercase.
22pub 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
34/// The hosts a credential may be sent to: bare, lowercase, without a
35/// leading dot, at least one.
36pub 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
59/// The conversation's audience, shared across the SDK.
60pub use aidaemon_core::ChannelVisibility;
61
62/// An OAuth connection to an external service.
63#[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    /// Stable remote account identifier proven through an authenticated
70    /// identity endpoint. Mandate execution binds to this value rather than a
71    /// mutable provider alias or display name.
72    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/// A pending interactive OAuth flow awaiting browser callback completion.
80#[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/// Generic key/value settings persistence.
90#[async_trait]
91pub trait SettingsStore: Send + Sync {
92    /// Get a setting value by key. Returns None if unset.
93    async fn get_setting(&self, _key: &str) -> anyhow::Result<Option<String>> {
94        Ok(None)
95    }
96
97    /// Set a setting value. Creates or updates the key.
98    async fn set_setting(&self, _key: &str, _value: &str) -> anyhow::Result<()> {
99        Ok(())
100    }
101
102    /// Remove a setting; nothing happens when it is unset.
103    async fn delete_setting(&self, _key: &str) -> anyhow::Result<()> {
104        Ok(())
105    }
106}
107
108/// OAuth-connected external services persistence.
109#[async_trait]
110pub trait OAuthStore: Send + Sync {
111    /// Save an OAuth connection. Returns the connection ID.
112    async fn save_oauth_connection(&self, _conn: &OAuthConnection) -> anyhow::Result<i64> {
113        Ok(0)
114    }
115
116    /// Save or replace a pending interactive OAuth flow.
117    async fn save_pending_oauth_flow(&self, _flow: &PendingOAuthFlow) -> anyhow::Result<()> {
118        Ok(())
119    }
120
121    /// Get an OAuth connection by service name.
122    async fn get_oauth_connection(
123        &self,
124        _service: &str,
125    ) -> anyhow::Result<Option<OAuthConnection>> {
126        Ok(None)
127    }
128
129    /// List all OAuth connections.
130    async fn list_oauth_connections(&self) -> anyhow::Result<Vec<OAuthConnection>> {
131        Ok(vec![])
132    }
133
134    /// Persist or clear the verified remote account bound to an OAuth service.
135    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    /// Get a pending OAuth flow by state parameter.
144    async fn get_pending_oauth_flow(
145        &self,
146        _state: &str,
147    ) -> anyhow::Result<Option<PendingOAuthFlow>> {
148        Ok(None)
149    }
150
151    /// List all pending OAuth flows.
152    async fn list_pending_oauth_flows(&self) -> anyhow::Result<Vec<PendingOAuthFlow>> {
153        Ok(vec![])
154    }
155
156    /// Delete an OAuth connection by service name.
157    async fn delete_oauth_connection(&self, _service: &str) -> anyhow::Result<()> {
158        Ok(())
159    }
160
161    /// Delete a pending OAuth flow by state parameter.
162    async fn delete_pending_oauth_flow(&self, _state: &str) -> anyhow::Result<()> {
163        Ok(())
164    }
165
166    /// Update token expiry for an OAuth connection.
167    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/// A dynamically added CLI agent configuration (stored in database).
177#[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, // JSON array of argument strings
183    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/// A record of a CLI agent invocation for logging/auditing.
191#[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/// One thing a launched coding agent did, as its run's record keeps it:
208/// `kind` and `data` are a typed agent event's stored form (`session`, `step`, `step_ended`, `plan`, `usage`,
209/// `turn_ended`, `permission`).
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct CliAgentEvent {
212    pub seq: i64,
213    pub at: String,
214    pub kind: String,
215    /// Its fields, as JSON.
216    pub data: String,
217}
218
219/// The invocation behind one run of the runtime's records
220/// ([`DynamicCliAgentStore::cli_agent_run`]).
221#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct CliAgentRun {
223    pub invocation: i64,
224    /// The conversation it reported to.
225    pub session_id: String,
226    pub agent_name: String,
227    /// The agent's own session id, once it gave one.
228    pub agent_session: Option<String>,
229    pub working_dir: Option<String>,
230    pub prompt_summary: String,
231    /// What it was asked, whole ([`DynamicCliAgentStore::note_cli_agent_task`]);
232    /// an invocation from before it was kept has its summary alone.
233    pub task: Option<String>,
234    pub output_summary: Option<String>,
235    /// How it ended, once it did: whether it succeeded.
236    pub success: Option<bool>,
237    /// Its agent kept its session where a follow-up can continue it
238    /// ([`DynamicCliAgentStore::set_cli_agent_keeps_session`]).
239    pub keeps_session: bool,
240    /// The first run of its thread, when it continues one
241    /// ([`DynamicCliAgentStore::set_cli_agent_thread`]).
242    pub thread: Option<String>,
243    /// The tag its processes carry in their environment, once its process
244    /// was spawned ([`DynamicCliAgentStore::set_cli_agent_run_tag`]).
245    pub run_tag: Option<String>,
246    /// When its invocation was logged, in UTC as the store keeps it
247    /// (`YYYY-MM-DD HH:MM:SS`).
248    pub started_at: Option<String>,
249}
250
251/// A coding agents' team (one coordination tree of a conversation's lead)
252/// as kept: the tree's own bookkeeping and each member, as JSON the
253/// coordinating code writes and reads back
254/// ([`DynamicCliAgentStore::save_team`]).
255#[derive(Debug, Clone, PartialEq, Eq)]
256pub struct TeamRecord {
257    pub tree_id: String,
258    pub session_id: String,
259    /// The lead's agent (its tool name): a conversation keeps one team per
260    /// lead agent.
261    pub lead_agent: String,
262    /// The tree's bookkeeping (next peer number, next post, what the
263    /// owner's messages the lead was shown).
264    pub data: String,
265    /// Each member's record, by peer id.
266    pub members: Vec<(String, String)>,
267}
268
269/// One post on a team's board as kept ([`DynamicCliAgentStore::add_team_post`]).
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct TeamPostRecord {
272    pub tree_id: String,
273    pub seq: u64,
274    /// The lead's run when it was posted: which exchange it belongs to.
275    pub lead_run: Option<String>,
276    pub at_ms: Option<u64>,
277    /// The post, as JSON.
278    pub data: String,
279}
280
281/// A team as read back: its record and its newest posts, oldest first.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct SavedTeam {
284    pub team: TeamRecord,
285    pub posts: Vec<TeamPostRecord>,
286}
287
288/// Runtime-managed CLI agents persistence + invocation logs.
289#[async_trait]
290pub trait DynamicCliAgentStore: Send + Sync {
291    /// Keep `team` as it stands now: its bookkeeping and every member
292    /// (replacing what was kept of them).
293    async fn save_team(&self, _team: &TeamRecord) -> anyhow::Result<()> {
294        Ok(())
295    }
296
297    /// Keep one post of a team's board (once; a post kept again is left as
298    /// it was).
299    async fn add_team_post(&self, _post: &TeamPostRecord) -> anyhow::Result<()> {
300        Ok(())
301    }
302
303    /// The team conversation `session_id`'s lead `lead_agent` coordinated
304    /// most recently, with its newest `max_posts` posts.
305    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    /// Store a dynamically added CLI agent.
315    async fn save_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<i64> {
316        Ok(0)
317    }
318
319    /// Get all dynamic CLI agents.
320    async fn list_dynamic_cli_agents(&self) -> anyhow::Result<Vec<DynamicCliAgent>> {
321        Ok(vec![])
322    }
323
324    /// Delete a dynamic CLI agent by ID.
325    async fn delete_dynamic_cli_agent(&self, _id: i64) -> anyhow::Result<()> {
326        Ok(())
327    }
328
329    /// Update a dynamic CLI agent.
330    async fn update_dynamic_cli_agent(&self, _agent: &DynamicCliAgent) -> anyhow::Result<()> {
331        Ok(())
332    }
333
334    /// Log the start of a CLI agent invocation. Returns the invocation ID.
335    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    /// Log the completion of a CLI agent invocation.
347    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    /// Invocation `id` is run `run_id` in the runtime's records, launched in
359    /// `mode` (its permission mode's stored name, when one applies).
360    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    /// What invocation `id` was asked, whole: the task its run view shows.
370    async fn note_cli_agent_task(&self, _id: i64, _task: &str) -> anyhow::Result<()> {
371        Ok(())
372    }
373
374    /// Invocation `id` continues the thread whose first run is `thread`.
375    async fn set_cli_agent_thread(&self, _id: i64, _thread: &str) -> anyhow::Result<()> {
376        Ok(())
377    }
378
379    /// Whether invocation `id`'s agent keeps its session where a later run
380    /// can continue it.
381    async fn set_cli_agent_keeps_session(&self, _id: i64, _kept: bool) -> anyhow::Result<()> {
382        Ok(())
383    }
384
385    /// The tag invocation `id`'s processes carry in their environment
386    /// (`AIDAEMON_CLI_RUN`), kept at its spawn: what finds them after a
387    /// stop the daemon did not see coming.
388    async fn set_cli_agent_run_tag(&self, _id: i64, _run_tag: &str) -> anyhow::Result<()> {
389        Ok(())
390    }
391
392    /// The agent's own session (Claude Code's session id, Codex's thread id,
393    /// an ACP session id): what resumes it or finds its own transcript.
394    async fn set_cli_agent_session(&self, _id: i64, _agent_session: &str) -> anyhow::Result<()> {
395        Ok(())
396    }
397
398    /// Keep one event of invocation `id`, in order (`seq`).
399    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    /// The invocation that is run `run_id` in the runtime's records, when
410    /// one is.
411    async fn cli_agent_run(&self, _run_id: &str) -> anyhow::Result<Option<CliAgentRun>> {
412        Ok(None)
413    }
414
415    /// The latest run id in conversation `session_id` belonging to `thread`
416    /// (matching either `run_id = thread` or `thread_id = thread`).
417    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    /// The latest run of conversation `session_id` by agent `agent_name`
426    /// that kept its agent's session (a follow-up can go on from it).
427    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    /// The latest run of conversation `session_id` by agent `agent_name`,
436    /// however it ended (or still working).
437    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    /// Invocation `id`'s events, in order.
446    async fn get_cli_agent_events(&self, _id: i64) -> anyhow::Result<Vec<CliAgentEvent>> {
447        Ok(vec![])
448    }
449
450    /// Get recent CLI agent invocations (most recent first).
451    async fn get_cli_agent_invocations(
452        &self,
453        _limit: usize,
454    ) -> anyhow::Result<Vec<CliAgentInvocation>> {
455        Ok(vec![])
456    }
457
458    /// Auto-close stale CLI agent invocations that never completed (e.g. crashed worker).
459    ///
460    /// Implementations should mark rows with `completed_at IS NULL` and older than
461    /// `max_age_hours` as completed with `success=false`.
462    async fn cleanup_stale_cli_agent_invocations(
463        &self,
464        _max_age_hours: i64,
465    ) -> anyhow::Result<u64> {
466        Ok(0)
467    }
468}
469
470/// OAuth flows only need OAuth connection and pending-flow persistence.
471pub trait OAuthGatewayStore: OAuthStore {}
472
473impl<T> OAuthGatewayStore for T where T: OAuthStore {}
474
475/// OAuth connections and pending flows kept in memory, for tests and hosts
476/// without a database. Same upsert rules as the daemon's SQLite store.
477#[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}