Skip to main content

adk_kernel/agents/
check.rs

1//! The agent table's own checks (spec 3.3 §5.7, §10 K7, S-I12): what the kernel knows
2//! about a definition without its host — the risk floor, its area's limits, a suggester's
3//! ceiling, and whether a change lets an agent do more.
4
5use std::collections::BTreeSet;
6
7use adk_core::ApprovalRisk;
8use serde_json::Value;
9
10use crate::agents::factory::{AgentAssessment, AgentCeiling};
11use crate::agents::record::{AgentDefinition, AgentOrigin, FileAccess, ShellAccess, WebAccess};
12use crate::drivers::EffectClass;
13use crate::partition::{Partition, PartitionMode};
14
15/// The packs that let an agent spend money (spec 3.3 §5.7): payments and computer use.
16pub const MONEY_PACKS: [&str; 3] = ["payments", "computer-use", "computer_use"];
17
18/// How much a mode lets an agent do without asking: 0 for `read_only` to 3 for `auto`.
19pub(crate) fn looseness(mode: PartitionMode) -> u8 {
20    match mode {
21        PartitionMode::ReadOnly => 0,
22        PartitionMode::Plan => 1,
23        PartitionMode::Ask => 2,
24        PartitionMode::Auto => 3,
25    }
26}
27
28/// The plain words of a mode, as the surfaces show it.
29pub(crate) fn mode_words(mode: PartitionMode) -> &'static str {
30    match mode {
31        PartitionMode::ReadOnly => "Just look",
32        PartitionMode::Plan => "Suggest",
33        PartitionMode::Ask => "Ask first",
34        PartitionMode::Auto => "Go ahead",
35    }
36}
37
38/// The risk of a driver whose tools are of `classes` (spec 3.3 §5.7): low for reads,
39/// medium for writing locally and scheduling with others, high for sending and deleting and
40/// for tools it does not describe, high and money for spending or publishing (K-I9).
41fn class_risk(class: EffectClass) -> (ApprovalRisk, bool) {
42    match class {
43        EffectClass::Read => (ApprovalRisk::Low, false),
44        EffectClass::WriteLocal | EffectClass::ScheduleWithOthers => (ApprovalRisk::Medium, false),
45        EffectClass::PublishPublic | EffectClass::Financial => (ApprovalRisk::High, true),
46        _ => (ApprovalRisk::High, false),
47    }
48}
49
50fn class_words(class: EffectClass) -> &'static str {
51    match class {
52        EffectClass::Read => "read",
53        EffectClass::WriteLocal => "change your data",
54        EffectClass::ScheduleWithOthers => "schedule with others",
55        EffectClass::SendExternal => "send to others",
56        EffectClass::PublishPublic => "publish publicly",
57        EffectClass::Financial => "move money",
58        EffectClass::Delete => "delete",
59        _ => "do things it does not describe",
60    }
61}
62
63/// What the kernel itself knows of `definition`'s risk (spec 3.3 §5.7's risk table), the
64/// floor under any factory's assessment: its mode, files, shell, web and money packs; each
65/// of its drivers by the effect classes of its tools (`drivers`: id and classes; a driver
66/// with no class listed counts as undescribed); and a suggestion from work the person did
67/// not start at a screen, which is high (decision 20). Abilities name only the drivers; the
68/// factory words the rest.
69///
70/// # Example
71///
72/// ```rust
73/// use adk_core::ApprovalRisk;
74/// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentUses, kernel_assessment};
75/// use adk_kernel::drivers::EffectClass;
76/// use adk_kernel::PartitionMode;
77///
78/// let calendar = AgentDefinition::new("Planner", "work")
79///     .with_mode(PartitionMode::Plan)
80///     .with_uses(AgentUses::default().with_driver("calendar"));
81/// let low = kernel_assessment(&calendar, &AgentOrigin::ByHand, &[("calendar".into(), vec![EffectClass::Read])]);
82/// assert_eq!(low.risk, ApprovalRisk::Low);
83/// let money = kernel_assessment(&calendar, &AgentOrigin::ByHand, &[("calendar".into(), vec![EffectClass::Financial])]);
84/// assert_eq!((money.risk, money.money), (ApprovalRisk::High, true));
85/// ```
86pub fn kernel_assessment(
87    definition: &AgentDefinition,
88    origin: &AgentOrigin,
89    drivers: &[(String, Vec<EffectClass>)],
90) -> AgentAssessment {
91    let uses = &definition.uses;
92    let mut risk = match definition.mode {
93        PartitionMode::ReadOnly | PartitionMode::Plan => ApprovalRisk::Low,
94        PartitionMode::Ask => ApprovalRisk::Medium,
95        PartitionMode::Auto => ApprovalRisk::High,
96    };
97    if uses.files == FileAccess::ReadWrite || uses.web == WebAccess::Any {
98        risk = risk.max(ApprovalRisk::Medium);
99    }
100    risk = risk.max(match uses.shell {
101        ShellAccess::None => ApprovalRisk::Low,
102        ShellAccess::Sandboxed => ApprovalRisk::Medium,
103        ShellAccess::Host => ApprovalRisk::High,
104    });
105    if matches!(origin, AgentOrigin::Suggested { unattended: true, .. }) {
106        risk = ApprovalRisk::High;
107    }
108    let mut assessment = AgentAssessment::new(risk);
109    if uses.packs.iter().any(|pack| MONEY_PACKS.contains(&pack.as_str())) {
110        assessment = assessment.with_money();
111    }
112    for driver in &uses.drivers {
113        let classes: BTreeSet<EffectClass> = drivers
114            .iter()
115            .find(|(id, _)| id == driver)
116            .map(|(_, classes)| classes.iter().copied().collect())
117            .filter(|classes: &BTreeSet<EffectClass>| !classes.is_empty())
118            .unwrap_or_else(|| BTreeSet::from([EffectClass::Other]));
119        for class in &classes {
120            let (class_risk, money) = class_risk(*class);
121            assessment.risk = assessment.risk.max(class_risk);
122            if money {
123                assessment = assessment.with_money();
124            }
125        }
126        let words: Vec<&str> = classes.iter().map(|class| class_words(*class)).collect();
127        assessment
128            .abilities
129            .push(format!("It can use the {driver} driver, which can {}.", join_words(&words)));
130    }
131    assessment
132}
133
134fn join_words(words: &[&str]) -> String {
135    match words {
136        [] => String::new(),
137        [one] => (*one).to_string(),
138        [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
139    }
140}
141
142/// Why `definition` exceeds its area (spec 3.3 §5.7): a mode looser than the area's, a
143/// daily limit above the area's, or a driver not mounted for it. Empty when it fits.
144///
145/// # Example
146///
147/// ```rust
148/// use adk_kernel::agents::{AgentDefinition, AgentUses, area_limits};
149/// use adk_kernel::{Partition, PartitionMode};
150///
151/// let home = Partition::new("home", "home").with_mode(PartitionMode::Ask);
152/// let ok = AgentDefinition::new("Finance", "home").with_mode(PartitionMode::Plan);
153/// assert!(area_limits(&ok, &home).is_empty());
154/// let loose = ok.clone().with_mode(PartitionMode::Auto).with_uses(AgentUses::default().with_driver("mail"));
155/// assert_eq!(area_limits(&loose, &home).len(), 2);
156/// ```
157pub fn area_limits(definition: &AgentDefinition, area: &Partition) -> Vec<String> {
158    let mut over = Vec::new();
159    if looseness(definition.mode) > looseness(area.default_mode) {
160        over.push(format!(
161            "it would {} where its area asks for {} at most",
162            mode_words(definition.mode).to_lowercase(),
163            mode_words(area.default_mode).to_lowercase()
164        ));
165    }
166    if let Some(cap) = area.quotas.daily_spend_cap {
167        match definition.daily_limit_micro_usd {
168            Some(limit) if limit <= cap => {}
169            Some(limit) => over.push(format!(
170                "its daily limit of {} is above its area's {}",
171                dollars(limit),
172                dollars(cap)
173            )),
174            None => {}
175        }
176    }
177    // Mounting a driver is its own approval (K-I13), never part of adding an agent.
178    for driver in definition.uses.drivers.iter().filter(|driver| !area.drivers.contains(driver)) {
179        over.push(format!("the {driver} driver is not mounted for its area; mount it there first"));
180    }
181    over
182}
183
184/// Micro-USD as the person reads money: `$2.50`.
185fn dollars(micro_usd: u64) -> String {
186    let cents = micro_usd.saturating_add(5_000) / 10_000;
187    format!("${}.{:02}", cents / 100, cents % 100)
188}
189
190/// Why a suggested `definition` exceeds its suggester (spec 3.3 S-I12): what is over the
191/// suggester's `ceiling` — its mode, uses and daily spending limit — and what a suggestion
192/// never carries — a shell on this computer, payments or computer use. Empty when it fits.
193///
194/// # Example
195///
196/// ```rust
197/// use adk_kernel::agents::{AgentCeiling, AgentDefinition, AgentUses, ShellAccess, over_ceiling};
198/// use adk_kernel::PartitionMode;
199///
200/// let ceiling = AgentCeiling::new(PartitionMode::Auto, AgentUses::default().with_shell(ShellAccess::Host));
201/// let host = AgentDefinition::new("Ops", "default").with_uses(AgentUses::default().with_shell(ShellAccess::Host));
202/// assert_eq!(over_ceiling(&host, &ceiling), ["a shell on this computer"]);
203///
204/// let capped = AgentCeiling::new(PartitionMode::Auto, AgentUses::default()).with_daily_limit(2_000_000);
205/// let unlimited = AgentDefinition::new("Ops", "default");
206/// assert_eq!(over_ceiling(&unlimited, &capped), ["spending with no daily limit, where it may spend $2.00"]);
207/// ```
208pub fn over_ceiling(definition: &AgentDefinition, ceiling: &AgentCeiling) -> Vec<String> {
209    let mut over = Vec::new();
210    if looseness(definition.mode) > looseness(ceiling.mode) {
211        over.push(format!(
212            "{} where it may only {}",
213            mode_words(definition.mode).to_lowercase(),
214            mode_words(ceiling.mode).to_lowercase()
215        ));
216    }
217    // Spending is at most the suggester's, so a suggestion under a limit carries one too
218    // (spec 3.3 S-I12).
219    if let Some(cap) = ceiling.daily_limit_micro_usd {
220        match definition.daily_limit_micro_usd {
221            Some(limit) if limit <= cap => {}
222            Some(limit) => over.push(format!(
223                "a daily spending limit of {}, above its {}",
224                dollars(limit),
225                dollars(cap)
226            )),
227            None => over
228                .push(format!("spending with no daily limit, where it may spend {}", dollars(cap))),
229        }
230    }
231    over.extend(definition.uses.over(&ceiling.uses));
232    let host = "a shell on this computer".to_string();
233    if definition.uses.shell == ShellAccess::Host && !over.contains(&host) {
234        over.push(host);
235    }
236    for pack in definition.uses.packs.iter().filter(|pack| MONEY_PACKS.contains(&pack.as_str())) {
237        let words = format!("the {pack} pack");
238        if !over.contains(&words) {
239            over.push(words);
240        }
241    }
242    over
243}
244
245/// The definition fields `now` changes from `was`, by their wire names, sorted.
246///
247/// # Example
248///
249/// ```rust
250/// use adk_kernel::agents::{AgentDefinition, changed_fields};
251/// use adk_kernel::PartitionMode;
252///
253/// let was = AgentDefinition::new("Finance", "default");
254/// let now = was.clone().with_mode(PartitionMode::Plan);
255/// let mut renamed = now.clone();
256/// renamed.display_name = "Bills".into();
257/// assert_eq!(changed_fields(&was, &renamed), ["displayName", "mode"]);
258/// ```
259pub fn changed_fields(was: &AgentDefinition, now: &AgentDefinition) -> Vec<String> {
260    let (Ok(Value::Object(old)), Ok(Value::Object(new))) = (
261        serde_json::to_value(was.clone().normalized()),
262        serde_json::to_value(now.clone().normalized()),
263    ) else {
264        return Vec::new();
265    };
266    old.keys()
267        .chain(new.keys())
268        .filter(|key| old.get(*key) != new.get(*key))
269        .cloned()
270        .collect::<BTreeSet<_>>()
271        .into_iter()
272        .collect()
273}
274
275/// What `now` lets an agent do that `was` did not (spec 3.3 §5.7): a looser mode, more
276/// uses, a higher or no daily limit. Empty when the change only makes it do less or the
277/// same; its name, colour, line, instructions and model never count.
278///
279/// # Example
280///
281/// ```rust
282/// use adk_kernel::agents::{AgentDefinition, AgentUses, FileAccess, widened};
283/// use adk_kernel::PartitionMode;
284///
285/// let was = AgentDefinition::new("Finance", "default").with_mode(PartitionMode::Ask);
286/// assert!(widened(&was, &was.clone().with_mode(PartitionMode::Plan)).is_empty());
287/// let more = was.clone().with_uses(AgentUses::default().with_files(FileAccess::Read));
288/// assert_eq!(widened(&was, &more), ["reading files"]);
289/// ```
290pub fn widened(was: &AgentDefinition, now: &AgentDefinition) -> Vec<String> {
291    let mut more = Vec::new();
292    if looseness(now.mode) > looseness(was.mode) {
293        more.push(format!(
294            "{} instead of {}",
295            mode_words(now.mode).to_lowercase(),
296            mode_words(was.mode).to_lowercase()
297        ));
298    }
299    more.extend(now.uses.over(&was.uses));
300    match (was.daily_limit_micro_usd, now.daily_limit_micro_usd) {
301        (Some(_), None) => more.push("no daily limit of its own".to_string()),
302        (Some(old), Some(new)) if new > old => {
303            more.push(format!("a daily limit of {new} micro-USD instead of {old}"));
304        }
305        _ => {}
306    }
307    more
308}
309
310#[cfg(test)]
311mod tests {
312    use adk_core::AgentId;
313
314    use super::*;
315    use crate::agents::record::AgentUses;
316
317    fn definition(mode: PartitionMode, uses: AgentUses) -> AgentDefinition {
318        AgentDefinition::new("Finance", "default").with_mode(mode).with_uses(uses)
319    }
320
321    fn risk(mode: PartitionMode, uses: AgentUses) -> (ApprovalRisk, bool) {
322        let assessment = kernel_assessment(&definition(mode, uses), &AgentOrigin::ByHand, &[]);
323        (assessment.risk, assessment.money)
324    }
325
326    /// Wave 3 finding 25: what an area refuses reads as plain words, in dollars, with no
327    /// internal identifier.
328    #[test]
329    fn area_refusals_are_plain_words_in_dollars() {
330        let mut area = Partition::new("home", "home").with_mode(PartitionMode::Ask);
331        area.quotas.daily_spend_cap = Some(2_000_000);
332        let definition = definition(PartitionMode::Ask, AgentUses::default().with_driver("mail"))
333            .with_daily_limit(5_000_000);
334        let over = area_limits(&definition, &area);
335        assert_eq!(
336            over,
337            [
338                "its daily limit of $5.00 is above its area's $2.00",
339                "the mail driver is not mounted for its area; mount it there first"
340            ]
341        );
342        assert_eq!(dollars(2_499_999), "$2.50");
343        assert_eq!(dollars(999_999), "$1.00");
344    }
345
346    #[test]
347    fn the_risk_table_rows() {
348        use ApprovalRisk::{High, Low, Medium};
349        let none = AgentUses::default;
350        // Low: Just look or Suggest; no shell; no web or listed sites.
351        assert_eq!(risk(PartitionMode::ReadOnly, none()), (Low, false));
352        assert_eq!(
353            risk(
354                PartitionMode::Plan,
355                none().with_files(FileAccess::Read).with_web(WebAccess::listed(["a.io"]))
356            ),
357            (Low, false)
358        );
359        // Medium: Ask first; changing files; the sandboxed shell; any site.
360        assert_eq!(risk(PartitionMode::Ask, none()), (Medium, false));
361        assert_eq!(
362            risk(PartitionMode::Plan, none().with_files(FileAccess::ReadWrite)),
363            (Medium, false)
364        );
365        assert_eq!(
366            risk(PartitionMode::Plan, none().with_shell(ShellAccess::Sandboxed)),
367            (Medium, false)
368        );
369        assert_eq!(risk(PartitionMode::Plan, none().with_web(WebAccess::Any)), (Medium, false));
370        // High: Go ahead; a shell on this computer.
371        assert_eq!(risk(PartitionMode::Auto, none()), (High, false));
372        assert_eq!(
373            risk(PartitionMode::ReadOnly, none().with_shell(ShellAccess::Host)),
374            (High, false)
375        );
376        // High, spends money: payments or computer use.
377        assert_eq!(risk(PartitionMode::ReadOnly, none().with_pack("payments")), (High, true));
378        assert_eq!(risk(PartitionMode::ReadOnly, none().with_pack("computer-use")), (High, true));
379    }
380
381    #[test]
382    fn drivers_count_by_their_effect_classes() {
383        let uses = AgentUses::default().with_driver("cal");
384        let read_only = definition(PartitionMode::ReadOnly, uses.clone());
385        let assess = |classes: Vec<EffectClass>| {
386            let a = kernel_assessment(&read_only, &AgentOrigin::ByHand, &[("cal".into(), classes)]);
387            (a.risk, a.money)
388        };
389        assert_eq!(assess(vec![EffectClass::Read]), (ApprovalRisk::Low, false));
390        assert_eq!(
391            assess(vec![EffectClass::Read, EffectClass::ScheduleWithOthers]),
392            (ApprovalRisk::Medium, false)
393        );
394        assert_eq!(assess(vec![EffectClass::WriteLocal]), (ApprovalRisk::Medium, false));
395        assert_eq!(assess(vec![EffectClass::SendExternal]), (ApprovalRisk::High, false));
396        assert_eq!(assess(vec![EffectClass::Delete]), (ApprovalRisk::High, false));
397        assert_eq!(assess(vec![EffectClass::PublishPublic]), (ApprovalRisk::High, true));
398        assert_eq!(assess(vec![EffectClass::Financial]), (ApprovalRisk::High, true));
399        // A driver the kernel knows nothing of counts as undescribed.
400        assert_eq!(assess(vec![]), (ApprovalRisk::High, false));
401        let words = kernel_assessment(
402            &read_only,
403            &AgentOrigin::ByHand,
404            &[("cal".into(), vec![EffectClass::Read, EffectClass::ScheduleWithOthers])],
405        );
406        assert_eq!(
407            words.abilities,
408            ["It can use the cal driver, which can read and schedule with others."]
409        );
410    }
411
412    #[test]
413    fn an_unattended_suggestion_is_high_risk() {
414        let origin = |unattended| AgentOrigin::Suggested {
415            agent: AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
416            session: "s".into(),
417            run: None,
418            unattended,
419        };
420        let plain = definition(PartitionMode::ReadOnly, AgentUses::default());
421        assert_eq!(kernel_assessment(&plain, &origin(false), &[]).risk, ApprovalRisk::Low);
422        assert_eq!(kernel_assessment(&plain, &origin(true), &[]).risk, ApprovalRisk::High);
423    }
424
425    #[test]
426    fn a_suggestion_never_carries_a_host_shell_or_money() {
427        let generous = AgentCeiling::new(
428            PartitionMode::Auto,
429            AgentUses::default().with_shell(ShellAccess::Host).with_pack("payments"),
430        );
431        let wants = definition(
432            PartitionMode::Ask,
433            AgentUses::default().with_shell(ShellAccess::Host).with_pack("payments"),
434        );
435        assert_eq!(
436            over_ceiling(&wants, &generous),
437            ["a shell on this computer", "the payments pack"]
438        );
439        let tight = AgentCeiling::new(PartitionMode::Plan, AgentUses::default());
440        let looser = definition(PartitionMode::Ask, AgentUses::default());
441        assert_eq!(over_ceiling(&looser, &tight), ["ask first where it may only suggest"]);
442    }
443
444    #[test]
445    fn area_limits_cover_mode_limit_and_drivers() {
446        let home = Partition::new("home", "home")
447            .with_mode(PartitionMode::Ask)
448            .with_driver("calendar")
449            .with_quotas(crate::sched::Quotas::new().with_daily_spend_cap(1_000));
450        let fits = definition(PartitionMode::Ask, AgentUses::default().with_driver("calendar"))
451            .with_daily_limit(500);
452        assert!(area_limits(&fits, &home).is_empty());
453        let over = definition(PartitionMode::Auto, AgentUses::default().with_driver("mail"))
454            .with_daily_limit(5_000);
455        assert_eq!(area_limits(&over, &home).len(), 3);
456    }
457
458    #[test]
459    fn widening_ignores_words_and_model() {
460        let was = definition(PartitionMode::Ask, AgentUses::default()).with_daily_limit(100);
461        let mut words = was.clone().with_instructions("New words").with_description("New line");
462        words.display_name = "Bills".into();
463        assert!(widened(&was, &words).is_empty());
464        let mut unlimited = was.clone();
465        unlimited.daily_limit_micro_usd = None;
466        assert_eq!(widened(&was, &unlimited), ["no daily limit of its own"]);
467        assert_eq!(widened(&was, &was.clone().with_daily_limit(50)), Vec::<String>::new());
468    }
469}