adk_drivers/policy.rs
1//! The policy layer for driver tools' autonomy caps (spec 3.5 §7.13, A-I21).
2
3use std::collections::BTreeMap;
4
5use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest};
6use async_trait::async_trait;
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use crate::class::{AutonomyCap, tool_spec};
11
12/// The policy reference of [`DriverCapPolicy`] in audit records: `tool_policy:adk-drivers/caps`.
13pub const DRIVER_CAP_POLICY_REF: &str = "adk-drivers/caps";
14
15/// The owner's budget for one [`AutonomyCap::WithinBudget`] tool (spec 3.5 §7.13): the
16/// most a single call may commit, in minor units of `currency`.
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19#[non_exhaustive]
20pub struct BudgetCap {
21 /// The currency, as ISO 4217.
22 pub currency: String,
23 /// The most one call may commit, in minor units.
24 pub max_minor: u64,
25}
26
27/// The owner's budgets for the driver tools that act within budget (spec 3.5 §7.13): a
28/// domain renewal's price, an advertising bid.
29///
30/// # Example
31///
32/// ```rust
33/// use adk_drivers::DriverBudget;
34///
35/// let budget = DriverBudget::new()
36/// .cap("registrar_renew_domain", "USD", 30_00)
37/// .cap("ads_set_bid", "USD", 2_50);
38/// assert_eq!(budget.get("ads_set_bid").unwrap().max_minor, 250);
39/// ```
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct DriverBudget {
43 caps: BTreeMap<String, BudgetCap>,
44}
45
46impl DriverBudget {
47 /// No budget: every within-budget call is held.
48 pub fn new() -> Self {
49 Self::default()
50 }
51
52 /// Lets one call of `tool` commit at most `max_minor` of `currency` without a person.
53 #[must_use]
54 pub fn cap(
55 mut self,
56 tool: impl Into<String>,
57 currency: impl Into<String>,
58 max_minor: u64,
59 ) -> Self {
60 self.caps.insert(tool.into(), BudgetCap { currency: currency.into(), max_minor });
61 self
62 }
63
64 /// The cap of `tool`.
65 pub fn get(&self, tool: &str) -> Option<&BudgetCap> {
66 self.caps.get(tool)
67 }
68}
69
70/// Enforces the driver classes' autonomy caps on the governed path (spec 3.5 §7.13, A-I21).
71///
72/// It only ever tightens: compose it with the harness's mode policy and the kernel's
73/// `DriverPolicy` through `StrictestPolicy`, so a call it allows is decided by those
74/// layers. It knows driver tools by name, whether an in-process adapter or an MCP server
75/// serves them.
76///
77/// | Tool's cap | Decision |
78/// |---|---|
79/// | [`AlwaysHeld`](AutonomyCap::AlwaysHeld) — a DNS change, a campaign launch | RequireApproval on every call, in every mode (A-I21) |
80/// | [`WithinBudget`](AutonomyCap::WithinBudget) with an amount — a renewal, a bid | Allow within the owner's [`DriverBudget`] for the tool, in its currency; RequireApproval beyond it or without one |
81/// | Any other driver tool, and every tool that is not a driver's | Allow (decided by the other layers) |
82///
83/// # Example
84///
85/// ```rust
86/// use adk_core::{PolicyDecision, ToolPolicy, ToolPolicyRequest};
87/// use adk_drivers::{DriverBudget, DriverCapPolicy};
88/// use serde_json::json;
89///
90/// # futures::executor::block_on(async {
91/// let policy = DriverCapPolicy::new(DriverBudget::new().cap("ads_set_bid", "USD", 200));
92/// let change = ToolPolicyRequest::new("dns_change_records", json!({"zone": "example.com."}));
93/// assert!(matches!(policy.evaluate(&change).await, PolicyDecision::RequireApproval { .. }));
94/// let bid = ToolPolicyRequest::new("ads_set_bid", json!({"campaign": "c1", "bid_minor": 150, "currency": "USD"}));
95/// assert_eq!(policy.evaluate(&bid).await, PolicyDecision::Allow);
96/// let high = ToolPolicyRequest::new("ads_set_bid", json!({"campaign": "c1", "bid_minor": 900, "currency": "USD"}));
97/// assert!(matches!(policy.evaluate(&high).await, PolicyDecision::RequireApproval { .. }));
98/// # });
99/// ```
100#[derive(Debug, Clone, Default)]
101pub struct DriverCapPolicy {
102 budget: DriverBudget,
103}
104
105impl DriverCapPolicy {
106 /// The policy with the owner's `budget`.
107 pub fn new(budget: DriverBudget) -> Self {
108 Self { budget }
109 }
110
111 /// The decision for a call to `tool` with `args`.
112 pub fn decide(&self, tool: &str, args: &Value) -> PolicyDecision {
113 let Some(spec) = tool_spec(tool) else {
114 return PolicyDecision::Allow;
115 };
116 match spec.cap {
117 AutonomyCap::AlwaysHeld => PolicyDecision::require_approval(format!(
118 "`{tool}` is held for the owner in every mode (spec 3.5 §7.13, A-I21)"
119 )),
120 AutonomyCap::WithinBudget => {
121 let Some(pointer) = spec.budget_arg else {
122 return PolicyDecision::Allow;
123 };
124 let Some(cap) = self.budget.get(tool) else {
125 return PolicyDecision::require_approval(format!(
126 "`{tool}` acts within the owner's budget, and none is set for it"
127 ));
128 };
129 let amount = args.pointer(pointer).and_then(Value::as_u64);
130 let currency = args.get("currency").and_then(Value::as_str);
131 match (amount, currency) {
132 (Some(amount), Some(currency))
133 if amount <= cap.max_minor
134 && currency.eq_ignore_ascii_case(&cap.currency) =>
135 {
136 PolicyDecision::Allow
137 }
138 _ => PolicyDecision::require_approval(format!(
139 "`{tool}` goes beyond the owner's budget of {} {} (minor units) per call",
140 cap.max_minor, cap.currency
141 )),
142 }
143 }
144 AutonomyCap::Read | AutonomyCap::Propose | AutonomyCap::WithinPlaybook => {
145 PolicyDecision::Allow
146 }
147 }
148 }
149}
150
151#[async_trait]
152impl ToolPolicy for DriverCapPolicy {
153 async fn evaluate(&self, request: &ToolPolicyRequest) -> PolicyDecision {
154 self.decide(&request.tool_name, &request.args)
155 }
156
157 fn policy_ref(&self) -> Option<String> {
158 Some(DRIVER_CAP_POLICY_REF.to_string())
159 }
160}