Skip to main content

aidaemon_channels/
approvals.rs

1//! Pending approvals that outlive the process.
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5
6use aidaemon_core::{RunId, StoreError};
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::channel::{Conversation, MessageRef};
11
12/// One open approval, as the runner needs it after a restart. The interrupted
13/// run itself is not copied here: it is read back from the runner's
14/// [`aidaemon_core::RunStore`] by `run_id`, so the approval can never resume
15/// anything other than what that store says is waiting.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct StoredApproval {
18    pub prompt_id: String,
19    pub session_id: String,
20    /// The channel's name. Channels are matched by name on restart.
21    pub channel: String,
22    pub conversation: Conversation,
23    pub reply_to: Option<String>,
24    pub run_id: RunId,
25    pub prompt_text: String,
26    pub prompt_ref: Option<MessageRef>,
27    /// When the approval is answered with Deny, in milliseconds since the
28    /// Unix epoch. Wall-clock, so time spent stopped counts.
29    pub expires_at_ms: u64,
30}
31
32/// Where the runner keeps open approvals. Implement it on your database to
33/// survive restarts; [`MemoryApprovalStore`] is the in-process version. Set it
34/// with [`crate::ChannelRunnerBuilder::approval_store`].
35///
36/// A record is removed before its run resumes. A crash between the two leaves
37/// a call that never runs, which is the safe way round: the other order could
38/// run an approved call twice.
39#[async_trait]
40pub trait ApprovalStore: Send + Sync {
41    /// Insert or replace the record with this `prompt_id`.
42    async fn save(&self, approval: &StoredApproval) -> Result<(), StoreError>;
43    async fn remove(&self, prompt_id: &str) -> Result<(), StoreError>;
44    async fn load_all(&self) -> Result<Vec<StoredApproval>, StoreError>;
45}
46
47#[derive(Default)]
48pub struct MemoryApprovalStore {
49    approvals: Mutex<HashMap<String, StoredApproval>>,
50}
51
52impl MemoryApprovalStore {
53    pub fn new() -> Self {
54        Self::default()
55    }
56}
57
58#[async_trait]
59impl ApprovalStore for MemoryApprovalStore {
60    async fn save(&self, approval: &StoredApproval) -> Result<(), StoreError> {
61        self.approvals
62            .lock()
63            .expect("approval store poisoned")
64            .insert(approval.prompt_id.clone(), approval.clone());
65        Ok(())
66    }
67
68    async fn remove(&self, prompt_id: &str) -> Result<(), StoreError> {
69        self.approvals
70            .lock()
71            .expect("approval store poisoned")
72            .remove(prompt_id);
73        Ok(())
74    }
75
76    async fn load_all(&self) -> Result<Vec<StoredApproval>, StoreError> {
77        Ok(self
78            .approvals
79            .lock()
80            .expect("approval store poisoned")
81            .values()
82            .cloned()
83            .collect())
84    }
85}