Skip to main content

adk_kernel/drivers/
store.rs

1//! Driver records, parked driver calls and the [`DriverStore`] (spec 3.2 §7.7, §9.3,
2//! §13 Q8, Q9).
3
4use std::collections::BTreeMap;
5
6use adk_core::{ApprovalScope, ToolConfirmationRequest};
7use adk_tool::mcp::ParkedMcpCall;
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11
12use super::manifest::DriverManifest;
13use crate::error::Result;
14
15/// How a driver's process was isolated when it last started (spec 3.2 §7.7).
16///
17/// # Example
18///
19/// ```rust
20/// use adk_kernel::drivers::DriverIsolation;
21///
22/// let isolation = DriverIsolation::Unsandboxed { reason: "no enforcer".into() };
23/// assert_eq!(serde_json::to_value(&isolation).unwrap()["kind"], "unsandboxed");
24/// assert!(!isolation.is_sandboxed());
25/// ```
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
28#[non_exhaustive]
29pub enum DriverIsolation {
30    /// Under the platform's OS sandbox.
31    OsSandbox {
32        /// The enforcer: `seatbelt`, `bubblewrap`.
33        enforcer: String,
34        /// The directories opened read-only for the driver's program outside the system
35        /// directories: its own, a script's interpreter's, and an ELF program's dynamic
36        /// loader's and run paths.
37        #[serde(default, skip_serializing_if = "Vec::is_empty")]
38        program_paths: Vec<std::path::PathBuf>,
39    },
40    /// On the host with the user's permissions; recorded with why.
41    Unsandboxed {
42        /// Why the process runs unsandboxed.
43        reason: String,
44    },
45}
46
47impl DriverIsolation {
48    /// Whether an enforcer confines the process.
49    pub fn is_sandboxed(&self) -> bool {
50        matches!(self, Self::OsSandbox { .. })
51    }
52}
53
54/// What holds a driver's process tree when it starts, so that ending the driver ends every
55/// process it started (spec 3.2 §7.7, §10 W1, K-I5).
56///
57/// # Example
58///
59/// ```rust
60/// use adk_kernel::drivers::DriverProcessTree;
61///
62/// assert_eq!(serde_json::to_value(DriverProcessTree::JobObject).unwrap(), "jobObject");
63/// assert_eq!(serde_json::to_value(DriverProcessTree::ProcessGroup).unwrap(), "processGroup");
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67#[non_exhaustive]
68pub enum DriverProcessTree {
69    /// A Windows Job Object that closes with the driver's connection: a stop, a restart, a
70    /// crash, or the kernel's own exit ends every process the driver started.
71    JobObject,
72    /// A Unix session and process group that the driver leads and that closes with its
73    /// connection (spec 3.2 §7.7, K-I5): a stop, a restart, a crash's cleanup, or the
74    /// kernel's shutdown ends every process of the group and returns once each has exited.
75    /// A process that leaves the group (`setsid`, `setpgid`) is not ended with it.
76    ProcessGroup,
77}
78
79impl DriverProcessTree {
80    /// What holds a driver's process tree on this platform: a Job Object on Windows, a
81    /// process group on Unix; `None` elsewhere, where ending a driver ends its own process
82    /// only.
83    pub(crate) fn platform() -> Option<Self> {
84        if cfg!(windows) {
85            Some(Self::JobObject)
86        } else if cfg!(unix) {
87            Some(Self::ProcessGroup)
88        } else {
89            None
90        }
91    }
92}
93
94/// A mounted driver: the manifest the user approved, with what the kernel recorded since
95/// (spec 3.2 §7.7, §9.3, K-I13).
96///
97/// # Example
98///
99/// ```rust
100/// use adk_kernel::drivers::{DriverManifest, DriverRecord};
101///
102/// let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n").unwrap();
103/// let record = DriverRecord::new(manifest, "alice", chrono::Utc::now());
104/// assert_eq!(record.id(), "fs");
105/// assert!(!record.needs_reapproval());
106/// ```
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108#[serde(rename_all = "camelCase")]
109#[non_exhaustive]
110pub struct DriverRecord {
111    /// The approved manifest, with each tool's pinned declaration digest.
112    pub manifest: DriverManifest,
113    /// [`DriverManifest::command_digest`] at approval.
114    pub command_digest: String,
115    /// Who approved the mount, or the last re-approval.
116    pub approved_by: String,
117    /// When.
118    pub approved_at: DateTime<Utc>,
119    /// How the process was isolated when it last started.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub isolation: Option<DriverIsolation>,
122    /// What held the process tree when it last started: a Job Object on Windows (spec 3.2
123    /// §10 W1), a process group on Unix (§7.7, K-I5); `None` before the first start.
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub process_tree: Option<DriverProcessTree>,
126    /// Tools whose declaration differs from the pin, with the digest observed.
127    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
128    pub stale: BTreeMap<String, String>,
129    /// When the record last changed.
130    pub updated_at: DateTime<Utc>,
131}
132
133impl DriverRecord {
134    /// A record of `manifest`, approved by `by` at `at`.
135    pub fn new(manifest: DriverManifest, by: impl Into<String>, at: DateTime<Utc>) -> Self {
136        Self {
137            command_digest: manifest.command_digest(),
138            manifest,
139            approved_by: by.into(),
140            approved_at: at,
141            isolation: None,
142            process_tree: None,
143            stale: BTreeMap::new(),
144            updated_at: at,
145        }
146    }
147
148    /// The driver's id.
149    pub fn id(&self) -> &str {
150        &self.manifest.id
151    }
152
153    /// Whether a tool is stale, so the driver needs re-approval (K-I14).
154    pub fn needs_reapproval(&self) -> bool {
155        !self.stale.is_empty()
156    }
157}
158
159/// A driver tool call parked on its server's input request, persisted beside the approval
160/// that asks the person: the run's checkpoint payload (spec 3.2 §7.7, §13 Q9).
161///
162/// The call is keyed by its scope and call id. On wake — a decision, or a restart — the
163/// agent dispatches the held call again and the driver re-issues `call` with the answers
164/// ([`McpServerManager::reissue_parked_call`](adk_tool::mcp::McpServerManager::reissue_parked_call)).
165///
166/// # Example
167///
168/// ```rust
169/// use adk_core::{ApprovalScope, ToolConfirmationRequest};
170/// use adk_kernel::drivers::DriverPark;
171/// use adk_tool::mcp::ParkedMcpCall;
172///
173/// let call: ParkedMcpCall = serde_json::from_value(serde_json::json!({
174///     "serverId": "email", "toolName": "send_draft", "callId": "call-1",
175///     "inputRequestsDigest": ParkedMcpCall::digest_input_requests(&Default::default()),
176///     "inputRounds": 1, "kind": "mrtr"
177/// })).unwrap();
178/// let request = ToolConfirmationRequest::new("driver:email/elicitation", serde_json::json!({}));
179/// let park = DriverPark::new(ApprovalScope::new("app", "alice", "s1"), "call-1", call, request);
180/// assert_eq!(park.driver, "email");
181/// assert_eq!(park.fingerprint, park.request.fingerprint());
182/// ```
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185#[non_exhaustive]
186pub struct DriverPark {
187    /// The driver the call was made to.
188    pub driver: String,
189    /// The session the call belongs to.
190    pub scope: ApprovalScope,
191    /// The agent's function call id.
192    pub call_id: String,
193    /// The durable run that holds the call, when one does.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub run_id: Option<String>,
196    /// The parked MCP call: tool, arguments, `requestState`, input requests and their
197    /// digest, and how it resumes.
198    pub call: ParkedMcpCall,
199    /// The held request that asks the person; its decision answers the input requests.
200    pub request: ToolConfirmationRequest,
201    /// `request.fingerprint()`, the key of its decision and of the run's wait.
202    pub fingerprint: String,
203    /// When the call parked.
204    pub created_at: DateTime<Utc>,
205    /// When the question lapses, if it does.
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub expires_at: Option<DateTime<Utc>>,
208    /// Whether a person approved the call itself before the server asked, so the approval
209    /// is carried to the call that resumes, once, until the question lapses.
210    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
211    pub carries_approval: bool,
212}
213
214impl DriverPark {
215    /// The park of `call`, held for `request`, as the agent's call `call_id` in `scope`.
216    pub fn new(
217        scope: ApprovalScope,
218        call_id: impl Into<String>,
219        call: ParkedMcpCall,
220        request: ToolConfirmationRequest,
221    ) -> Self {
222        Self {
223            driver: call.server_id.clone(),
224            scope,
225            call_id: call_id.into(),
226            run_id: None,
227            fingerprint: request.fingerprint(),
228            call,
229            request,
230            created_at: Utc::now(),
231            expires_at: None,
232            carries_approval: false,
233        }
234    }
235
236    /// Sets the durable run holding the call.
237    #[must_use]
238    pub fn with_run_id(mut self, run_id: impl Into<String>) -> Self {
239        self.run_id = Some(run_id.into());
240        self
241    }
242
243    /// Sets when the question lapses.
244    #[must_use]
245    pub fn with_expires_at(mut self, at: DateTime<Utc>) -> Self {
246        self.expires_at = Some(at);
247        self
248    }
249}
250
251/// The kernel's store of mounted drivers and parked driver calls (spec 3.2 §7.7, §13 Q8).
252///
253/// Runs on every backend that holds the run, schedule and governance stores, with one
254/// conformance suite (`driver_store_conformance_tests!`, feature `conformance`):
255///
256/// | Backend | Type | Feature |
257/// |---|---|---|
258/// | In-memory | [`InMemoryDriverStore`](crate::stores::InMemoryDriverStore) | `drivers` |
259/// | SQLite | `SqliteDriverStore` | `drivers`, `sqlite` |
260/// | PostgreSQL | `PostgresDriverStore` | `drivers`, `postgres` |
261/// | Redis | `RedisDriverStore` | `drivers`, `redis` |
262///
263/// # Example
264///
265/// ```rust
266/// use adk_kernel::drivers::{DriverManifest, DriverRecord, DriverStore};
267/// use adk_kernel::stores::InMemoryDriverStore;
268///
269/// # #[tokio::main(flavor = "current_thread")]
270/// # async fn main() -> adk_kernel::Result<()> {
271/// let store = InMemoryDriverStore::new();
272/// let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n")?;
273/// store.put(DriverRecord::new(manifest, "alice", chrono::Utc::now())).await?;
274/// assert_eq!(store.get("fs").await?.unwrap().approved_by, "alice");
275/// # Ok(())
276/// # }
277/// ```
278#[async_trait]
279pub trait DriverStore: Send + Sync {
280    /// Inserts `record`, or replaces the record of the same driver.
281    ///
282    /// # Errors
283    ///
284    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
285    async fn put(&self, record: DriverRecord) -> Result<()>;
286
287    /// The record of driver `id`, or `None`.
288    ///
289    /// # Errors
290    ///
291    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
292    async fn get(&self, id: &str) -> Result<Option<DriverRecord>>;
293
294    /// Every record, ordered by driver id.
295    ///
296    /// # Errors
297    ///
298    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
299    async fn list(&self) -> Result<Vec<DriverRecord>>;
300
301    /// Deletes the record of driver `id`; `false` when there was none. Its parked calls
302    /// stay until [`delete_park`](Self::delete_park) removes them.
303    ///
304    /// # Errors
305    ///
306    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
307    async fn delete(&self, id: &str) -> Result<bool>;
308
309    /// Inserts `park`, or replaces the park of the same scope and call id.
310    ///
311    /// # Errors
312    ///
313    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
314    async fn put_park(&self, park: DriverPark) -> Result<()>;
315
316    /// The park of call `call_id` in `scope`, or `None`.
317    ///
318    /// # Errors
319    ///
320    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
321    async fn get_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<Option<DriverPark>>;
322
323    /// The parks of `driver`, or of every driver, ordered by scope and call id.
324    ///
325    /// # Errors
326    ///
327    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
328    async fn list_parks(&self, driver: Option<&str>) -> Result<Vec<DriverPark>>;
329
330    /// Deletes the park of call `call_id` in `scope`; `false` when there was none.
331    ///
332    /// # Errors
333    ///
334    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
335    async fn delete_park(&self, scope: &ApprovalScope, call_id: &str) -> Result<bool>;
336}
337
338/// The order parks list in: scope, then call id.
339pub(crate) fn park_key(scope: &ApprovalScope, call_id: &str) -> (String, String, String, String) {
340    (scope.app_name.clone(), scope.user_id.clone(), scope.session_id.clone(), call_id.to_string())
341}