Skip to main content

adk_drivers/
class.rs

1//! Driver classes: the tools each class of driver offers, their effect classes, their
2//! partitions and their default autonomy caps, as kernel driver manifests (spec 3.5 §7.13,
3//! §7.10; spec 3.2 §7.7).
4
5use std::collections::BTreeSet;
6use std::fmt;
7
8use adk_kernel::KernelError;
9use adk_kernel::drivers::{DriverManifest, EffectClass};
10use adk_kernel::partition::PartitionId;
11use adk_tool::mcp::manager::McpServerConfig;
12use awp_types::AutonomyLevel;
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16/// The partition of a website's public agents (spec 3.5 §7.10): Concierge, Agent desk,
17/// Inbox.
18pub const PUBLIC_PARTITION: &str = "public";
19
20/// The partition of a website's back office (spec 3.5 §7.10): Steward, Growth, Revenue,
21/// Guardian, Finance.
22pub const BACK_OFFICE_PARTITION: &str = "back-office";
23
24/// Which of a website's two partitions a driver tool serves (spec 3.5 §7.10).
25///
26/// Untrusted text — an inbound email, a mention — is read in the public partition only;
27/// the back office never reads it raw (A-I3), so a tool that reads such text is
28/// [`Public`](Self::Public) and every tool that publishes, changes DNS, spends or sends in
29/// bulk is [`BackOffice`](Self::BackOffice) (A-I2).
30///
31/// # Example
32///
33/// ```rust
34/// use adk_drivers::Side;
35///
36/// assert_eq!(Side::Public.partition().as_str(), "public");
37/// assert_eq!(Side::BackOffice.partition().as_str(), "back-office");
38/// ```
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
40#[serde(rename_all = "camelCase")]
41#[non_exhaustive]
42pub enum Side {
43    /// The public partition: reads untrusted input and replies in its thread.
44    Public,
45    /// The back-office partition: everything else.
46    BackOffice,
47}
48
49impl Side {
50    /// The partition this side runs in by default.
51    pub fn partition(self) -> PartitionId {
52        PartitionId::new(match self {
53            Self::Public => PUBLIC_PARTITION,
54            Self::BackOffice => BACK_OFFICE_PARTITION,
55        })
56    }
57
58    /// The side's name: `public` or `backOffice`.
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Self::Public => "public",
62            Self::BackOffice => "backOffice",
63        }
64    }
65}
66
67/// How far a job goes with a tool before a person decides, by default (spec 3.5 §7.13,
68/// "Default autonomy cap"; §7.11 autonomy ladder).
69///
70/// The cap is the level a job using the tool starts at and is offered promotion from;
71/// promotion is an owner's decision (A-I13). [`AlwaysHeld`](Self::AlwaysHeld) is an
72/// invariant, not a level: no mode, standing rule or promotion lifts it (A-I21), and
73/// [`DriverCapPolicy`](crate::DriverCapPolicy) enforces it on every call.
74///
75/// # Example
76///
77/// ```rust
78/// use adk_drivers::AutonomyCap;
79///
80/// assert!(AutonomyCap::AlwaysHeld.is_invariant());
81/// assert!(!AutonomyCap::Propose.is_invariant());
82/// ```
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase")]
85#[non_exhaustive]
86pub enum AutonomyCap {
87    /// Reads only.
88    Read,
89    /// The job proposes; a person decides each call.
90    Propose,
91    /// Within the job's playbook and the recipient's consent.
92    WithinPlaybook,
93    /// Within the owner's budget; a call beyond it is held.
94    WithinBudget,
95    /// Held for a person in every mode (A-I21).
96    AlwaysHeld,
97}
98
99impl AutonomyCap {
100    /// Whether the cap holds in every mode, whatever the job's level.
101    pub fn is_invariant(self) -> bool {
102        matches!(self, Self::AlwaysHeld)
103    }
104
105    /// The autonomy level a job using the tool starts at (spec 3.5 §7.11, §7.20): Observe
106    /// for reads, Propose, "act within budget" for the playbook and budget caps, and "act
107    /// with approval" for a held tool — whose calls [`DriverCapPolicy`](crate::DriverCapPolicy)
108    /// holds on every rung.
109    ///
110    /// # Example
111    ///
112    /// ```rust
113    /// use adk_drivers::AutonomyCap;
114    /// use awp_types::AutonomyLevel;
115    ///
116    /// assert_eq!(AutonomyCap::Propose.starting_level(), AutonomyLevel::Propose);
117    /// assert_eq!(AutonomyCap::AlwaysHeld.starting_level(), AutonomyLevel::ActWithApproval);
118    /// ```
119    pub fn starting_level(self) -> AutonomyLevel {
120        match self {
121            Self::Read => AutonomyLevel::Observe,
122            Self::Propose => AutonomyLevel::Propose,
123            Self::WithinPlaybook | Self::WithinBudget => AutonomyLevel::ActWithinBudget,
124            Self::AlwaysHeld => AutonomyLevel::ActWithApproval,
125        }
126    }
127}
128
129/// One tool of a driver class (spec 3.5 §7.13): its name, effect class, side and default
130/// autonomy cap, and the JSON Schema of its arguments.
131///
132/// The same name and schema serve an in-process adapter's toolset and any MCP server that
133/// satisfies the class's manifest, so an agent's playbook does not depend on which one
134/// the owner connected.
135#[derive(Debug, Clone, Copy)]
136#[non_exhaustive]
137pub struct ToolSpec {
138    /// The tool's name, prefixed by its class.
139    pub name: &'static str,
140    /// What the tool does, as the model reads it.
141    pub description: &'static str,
142    /// The effect class its manifest declares (spec 3.2 §7.7).
143    pub class: EffectClass,
144    /// A further effect the call has, such as a campaign launch that both spends and
145    /// publishes; the manifest declares [`class`](Self::class), the stricter.
146    pub also: Option<EffectClass>,
147    /// The partition side it serves.
148    pub side: Side,
149    /// Its default autonomy cap.
150    pub cap: AutonomyCap,
151    /// The JSON pointer of the amount argument a [`AutonomyCap::WithinBudget`] call is
152    /// measured by, in minor units; `None` for a call that never adds spend.
153    pub budget_arg: Option<&'static str>,
154    /// The JSON Schema of its arguments.
155    pub schema: fn() -> Value,
156}
157
158impl ToolSpec {
159    /// The names of the arguments its schema requires.
160    pub fn required_args(&self) -> Vec<String> {
161        required_of(&(self.schema)())
162    }
163}
164
165fn required_of(schema: &Value) -> Vec<String> {
166    schema
167        .get("required")
168        .and_then(Value::as_array)
169        .map(|required| required.iter().filter_map(Value::as_str).map(str::to_string).collect())
170        .unwrap_or_default()
171}
172
173/// A class of driver (spec 3.5 §7.13).
174///
175/// # Example
176///
177/// ```rust
178/// use adk_drivers::DriverKind;
179///
180/// assert_eq!(DriverKind::Dns.as_str(), "dns");
181/// assert_eq!(DriverKind::ALL.len(), 7);
182/// ```
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
184#[serde(rename_all = "camelCase")]
185#[non_exhaustive]
186pub enum DriverKind {
187    /// DNS records.
188    Dns,
189    /// Domain registration: expiry and renewal.
190    Registrar,
191    /// Email: inbox, replies, sequences and newsletters, delivery statistics.
192    Email,
193    /// Site analytics.
194    Analytics,
195    /// Search performance.
196    SearchConsole,
197    /// Social: mentions, messages, replies and posts.
198    Social,
199    /// Advertising: spend and performance, campaigns, bids and pauses.
200    Advertising,
201}
202
203impl DriverKind {
204    /// Every class, in the order of spec 3.5 §7.13's table.
205    pub const ALL: [DriverKind; 7] = [
206        Self::Dns,
207        Self::Registrar,
208        Self::Email,
209        Self::Analytics,
210        Self::SearchConsole,
211        Self::Social,
212        Self::Advertising,
213    ];
214
215    /// The class's name, which prefixes its tools.
216    pub fn as_str(self) -> &'static str {
217        match self {
218            Self::Dns => "dns",
219            Self::Registrar => "registrar",
220            Self::Email => "email",
221            Self::Analytics => "analytics",
222            Self::SearchConsole => "search_console",
223            Self::Social => "social",
224            Self::Advertising => "ads",
225        }
226    }
227
228    /// The class's tools.
229    pub fn class(self) -> DriverClass {
230        let tools: &'static [ToolSpec] = match self {
231            Self::Dns => crate::dns::DNS_TOOLS,
232            Self::Registrar => crate::dns::REGISTRAR_TOOLS,
233            Self::Email => crate::email::EMAIL_TOOLS,
234            Self::Analytics => crate::analytics::ANALYTICS_TOOLS,
235            Self::SearchConsole => crate::analytics::SEARCH_CONSOLE_TOOLS,
236            Self::Social => crate::social::SOCIAL_TOOLS,
237            Self::Advertising => crate::ads::ADS_TOOLS,
238        };
239        DriverClass { kind: self, tools }
240    }
241}
242
243impl fmt::Display for DriverKind {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        f.write_str(self.as_str())
246    }
247}
248
249/// The spec of every driver tool of every class.
250pub fn all_tools() -> impl Iterator<Item = &'static ToolSpec> {
251    DriverKind::ALL.into_iter().flat_map(|kind| kind.class().tools.iter())
252}
253
254/// The spec of the driver tool named `name`, of any class.
255pub fn tool_spec(name: &str) -> Option<&'static ToolSpec> {
256    all_tools().find(|spec| spec.name == name)
257}
258
259/// A class of driver and its tools (spec 3.5 §7.13), as kernel driver manifests.
260///
261/// A driver is a kernel driver — a supervised MCP server under a manifest the owner
262/// approved — or an in-process adapter with the same tools. A class's manifest lists its
263/// tools with their effect classes for one side; [`check_manifest`](Self::check_manifest)
264/// and [`check_listing`](Self::check_listing) tell whether any MCP server and its manifest
265/// satisfy the class, so the owner may connect whichever server they choose (D-13).
266///
267/// # Example
268///
269/// ```rust
270/// use adk_drivers::{DriverKind, Side};
271/// use adk_kernel::drivers::{DriverManifest, EffectClass};
272///
273/// let dns = DriverKind::Dns.class();
274/// let text = dns.manifest_toml("dns", "mcp-dns", &[], Side::BackOffice);
275/// let manifest = DriverManifest::from_toml(&text).unwrap();
276/// assert_eq!(manifest.class_of("dns_change_records"), EffectClass::PublishPublic);
277/// assert!(dns.check_manifest(&manifest, Side::BackOffice).is_satisfied());
278/// ```
279#[derive(Debug, Clone, Copy)]
280#[non_exhaustive]
281pub struct DriverClass {
282    /// Which class.
283    pub kind: DriverKind,
284    /// Its tools, on both sides.
285    pub tools: &'static [ToolSpec],
286}
287
288impl DriverClass {
289    /// The tool named `name`.
290    pub fn tool(&self, name: &str) -> Option<&'static ToolSpec> {
291        self.tools.iter().find(|spec| spec.name == name)
292    }
293
294    /// The tools that serve `side`.
295    pub fn tools_for(&self, side: Side) -> impl Iterator<Item = &'static ToolSpec> + use<> {
296        self.tools.iter().filter(move |spec| spec.side == side)
297    }
298
299    /// Whether the class has a tool on `side`.
300    pub fn serves(&self, side: Side) -> bool {
301        self.tools_for(side).next().is_some()
302    }
303
304    /// The kernel manifest of driver `id` running `server` for `side`: the side's tools with
305    /// their effect classes, serving the side's partition.
306    ///
307    /// # Errors
308    ///
309    /// Returns [`KernelError::Config`] when `id` or the server is not a valid driver (see
310    /// [`DriverManifest::new`]), or the class has no tool on `side`.
311    pub fn manifest(
312        &self,
313        id: &str,
314        server: McpServerConfig,
315        side: Side,
316    ) -> std::result::Result<DriverManifest, KernelError> {
317        if !self.serves(side) {
318            return Err(KernelError::Config {
319                reason: format!("the {} driver class has no {} tool", self.kind, side.as_str()),
320            });
321        }
322        let mut manifest = DriverManifest::new(id, server)?.with_partitions([side.partition()]);
323        for spec in self.tools_for(side) {
324            manifest = manifest.with_tool(spec.name, spec.class);
325        }
326        Ok(manifest)
327    }
328
329    /// The TOML manifest of driver `id` running `command` with `args` for `side`, as the
330    /// owner reviews and mounts it (`adk-rust drivers mount <file>`).
331    pub fn manifest_toml(&self, id: &str, command: &str, args: &[&str], side: Side) -> String {
332        let quoted = |text: &str| serde_json::to_string(text).unwrap_or_default();
333        let mut out = format!(
334            "# The {} driver's {} tools (spec 3.5 §7.13).\nid = {}\ncommand = {}\n",
335            self.kind,
336            side.as_str(),
337            quoted(id),
338            quoted(command)
339        );
340        if !args.is_empty() {
341            let args: Vec<String> = args.iter().map(|arg| quoted(arg)).collect();
342            out.push_str(&format!("args = [{}]\n", args.join(", ")));
343        }
344        out.push_str(&format!("partitions = [{}]\n\n[tools]\n", quoted(side.partition().as_str())));
345        for spec in self.tools_for(side) {
346            out.push_str(&format!("{} = {}\n", spec.name, quoted(spec.class.as_str())));
347        }
348        out
349    }
350
351    /// What keeps `manifest` from satisfying the class on `side`: a tool it does not list,
352    /// a tool it classes less strictly than the contract, a tool of the other side, or a
353    /// partition other than the side's.
354    pub fn check_manifest(&self, manifest: &DriverManifest, side: Side) -> ManifestCheck {
355        let mut gaps = Vec::new();
356        let partition = side.partition();
357        for listed in &manifest.partitions {
358            if *listed != partition {
359                gaps.push(Gap::WrongPartition { partition: listed.to_string() });
360            }
361        }
362        for spec in self.tools_for(side) {
363            match manifest.tools.get(spec.name) {
364                None => gaps.push(Gap::MissingTool { tool: spec.name.to_string() }),
365                Some(class) if !at_least_as_strict(*class, spec.class) => {
366                    gaps.push(Gap::WeakerClass {
367                        tool: spec.name.to_string(),
368                        contract: spec.class,
369                        manifest: *class,
370                    });
371                }
372                Some(_) => {}
373            }
374        }
375        for tool in manifest.tools.keys() {
376            if self.tool(tool).is_some_and(|spec| spec.side != side) {
377                gaps.push(Gap::ForeignTool { tool: tool.clone() });
378            }
379        }
380        ManifestCheck { gaps }
381    }
382
383    /// What keeps an MCP server's tool listing from satisfying the class on `side`: a tool
384    /// it does not offer, an argument the contract requires that its schema lacks, or a
385    /// tool beyond the side's contract — which the kernel would serve to the partition as
386    /// `other`, so the server must not offer it there.
387    ///
388    /// `listed` holds each tool's name and input schema, as the server lists them.
389    pub fn check_listing(&self, side: Side, listed: &[(String, Value)]) -> ManifestCheck {
390        let mut gaps = Vec::new();
391        for spec in self.tools_for(side) {
392            let Some((_, schema)) = listed.iter().find(|(name, _)| name == spec.name) else {
393                gaps.push(Gap::MissingTool { tool: spec.name.to_string() });
394                continue;
395            };
396            let offered: BTreeSet<&str> = schema
397                .get("properties")
398                .and_then(Value::as_object)
399                .map(|properties| properties.keys().map(String::as_str).collect())
400                .unwrap_or_default();
401            for argument in spec.required_args() {
402                if !offered.contains(argument.as_str()) {
403                    gaps.push(Gap::MissingArgument { tool: spec.name.to_string(), argument });
404                }
405            }
406        }
407        for (name, _) in listed {
408            if !self.tools_for(side).any(|spec| spec.name == name) {
409                gaps.push(Gap::ForeignTool { tool: name.clone() });
410            }
411        }
412        ManifestCheck { gaps }
413    }
414}
415
416/// Whether a manifest's `declared` class is the contract's or stricter than it.
417fn at_least_as_strict(declared: EffectClass, contract: EffectClass) -> bool {
418    declared == contract || declared.strictness() > contract.strictness()
419}
420
421/// What keeps a manifest or a server's listing from satisfying a driver class (spec 3.5
422/// §7.13).
423#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
425#[non_exhaustive]
426pub enum Gap {
427    /// A tool of the contract is not there.
428    MissingTool {
429        /// The tool.
430        tool: String,
431    },
432    /// The manifest classes a tool less strictly than the contract.
433    WeakerClass {
434        /// The tool.
435        tool: String,
436        /// The contract's class.
437        contract: EffectClass,
438        /// The manifest's class.
439        manifest: EffectClass,
440    },
441    /// A tool that does not belong on this side.
442    ForeignTool {
443        /// The tool.
444        tool: String,
445    },
446    /// The manifest serves a partition other than the side's.
447    WrongPartition {
448        /// The partition.
449        partition: String,
450    },
451    /// The server's schema for a tool lacks an argument the contract requires.
452    MissingArgument {
453        /// The tool.
454        tool: String,
455        /// The argument.
456        argument: String,
457    },
458}
459
460impl fmt::Display for Gap {
461    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462        match self {
463            Self::MissingTool { tool } => write!(f, "`{tool}` is missing"),
464            Self::WeakerClass { tool, contract, manifest } => {
465                write!(f, "`{tool}` is classed `{manifest}`; the contract needs `{contract}`")
466            }
467            Self::ForeignTool { tool } => write!(f, "`{tool}` does not belong on this side"),
468            Self::WrongPartition { partition } => {
469                write!(f, "the manifest serves partition `{partition}`")
470            }
471            Self::MissingArgument { tool, argument } => {
472                write!(f, "`{tool}` takes no `{argument}` argument")
473            }
474        }
475    }
476}
477
478/// The result of checking a manifest or a listing against a driver class.
479#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
480#[serde(rename_all = "camelCase")]
481#[non_exhaustive]
482pub struct ManifestCheck {
483    /// Every gap found.
484    pub gaps: Vec<Gap>,
485}
486
487impl ManifestCheck {
488    /// Whether nothing keeps it from satisfying the class.
489    pub fn is_satisfied(&self) -> bool {
490        self.gaps.is_empty()
491    }
492}
493
494impl fmt::Display for ManifestCheck {
495    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496        if self.gaps.is_empty() {
497            return f.write_str("satisfies the driver class");
498        }
499        let gaps: Vec<String> = self.gaps.iter().map(ToString::to_string).collect();
500        f.write_str(&gaps.join("; "))
501    }
502}