use std::collections::BTreeSet;
use std::fmt;
use adk_kernel::KernelError;
use adk_kernel::drivers::{DriverManifest, EffectClass};
use adk_kernel::partition::PartitionId;
use adk_tool::mcp::manager::McpServerConfig;
use awp_types::AutonomyLevel;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const PUBLIC_PARTITION: &str = "public";
pub const BACK_OFFICE_PARTITION: &str = "back-office";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Side {
Public,
BackOffice,
}
impl Side {
pub fn partition(self) -> PartitionId {
PartitionId::new(match self {
Self::Public => PUBLIC_PARTITION,
Self::BackOffice => BACK_OFFICE_PARTITION,
})
}
pub fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::BackOffice => "backOffice",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum AutonomyCap {
Read,
Propose,
WithinPlaybook,
WithinBudget,
AlwaysHeld,
}
impl AutonomyCap {
pub fn is_invariant(self) -> bool {
matches!(self, Self::AlwaysHeld)
}
pub fn starting_level(self) -> AutonomyLevel {
match self {
Self::Read => AutonomyLevel::Observe,
Self::Propose => AutonomyLevel::Propose,
Self::WithinPlaybook | Self::WithinBudget => AutonomyLevel::ActWithinBudget,
Self::AlwaysHeld => AutonomyLevel::ActWithApproval,
}
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ToolSpec {
pub name: &'static str,
pub description: &'static str,
pub class: EffectClass,
pub also: Option<EffectClass>,
pub side: Side,
pub cap: AutonomyCap,
pub budget_arg: Option<&'static str>,
pub schema: fn() -> Value,
}
impl ToolSpec {
pub fn required_args(&self) -> Vec<String> {
required_of(&(self.schema)())
}
}
fn required_of(schema: &Value) -> Vec<String> {
schema
.get("required")
.and_then(Value::as_array)
.map(|required| required.iter().filter_map(Value::as_str).map(str::to_string).collect())
.unwrap_or_default()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum DriverKind {
Dns,
Registrar,
Email,
Analytics,
SearchConsole,
Social,
Advertising,
}
impl DriverKind {
pub const ALL: [DriverKind; 7] = [
Self::Dns,
Self::Registrar,
Self::Email,
Self::Analytics,
Self::SearchConsole,
Self::Social,
Self::Advertising,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Dns => "dns",
Self::Registrar => "registrar",
Self::Email => "email",
Self::Analytics => "analytics",
Self::SearchConsole => "search_console",
Self::Social => "social",
Self::Advertising => "ads",
}
}
pub fn class(self) -> DriverClass {
let tools: &'static [ToolSpec] = match self {
Self::Dns => crate::dns::DNS_TOOLS,
Self::Registrar => crate::dns::REGISTRAR_TOOLS,
Self::Email => crate::email::EMAIL_TOOLS,
Self::Analytics => crate::analytics::ANALYTICS_TOOLS,
Self::SearchConsole => crate::analytics::SEARCH_CONSOLE_TOOLS,
Self::Social => crate::social::SOCIAL_TOOLS,
Self::Advertising => crate::ads::ADS_TOOLS,
};
DriverClass { kind: self, tools }
}
}
impl fmt::Display for DriverKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
pub fn all_tools() -> impl Iterator<Item = &'static ToolSpec> {
DriverKind::ALL.into_iter().flat_map(|kind| kind.class().tools.iter())
}
pub fn tool_spec(name: &str) -> Option<&'static ToolSpec> {
all_tools().find(|spec| spec.name == name)
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct DriverClass {
pub kind: DriverKind,
pub tools: &'static [ToolSpec],
}
impl DriverClass {
pub fn tool(&self, name: &str) -> Option<&'static ToolSpec> {
self.tools.iter().find(|spec| spec.name == name)
}
pub fn tools_for(&self, side: Side) -> impl Iterator<Item = &'static ToolSpec> + use<> {
self.tools.iter().filter(move |spec| spec.side == side)
}
pub fn serves(&self, side: Side) -> bool {
self.tools_for(side).next().is_some()
}
pub fn manifest(
&self,
id: &str,
server: McpServerConfig,
side: Side,
) -> std::result::Result<DriverManifest, KernelError> {
if !self.serves(side) {
return Err(KernelError::Config {
reason: format!("the {} driver class has no {} tool", self.kind, side.as_str()),
});
}
let mut manifest = DriverManifest::new(id, server)?.with_partitions([side.partition()]);
for spec in self.tools_for(side) {
manifest = manifest.with_tool(spec.name, spec.class);
}
Ok(manifest)
}
pub fn manifest_toml(&self, id: &str, command: &str, args: &[&str], side: Side) -> String {
let quoted = |text: &str| serde_json::to_string(text).unwrap_or_default();
let mut out = format!(
"# The {} driver's {} tools (spec 3.5 §7.13).\nid = {}\ncommand = {}\n",
self.kind,
side.as_str(),
quoted(id),
quoted(command)
);
if !args.is_empty() {
let args: Vec<String> = args.iter().map(|arg| quoted(arg)).collect();
out.push_str(&format!("args = [{}]\n", args.join(", ")));
}
out.push_str(&format!("partitions = [{}]\n\n[tools]\n", quoted(side.partition().as_str())));
for spec in self.tools_for(side) {
out.push_str(&format!("{} = {}\n", spec.name, quoted(spec.class.as_str())));
}
out
}
pub fn check_manifest(&self, manifest: &DriverManifest, side: Side) -> ManifestCheck {
let mut gaps = Vec::new();
let partition = side.partition();
for listed in &manifest.partitions {
if *listed != partition {
gaps.push(Gap::WrongPartition { partition: listed.to_string() });
}
}
for spec in self.tools_for(side) {
match manifest.tools.get(spec.name) {
None => gaps.push(Gap::MissingTool { tool: spec.name.to_string() }),
Some(class) if !at_least_as_strict(*class, spec.class) => {
gaps.push(Gap::WeakerClass {
tool: spec.name.to_string(),
contract: spec.class,
manifest: *class,
});
}
Some(_) => {}
}
}
for tool in manifest.tools.keys() {
if self.tool(tool).is_some_and(|spec| spec.side != side) {
gaps.push(Gap::ForeignTool { tool: tool.clone() });
}
}
ManifestCheck { gaps }
}
pub fn check_listing(&self, side: Side, listed: &[(String, Value)]) -> ManifestCheck {
let mut gaps = Vec::new();
for spec in self.tools_for(side) {
let Some((_, schema)) = listed.iter().find(|(name, _)| name == spec.name) else {
gaps.push(Gap::MissingTool { tool: spec.name.to_string() });
continue;
};
let offered: BTreeSet<&str> = schema
.get("properties")
.and_then(Value::as_object)
.map(|properties| properties.keys().map(String::as_str).collect())
.unwrap_or_default();
for argument in spec.required_args() {
if !offered.contains(argument.as_str()) {
gaps.push(Gap::MissingArgument { tool: spec.name.to_string(), argument });
}
}
}
for (name, _) in listed {
if !self.tools_for(side).any(|spec| spec.name == name) {
gaps.push(Gap::ForeignTool { tool: name.clone() });
}
}
ManifestCheck { gaps }
}
}
fn at_least_as_strict(declared: EffectClass, contract: EffectClass) -> bool {
declared == contract || declared.strictness() > contract.strictness()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
#[non_exhaustive]
pub enum Gap {
MissingTool {
tool: String,
},
WeakerClass {
tool: String,
contract: EffectClass,
manifest: EffectClass,
},
ForeignTool {
tool: String,
},
WrongPartition {
partition: String,
},
MissingArgument {
tool: String,
argument: String,
},
}
impl fmt::Display for Gap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingTool { tool } => write!(f, "`{tool}` is missing"),
Self::WeakerClass { tool, contract, manifest } => {
write!(f, "`{tool}` is classed `{manifest}`; the contract needs `{contract}`")
}
Self::ForeignTool { tool } => write!(f, "`{tool}` does not belong on this side"),
Self::WrongPartition { partition } => {
write!(f, "the manifest serves partition `{partition}`")
}
Self::MissingArgument { tool, argument } => {
write!(f, "`{tool}` takes no `{argument}` argument")
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ManifestCheck {
pub gaps: Vec<Gap>,
}
impl ManifestCheck {
pub fn is_satisfied(&self) -> bool {
self.gaps.is_empty()
}
}
impl fmt::Display for ManifestCheck {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.gaps.is_empty() {
return f.write_str("satisfies the driver class");
}
let gaps: Vec<String> = self.gaps.iter().map(ToString::to_string).collect();
f.write_str(&gaps.join("; "))
}
}