use std::collections::BTreeMap;
use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::class::{AutonomyCap, tool_spec};
pub const DRIVER_CAP_POLICY_REF: &str = "adk-drivers/caps";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BudgetCap {
pub currency: String,
pub max_minor: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DriverBudget {
caps: BTreeMap<String, BudgetCap>,
}
impl DriverBudget {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn cap(
mut self,
tool: impl Into<String>,
currency: impl Into<String>,
max_minor: u64,
) -> Self {
self.caps.insert(tool.into(), BudgetCap { currency: currency.into(), max_minor });
self
}
pub fn get(&self, tool: &str) -> Option<&BudgetCap> {
self.caps.get(tool)
}
}
#[derive(Debug, Clone, Default)]
pub struct DriverCapPolicy {
budget: DriverBudget,
}
impl DriverCapPolicy {
pub fn new(budget: DriverBudget) -> Self {
Self { budget }
}
pub fn decide(&self, tool: &str, args: &Value) -> PolicyDecision {
let Some(spec) = tool_spec(tool) else {
return PolicyDecision::Allow;
};
match spec.cap {
AutonomyCap::AlwaysHeld => PolicyDecision::require_approval(format!(
"`{tool}` is held for the owner in every mode (spec 3.5 §7.13, A-I21)"
)),
AutonomyCap::WithinBudget => {
let Some(pointer) = spec.budget_arg else {
return PolicyDecision::Allow;
};
let Some(cap) = self.budget.get(tool) else {
return PolicyDecision::require_approval(format!(
"`{tool}` acts within the owner's budget, and none is set for it"
));
};
let amount = args.pointer(pointer).and_then(Value::as_u64);
let currency = args.get("currency").and_then(Value::as_str);
match (amount, currency) {
(Some(amount), Some(currency))
if amount <= cap.max_minor
&& currency.eq_ignore_ascii_case(&cap.currency) =>
{
PolicyDecision::Allow
}
_ => PolicyDecision::require_approval(format!(
"`{tool}` goes beyond the owner's budget of {} {} (minor units) per call",
cap.max_minor, cap.currency
)),
}
}
AutonomyCap::Read | AutonomyCap::Propose | AutonomyCap::WithinPlaybook => {
PolicyDecision::Allow
}
}
}
}
#[async_trait]
impl ToolPolicy for DriverCapPolicy {
async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
self.decide(&request.tool_name, &request.args)
}
fn policy_ref(&self) -> Option<String> {
Some(DRIVER_CAP_POLICY_REF.to_string())
}
}