adk_kernel/drivers.rs
1//! Drivers: MCP servers run as supervised child processes under a manifest the user
2//! approved (spec 3.2 §7.7).
3//!
4//! | Item | Spec |
5//! |---|---|
6//! | [`EffectClass`], [`DriverState`] | §7.7, §7.6 |
7// The items of these rows exist only with the `drivers` feature, so they link only with it.
8#![cfg_attr(
9 feature = "drivers",
10 doc = r#"| [`DriverManifest`], [`DriverSandbox`], [`DriverLifecycle`], [`DriverAccess`], [`load_manifests`] (feature `drivers`) | §7.7 |
11| [`DriverStore`], [`DriverRecord`], [`DriverPark`], [`DriverIsolation`] (feature `drivers`) | §7.7, §9.3, §13 Q8, Q9 |
12| [`DriverProcessTree`] (feature `drivers`) | §7.7, §10 W1, K-I5 |
13| [`DriverSupervisor`], [`DriverSupervisorBuilder`], [`DriverProposal`], [`DriverView`], [`StandingRulePins`] (feature `drivers`) | §7.7, K-I13, K-I14 |
14| [`DriverPolicy`] (feature `drivers`) | §7.7, K-I9, K-I14 |"#
15)]
16#![cfg_attr(
17 not(feature = "drivers"),
18 doc = r#"| `DriverManifest`, `DriverSandbox`, `DriverLifecycle`, `DriverAccess`, `load_manifests` (feature `drivers`) | §7.7 |
19| `DriverStore`, `DriverRecord`, `DriverPark`, `DriverIsolation` (feature `drivers`) | §7.7, §9.3, §13 Q8, Q9 |
20| `DriverProcessTree` (feature `drivers`) | §7.7, §10 W1, K-I5 |
21| `DriverSupervisor`, `DriverSupervisorBuilder`, `DriverProposal`, `DriverView`, `StandingRulePins` (feature `drivers`) | §7.7, K-I13, K-I14 |
22| `DriverPolicy` (feature `drivers`) | §7.7, K-I9, K-I14 |"#
23)]
24//!
25//! A driver's lifecycle:
26//!
27//! 1. **Mount.** `DriverSupervisor::propose` shows what the person approves — the command
28//! line, the partitions, the effect classes, the sandbox and the secrets it names — and
29//! `DriverSupervisor::mount` records the approval (`kernel.driver.mounted`). Nothing runs
30//! before it (K-I13).
31//! 2. **Start.** Lazily when a partition's agent lists the driver's tools, or at mount for
32//! `lifecycle = "eager"`. The stdio launcher runs the server under the OS sandbox where an
33//! enforcer exists and records `Unsandboxed { reason }` otherwise, with an environment
34//! cleared to an allowlist and each `secret://` reference minted by the credential broker
35//! into a file only the user can read. On Windows the server runs in a Job Object of its
36//! own, so ending the driver ends every process it started (spec 3.2 §10 W1). The first
37//! listing after approval pins each tool's declaration digest.
38//! 3. **Supervise.** The MCP manager's status channel (spec 3.2 §10 T1) becomes
39//! [`KernelEvent::Driver`](crate::KernelEvent::Driver) events and `kernel.driver.*`
40//! records; a crash restarts with the manifest's backoff.
41//! 4. **Stale.** A tool whose declaration differs from its pin is stale: the harness's
42//! standing rules pinned to the old declaration stop matching, `DriverPolicy` asks
43//! before every call of it, and the driver is `NeedsReapproval` (K-I14) until
44//! `DriverSupervisor::reapprove` pins the new declarations and carries the re-approving
45//! person's rules forward.
46//! 5. **Park.** A call the server answers with a question ends as a held call: the
47//! `DriverPark` is stored beside the approval as the run's checkpoint, the run parks,
48//! and the decision — after any restart — dispatches the call again, which re-issues it
49//! with the answers (spec 3.2 §13 Q9).
50
51use std::fmt;
52use std::str::FromStr;
53
54use adk_core::ToolEffect;
55use serde::{Deserialize, Serialize};
56
57use crate::error::{KernelError, Result};
58
59#[cfg(feature = "drivers")]
60mod launch;
61#[cfg(feature = "drivers")]
62mod manifest;
63#[cfg(feature = "drivers")]
64mod policy;
65#[cfg(feature = "drivers")]
66pub(crate) mod store;
67#[cfg(feature = "drivers")]
68mod supervisor;
69#[cfg(feature = "drivers")]
70mod tool;
71
72#[cfg(feature = "drivers")]
73pub use manifest::{
74 DriverAccess, DriverLifecycle, DriverManifest, DriverSandbox, SECRET_SCHEME, load_dir,
75 load_manifests,
76};
77#[cfg(feature = "drivers")]
78pub use policy::DriverPolicy;
79#[cfg(feature = "drivers")]
80pub use store::{DriverIsolation, DriverPark, DriverProcessTree, DriverRecord, DriverStore};
81#[cfg(feature = "drivers")]
82pub(crate) use supervisor::not_mounted;
83#[cfg(feature = "drivers")]
84pub use supervisor::{
85 DriverProposal, DriverSupervisor, DriverSupervisorBuilder, DriverView, StandingRulePins,
86};
87
88/// The `ToolOrigin::source` of every tool driver `id` serves: `driver:<id>` (spec 3.2 §7.7).
89///
90/// A driver's tools report their own source rather than the `mcp:<server>` of an MCP
91/// server the harness starts, so a manifest's classes apply only to the tools the kernel
92/// supervises.
93///
94/// # Example
95///
96/// ```rust
97/// assert_eq!(adk_kernel::drivers::driver_source("email"), "driver:email");
98/// assert_eq!(adk_kernel::drivers::driver_of("driver:email"), Some("email"));
99/// assert_eq!(adk_kernel::drivers::driver_of("mcp:email"), None);
100/// ```
101pub fn driver_source(id: &str) -> String {
102 format!("{DRIVER_SOURCE_PREFIX}{id}")
103}
104
105/// The driver a `ToolOrigin::source` names, if it is a driver's.
106pub fn driver_of(source: &str) -> Option<&str> {
107 source.strip_prefix(DRIVER_SOURCE_PREFIX).filter(|id| !id.is_empty())
108}
109
110/// The prefix of [`driver_source`].
111pub const DRIVER_SOURCE_PREFIX: &str = "driver:";
112
113/// What a driver tool does to the world, as its manifest declares it (spec 3.2 §7.7).
114///
115/// The manifest's class is the source of truth for the harness policy: a server's own
116/// `readOnlyHint` never grants anything (spec 3.1 I12). A tool the manifest does not list
117/// is [`Other`](Self::Other). [`PublishPublic`](Self::PublishPublic) and
118/// [`Financial`](Self::Financial) are never auto-allowed on any path (K-I9).
119///
120/// # Example
121///
122/// ```rust
123/// use adk_kernel::drivers::EffectClass;
124///
125/// let class: EffectClass = "send_external".parse().unwrap();
126/// assert_eq!(class, EffectClass::SendExternal);
127/// assert_eq!(class.to_string(), "send_external");
128/// assert!(EffectClass::Financial.is_never_auto_allowed());
129/// assert_eq!(EffectClass::Read.tool_effect(), adk_core::ToolEffect::ReadOnly);
130/// ```
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133#[non_exhaustive]
134pub enum EffectClass {
135 /// Reads without changing anything.
136 Read,
137 /// Changes the user's own data on the host or in the service, such as a draft.
138 WriteLocal,
139 /// Schedules something that involves other people, such as a meeting.
140 ScheduleWithOthers,
141 /// Sends something to someone outside, such as an email.
142 SendExternal,
143 /// Publishes something anyone can see.
144 PublishPublic,
145 /// Moves money.
146 Financial,
147 /// Deletes something.
148 Delete,
149 /// Anything else, and every tool the manifest does not list.
150 Other,
151}
152
153impl EffectClass {
154 /// Every class, in declaration order.
155 pub const ALL: [EffectClass; 8] = [
156 Self::Read,
157 Self::WriteLocal,
158 Self::ScheduleWithOthers,
159 Self::SendExternal,
160 Self::PublishPublic,
161 Self::Financial,
162 Self::Delete,
163 Self::Other,
164 ];
165
166 /// The class's name as a manifest writes it.
167 pub fn as_str(self) -> &'static str {
168 match self {
169 Self::Read => "read",
170 Self::WriteLocal => "write_local",
171 Self::ScheduleWithOthers => "schedule_with_others",
172 Self::SendExternal => "send_external",
173 Self::PublishPublic => "publish_public",
174 Self::Financial => "financial",
175 Self::Delete => "delete",
176 Self::Other => "other",
177 }
178 }
179
180 /// The [`ToolEffect`] a driver tool of this class reports: `ReadOnly` for
181 /// [`Read`](Self::Read), `NonIdempotent` for every other class, so a call that changes
182 /// something is never retried and is recorded in the action ledger.
183 pub fn tool_effect(self) -> ToolEffect {
184 match self {
185 Self::Read => ToolEffect::ReadOnly,
186 _ => ToolEffect::NonIdempotent,
187 }
188 }
189
190 /// Whether no mode, standing rule or run-wide approval may allow a call of this class
191 /// without a person deciding it (spec 3.2 K-I9).
192 pub fn is_never_auto_allowed(self) -> bool {
193 matches!(self, Self::PublishPublic | Self::Financial)
194 }
195
196 /// How strictly the harness treats the class: 0 for reads, 1 for changes a standing
197 /// rule may allow, 2 for the classes never auto-allowed. A project manifest may only
198 /// keep or raise a tool's strictness.
199 pub fn strictness(self) -> u8 {
200 match self {
201 Self::Read => 0,
202 Self::PublishPublic | Self::Financial => 2,
203 _ => 1,
204 }
205 }
206}
207
208impl fmt::Display for EffectClass {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.write_str(self.as_str())
211 }
212}
213
214impl FromStr for EffectClass {
215 type Err = KernelError;
216
217 fn from_str(text: &str) -> Result<Self> {
218 let normalized = text.trim().to_ascii_lowercase().replace('-', "_");
219 Self::ALL.into_iter().find(|class| class.as_str() == normalized).ok_or_else(|| {
220 KernelError::Config {
221 reason: format!(
222 "unknown effect class `{text}`; use one of {}",
223 Self::ALL.map(Self::as_str).join(", ")
224 ),
225 }
226 })
227 }
228}
229
230/// A driver's state on the event bus (spec 3.2 §7.6): its MCP server's status, or
231/// [`NeedsReapproval`](Self::NeedsReapproval) once a tool's declaration differs from the
232/// one pinned at approval.
233///
234/// # Example
235///
236/// ```rust
237/// use adk_kernel::drivers::DriverState;
238///
239/// assert_eq!(serde_json::to_value(DriverState::NeedsReapproval).unwrap(), "needsReapproval");
240/// assert_eq!(DriverState::FailedToStart.as_str(), "failedToStart");
241/// ```
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244#[non_exhaustive]
245pub enum DriverState {
246 /// The process is starting and its MCP handshake runs.
247 Starting,
248 /// The server runs and serves its tools.
249 Running,
250 /// The server is stopped.
251 Stopped,
252 /// The process exited or its connection closed unexpectedly.
253 Crashed,
254 /// The supervisor is restarting the server.
255 Restarting,
256 /// The server is disabled.
257 Disabled,
258 /// The server failed to start; after the restart policy's attempts, the exhausted state.
259 FailedToStart,
260 /// A tool's declaration differs from the pinned one; its standing rules no longer match
261 /// and its calls need approval until the driver is re-approved (K-I14).
262 NeedsReapproval,
263}
264
265#[cfg(feature = "drivers")]
266impl From<adk_tool::mcp::ServerStatus> for DriverState {
267 fn from(status: adk_tool::mcp::ServerStatus) -> Self {
268 use adk_tool::mcp::ServerStatus;
269 match status {
270 ServerStatus::Starting => Self::Starting,
271 ServerStatus::Running => Self::Running,
272 ServerStatus::Stopped => Self::Stopped,
273 ServerStatus::Crashed => Self::Crashed,
274 ServerStatus::Restarting => Self::Restarting,
275 ServerStatus::Disabled => Self::Disabled,
276 ServerStatus::FailedToStart => Self::FailedToStart,
277 }
278 }
279}
280
281impl DriverState {
282 /// The state's name, as it serializes.
283 pub fn as_str(self) -> &'static str {
284 match self {
285 Self::Starting => "starting",
286 Self::Running => "running",
287 Self::Stopped => "stopped",
288 Self::Crashed => "crashed",
289 Self::Restarting => "restarting",
290 Self::Disabled => "disabled",
291 Self::FailedToStart => "failedToStart",
292 Self::NeedsReapproval => "needsReapproval",
293 }
294 }
295}