Skip to main content

adk_surface/verbs/
policy.rs

1//! How an agent's screen actions are governed and shown (spec 3.3 §7.1, §7.2, owner question
2//! 22): held for a person every time, at most three waiting, on a card that offers Allow once ·
3//! Edit · Deny and never **Always allow**.
4
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6use std::sync::{Arc, Mutex};
7
8use adk_core::{
9    AgentId, ApprovalAction, ApprovalCall, ApprovalRequest, ApprovalRequestQuery, ApprovalRisk,
10    ApprovalRoute, ApprovalRouter, ApprovalScope, ApprovalState, ApprovalStore, Event, Part,
11    PolicyCall, PolicyDecision, ToolConfirmationRequest, ToolPolicy, ToolPolicyRequest,
12};
13use adk_kernel::PartitionId;
14use adk_kernel::drivers::EffectClass;
15use adk_session::GetRequest;
16use async_trait::async_trait;
17
18use super::registry::VerbRegistry;
19use super::{Callers, MAX_WAITING, verbs_principal, words};
20use crate::hints::{CardHint, CardHints};
21use crate::model::{CardDetail, Reversibility};
22use crate::source::Source;
23
24/// The policy reference of [`VerbPolicy`] in audit records: `tool_policy:adk-surface/verbs`.
25pub const VERB_POLICY_REF: &str = "adk-surface/verbs";
26
27/// Decides calls to screen-action tools (spec 3.3 §2 item 7, owner questions 22 and 23).
28///
29/// Attach it with `HarnessAgentBuilder::add_operator_policy`: it composes with the harness's
30/// policy through `StrictestPolicy`, so no mode, standing rule or earlier approval allows an
31/// agent's change (the spec 3.2 K-I9 pattern).
32///
33/// | Call | Decision |
34/// |---|---|
35/// | A tool not published as `verbs:<app>` | Allow (not this layer's call) |
36/// | By `urn:adk:agent:<app>/surface.verbs`, a person's own action | Allow |
37/// | An action that only reads (`coming_up`) | Allow |
38/// | An action only a person takes | Deny |
39/// | From an agent with [`MAX_WAITING`] requests waiting for the same person already, unless the person answered this call | Deny: "Finance already has 3 changes waiting for you" |
40/// | An action that would be refused now: not found, in another area, started, moved | Deny, before any card |
41/// | Any other action | RequireApproval, every call, with the kernel's words: "Move News digest to 19:00" |
42///
43/// # Example
44///
45/// ```rust,no_run
46/// use std::sync::Arc;
47///
48/// # fn example(registry: adk_surface::verbs::VerbRegistry, builder: adk_harness::HarnessAgentBuilder) {
49/// let builder = builder
50///     .toolset(Arc::new(registry.toolset("work")))
51///     .tool_classes(Arc::new(registry.classes()))
52///     .add_operator_policy(Arc::new(registry.policy("work")));
53/// # let _ = builder;
54/// # }
55/// ```
56#[derive(Debug, Clone)]
57pub struct VerbPolicy {
58    registry: VerbRegistry,
59    area: Option<PartitionId>,
60}
61
62impl VerbPolicy {
63    pub(crate) fn new(registry: VerbRegistry, area: Option<PartitionId>) -> Self {
64        Self { registry, area }
65    }
66
67    /// How many of `agent`'s screen actions wait for `user` to answer, up to
68    /// [`MAX_WAITING`]: requests still pending, on every page of the store.
69    async fn waiting(&self, agent: &AgentId, user: &str) -> usize {
70        let registry = self.registry.inner();
71        let Some(store) = &registry.approvals else {
72            return 0;
73        };
74        let query = ApprovalRequestQuery::default()
75            .with_states([ApprovalState::Pending])
76            .with_app_name(&registry.app)
77            .with_user_id(user);
78        let origin = self.registry.origin();
79        let mut count = 0;
80        let found = every_request(store.as_ref(), query, |request| {
81            if request.origin.as_ref().is_some_and(|by| by.source == origin)
82                && request.acting.as_ref().is_some_and(|acting| acting.agent.id == *agent)
83            {
84                count += 1;
85            }
86            count >= MAX_WAITING
87        })
88        .await;
89        if let Err(error) = found {
90            tracing::warn!(error = %error, "the waiting screen actions could not be counted");
91        }
92        count
93    }
94
95    /// Whether the person already answered this call, so it asks for nothing new: a held
96    /// call resuming with its decision waiting, or the arguments a person's Edit gave it.
97    async fn answered(&self, request: &ToolPolicyRequest, call: &PolicyCall<'_>) -> bool {
98        let Some(store) = &self.registry.inner().approvals else {
99            return false;
100        };
101        let Some(acting) = &request.acting else {
102            return false;
103        };
104        let scope = ApprovalScope::new(&request.app_name, &request.user_id, &request.session_id);
105        let mut held = ToolConfirmationRequest::new(&request.tool_name, request.args.clone())
106            .with_acting_context(acting.clone());
107        if let Some(origin) = call.origin {
108            held = held.with_origin(origin.clone());
109        }
110        if store.has_decision(&scope, &held.fingerprint()).await.unwrap_or(false) {
111            return true;
112        }
113        let query = ApprovalRequestQuery::default()
114            .with_session(&scope)
115            .with_states([ApprovalState::Approved]);
116        let mut edited = false;
117        let _ = every_request(store.as_ref(), query, |approved| {
118            edited = approved.tool_name == request.tool_name
119                && approved.acting.as_ref().is_some_and(|by| by.agent.id == acting.agent.id)
120                && approved
121                    .decisions
122                    .last()
123                    .and_then(|decision| decision.edited_args.as_ref())
124                    .is_some_and(|args| *args == request.args);
125            edited
126        })
127        .await;
128        edited
129    }
130}
131
132/// Reads every request `query` selects, a page at a time, until `seen` returns true.
133pub(crate) async fn every_request(
134    store: &dyn ApprovalStore,
135    mut query: ApprovalRequestQuery,
136    mut seen: impl FnMut(&ApprovalRequest) -> bool,
137) -> adk_core::Result<()> {
138    loop {
139        let page = store.list_requests(&query).await?;
140        let full = page.len() >= query.limit;
141        for request in &page {
142            if seen(request) {
143                return Ok(());
144            }
145        }
146        match page.last() {
147            Some(last) if full => query = query.with_after(Some(last.cursor())),
148            _ => return Ok(()),
149        }
150    }
151}
152
153#[async_trait]
154impl ToolPolicy for VerbPolicy {
155    async fn evaluate(&self, _request: &ToolPolicyRequest) -> PolicyDecision {
156        PolicyDecision::Allow
157    }
158
159    async fn evaluate_call(
160        &self,
161        request: &ToolPolicyRequest,
162        call: &PolicyCall<'_>,
163    ) -> PolicyDecision {
164        let origin = self.registry.origin();
165        if call.origin.is_none_or(|by| by.source != origin) {
166            return PolicyDecision::Allow;
167        }
168        let person = verbs_principal(self.registry.app_name()).id;
169        let agent = request.acting.as_ref().map(|acting| acting.agent.id.clone());
170        if agent.as_ref() == Some(&person) {
171            return PolicyDecision::Allow;
172        }
173        let Some(entry) = self.registry.entry_for_tool(&request.tool_name) else {
174            return PolicyDecision::deny(format!(
175                "there is no screen action `{}` on this home",
176                request.tool_name
177            ));
178        };
179        if entry.spec.reads() {
180            return PolicyDecision::Allow;
181        }
182        if entry.spec.callers == Callers::PersonOnly {
183            return PolicyDecision::deny(format!(
184                "only a person takes `{}`, on a screen",
185                entry.spec.name
186            ));
187        }
188        if let Some(agent) = &agent
189            && self.waiting(agent, &request.user_id).await >= MAX_WAITING
190            && !self.answered(request, call).await
191        {
192            let name = self.registry.display_name(&request.agent_name);
193            return PolicyDecision::deny(words::already_waiting(&name, MAX_WAITING));
194        }
195        let scope = self.registry.scope(&request.user_id, self.area.clone());
196        match entry.handler.describe(&scope, &request.args).await {
197            Ok(text) => PolicyDecision::require_approval(text),
198            Err(error) => PolicyDecision::deny(error.to_string()),
199        }
200    }
201
202    fn policy_ref(&self) -> Option<String> {
203        Some(VERB_POLICY_REF.to_string())
204    }
205}
206
207/// Presents an agent's screen action to the person (spec 3.3 §7.1): the policy's words as the
208/// summary ("Move News digest to 19:00"), the risk its effect carries (a change on the
209/// person's own screens is low) and Allow once · Edit · Deny. Every other call goes to the
210/// fallback router unchanged.
211///
212/// # Example
213///
214/// ```rust,no_run
215/// use adk_core::{ApprovalPolicy, ApproverSelector, InMemoryApprovalStore, StoreApprovalService};
216/// use std::sync::Arc;
217///
218/// # fn example(registry: adk_surface::verbs::VerbRegistry) {
219/// let operator = ApprovalPolicy::new([ApproverSelector::group("operator")]).allow_self_approval();
220/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
221///     .with_router(registry.router(operator));
222/// # let _ = service;
223/// # }
224/// ```
225#[derive(Clone)]
226pub struct VerbRouter {
227    origin: String,
228    /// The effect of each action tool, by tool name.
229    effects: BTreeMap<String, EffectClass>,
230    fallback: Arc<dyn ApprovalRouter>,
231}
232
233impl std::fmt::Debug for VerbRouter {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        f.debug_struct("VerbRouter")
236            .field("origin", &self.origin)
237            .field("tools", &self.effects.keys().collect::<Vec<_>>())
238            .finish_non_exhaustive()
239    }
240}
241
242impl VerbRouter {
243    pub(crate) fn new(registry: VerbRegistry, fallback: Arc<dyn ApprovalRouter>) -> Self {
244        let effects = registry
245            .entries()
246            .iter()
247            .map(|entry| (entry.spec.tool_name(), entry.spec.effect))
248            .collect();
249        Self { origin: registry.origin(), effects, fallback }
250    }
251
252    /// The router of the first catalogue's tools in `app`, with `fallback` for every other
253    /// call, for a host that builds its approval service before the registry, which reads
254    /// that service's store (spec 3.3 §2 item 7).
255    ///
256    /// # Example
257    ///
258    /// ```rust
259    /// use adk_core::{ApprovalPolicy, ApproverSelector};
260    /// use adk_surface::verbs::VerbRouter;
261    ///
262    /// let operator = ApprovalPolicy::new([ApproverSelector::group("operator")]);
263    /// let router = VerbRouter::catalogue("adk-rust", operator);
264    /// # let _ = router;
265    /// ```
266    pub fn catalogue(app: &str, fallback: impl ApprovalRouter + 'static) -> Self {
267        let effects = super::snooze::catalogue()
268            .into_iter()
269            .map(|entry| (entry.spec.tool_name(), entry.spec.effect))
270            .collect();
271        Self { origin: super::verbs_origin(app), effects, fallback: Arc::new(fallback) }
272    }
273}
274
275/// The risk a card of an action of `effect` shows.
276fn risk_of(effect: EffectClass) -> ApprovalRisk {
277    match effect {
278        EffectClass::Read | EffectClass::WriteLocal => ApprovalRisk::Low,
279        EffectClass::PublishPublic | EffectClass::Financial | EffectClass::Delete => {
280            ApprovalRisk::High
281        }
282        _ => ApprovalRisk::Medium,
283    }
284}
285
286/// The policy's own words in `reason`, the governed path's "Tool 'verb_snooze' requires
287/// confirmation: Move News digest to 19:00".
288fn policy_words(reason: &str, tool: &str) -> String {
289    let prefix = format!("Tool '{tool}' requires confirmation: ");
290    reason.strip_prefix(&prefix).unwrap_or(reason).to_string()
291}
292
293impl ApprovalRouter for VerbRouter {
294    fn route(&self, call: &ApprovalCall) -> Option<ApprovalRoute> {
295        let route = self.fallback.route(call)?;
296        if call.request.origin.as_ref().is_none_or(|by| by.source != self.origin) {
297            return Some(route);
298        }
299        let Some(effect) = self.effects.get(&call.request.tool_name) else {
300            return Some(route);
301        };
302        Some(
303            route
304                .with_summary(policy_words(&call.reason, &call.request.tool_name))
305                .with_risk(risk_of(*effect))
306                .with_allowed_actions([
307                    ApprovalAction::Approve,
308                    ApprovalAction::Edit,
309                    ApprovalAction::Reject,
310                ]),
311        )
312    }
313}
314
315/// What an agent's screen action looks like on a card (spec 3.3 §7.1, owner question 30): the
316/// kernel's words as the heading, "Snooze something in Coming up" in chat, "You can change it
317/// back", the fixed line "Agents always ask before they change things on your screens.", what
318/// the agent read in the asking turn first, and never **Always allow**.
319///
320/// It reads only the inbox entry and, for the first step, the asking turn's tool results in
321/// the session store: the pages its `web_fetch` calls fetched, by host. It never reads text
322/// the agent wrote, and a call that was refused or failed is not a page read. Each request's
323/// turn is read once.
324///
325/// # Example
326///
327/// ```rust,no_run
328/// use std::sync::Arc;
329/// use adk_surface::{LocalSource, Source, SurfaceEngine};
330///
331/// # fn example(registry: adk_surface::verbs::VerbRegistry, source: LocalSource) {
332/// let source: Arc<dyn Source> = Arc::new(source);
333/// let engine = SurfaceEngine::builder(Arc::clone(&source))
334///     .card_hints(Arc::new(registry.hints().reading(source)))
335///     .grant(registry.grant())
336///     .build();
337/// # let _ = engine;
338/// # }
339/// ```
340#[derive(Clone)]
341pub struct VerbHints {
342    registry: VerbRegistry,
343    source: Option<Arc<dyn Source>>,
344    /// What the asking turn of each request read, by request: that turn never changes.
345    reads: Arc<Mutex<HashMap<String, Reads>>>,
346}
347
348impl std::fmt::Debug for VerbHints {
349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350        f.debug_struct("VerbHints")
351            .field("registry", &self.registry)
352            .field("source", &self.source.is_some())
353            .finish_non_exhaustive()
354    }
355}
356
357/// What an agent read in the turn that asked.
358#[derive(Debug, Clone)]
359struct Reads {
360    /// The agent, as the session names it.
361    agent: String,
362    /// Pages fetched.
363    pages: usize,
364    /// Their hosts.
365    hosts: BTreeSet<String>,
366}
367
368/// The most requests whose asking turn is kept.
369const KEPT_TURNS: usize = 512;
370
371/// The longest host name (RFC 1035).
372const MAX_HOST: usize = 253;
373
374impl VerbHints {
375    pub(crate) fn new(registry: VerbRegistry) -> Self {
376        Self { registry, source: None, reads: Arc::new(Mutex::new(HashMap::new())) }
377    }
378
379    /// Reads the asking turn and the agents' names through `source`, the engine's own (spec
380    /// 3.3 §5.7, §7.1): an agent the person added or renamed is named as the card names it,
381    /// and a process without the session store, such as a terminal attached to a kernel, still
382    /// shows what the agent read.
383    #[must_use]
384    pub fn reading(mut self, source: Arc<dyn Source>) -> Self {
385        self.source = Some(source);
386        self
387    }
388
389    /// The events of `request`'s session, from the registry's session store, else the source.
390    async fn events(&self, request: &ApprovalRequest) -> Option<Vec<Event>> {
391        let scope = &request.scope;
392        if let Some(sessions) = &self.registry.inner().sessions {
393            let session = sessions
394                .get(GetRequest {
395                    app_name: scope.app_name.clone(),
396                    user_id: scope.user_id.clone(),
397                    session_id: scope.session_id.clone(),
398                    num_recent_events: None,
399                    after: None,
400                })
401                .await
402                .ok()?;
403            return Some(session.events().all());
404        }
405        let source = self.source.as_ref()?;
406        source.transcript(&scope.user_id, &scope.session_id).await.ok().flatten()
407    }
408
409    /// What the turn that made `request`'s call read, once that turn is in the session.
410    async fn reads(&self, request: &ApprovalRequest) -> Option<Reads> {
411        if let Some(reads) = self.reads.lock().unwrap_or_else(|e| e.into_inner()).get(&request.id) {
412            return Some(reads.clone());
413        }
414        let events = self.events(request).await?;
415        // The newest turn that made this call asked.
416        let (at, asking) = events.iter().enumerate().rev().find(|(_, event)| {
417            event.content().is_some_and(|content| {
418                content.parts.iter().any(|part| {
419                    matches!(part, Part::FunctionCall { name, args, .. }
420                        if *name == request.tool_name && *args == request.args_redacted)
421                })
422            })
423        })?;
424        let mut reads = Reads {
425            // The agent that made the call, as the session names it.
426            agent: Some(asking.author.clone())
427                .filter(|author| !author.is_empty() && author != "user")
428                .or_else(|| {
429                    request.acting.as_ref().and_then(|acting| {
430                        acting.agent.id.as_str().rsplit('/').next().map(str::to_string)
431                    })
432                })
433                .unwrap_or_else(|| "The agent".to_string()),
434            pages: 0,
435            hosts: BTreeSet::new(),
436        };
437        let turn = events[..at].iter().filter(|event| event.invocation_id == asking.invocation_id);
438        for part in turn.filter_map(Event::content).flat_map(|content| content.parts.iter()) {
439            if let Part::FunctionResponse { function_response, .. } = part
440                && function_response.name == "web_fetch"
441                && let Some(host) = fetched(&function_response.response)
442            {
443                reads.pages += 1;
444                reads.hosts.extend(host);
445            }
446        }
447        let mut kept = self.reads.lock().unwrap_or_else(|e| e.into_inner());
448        if kept.len() >= KEPT_TURNS {
449            kept.clear();
450        }
451        kept.insert(request.id.clone(), reads.clone());
452        Some(reads)
453    }
454
455    /// "Finance read 1 web page (example.com)": the pages the agent fetched in the turn that
456    /// asked, named as the card names the agent.
457    async fn first_step(&self, request: &ApprovalRequest) -> Option<String> {
458        let reads = self.reads(request).await?;
459        if reads.pages == 0 {
460            return None;
461        }
462        let added = match &self.source {
463            Some(source) => source.agent(&request.scope.user_id, &reads.agent).await.ok().flatten(),
464            None => None,
465        };
466        let agent = match added {
467            Some(detail) => detail.agent.display_name,
468            None => self.registry.display_name(&reads.agent),
469        };
470        let what = match reads.pages {
471            1 => "1 web page".to_string(),
472            pages => format!("{pages} web pages"),
473        };
474        let hosts: Vec<String> = reads.hosts.into_iter().collect();
475        Some(match hosts.is_empty() {
476            true => format!("{agent} read {what}"),
477            false => format!("{agent} read {what} ({})", hosts.join(", ")),
478        })
479    }
480}
481
482/// For a `web_fetch` result that fetched a page, the host it was fetched from, when that is a
483/// host name; `None` for a call that was refused or failed.
484fn fetched(response: &serde_json::Value) -> Option<Option<String>> {
485    if response.get("error").is_some() || response.get("status").is_none() {
486        return None;
487    }
488    let url = response.get("final_url").or_else(|| response.get("url"))?.as_str()?;
489    let host = reqwest::Url::parse(url)
490        .ok()
491        .filter(|url| matches!(url.scheme(), "http" | "https"))
492        .and_then(|url| url.host_str().map(str::to_ascii_lowercase))
493        .filter(|host| !host.is_empty() && host.len() <= MAX_HOST);
494    Some(host)
495}
496
497/// Whether `request`'s summary is words a router wrote, not adk-core's default.
498fn written(request: &ApprovalRequest) -> bool {
499    let summary = request.summary.trim();
500    !(summary.is_empty()
501        || summary.starts_with(&format!("Tool '{}'", request.tool_name))
502        || summary == format!("Approve a call to '{}'", request.tool_name))
503}
504
505#[async_trait]
506impl CardHints for VerbHints {
507    async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
508        let origin = request.origin.as_ref()?;
509        if origin.source != self.registry.origin() {
510            return None;
511        }
512        let entry = self.registry.entry_for_tool(&request.tool_name)?;
513        let mut hint = CardHint::new()
514            .with_chat_heading(entry.spec.description.clone())
515            .without_always_allow()
516            .with_detail(CardDetail::new(words::AGENTS_ALWAYS_ASK));
517        if written(request) {
518            hint = hint.with_heading(request.summary.clone());
519        }
520        if entry.spec.reversible {
521            hint = hint.with_reversibility(Reversibility::CanBeChangedBack);
522        }
523        if let Some(step) = self.first_step(request).await {
524            hint = hint.with_first_step(step);
525        }
526        Some(hint)
527    }
528
529    /// The item's title, from the kernel's agenda; without it — a terminal attached to the
530    /// kernel, or an item that has ended — a snooze's card summary, which the kernel wrote,
531    /// still names it (spec 3.3 §8).
532    async fn names(&self, request: &ApprovalRequest) -> Option<String> {
533        let origin = request.origin.as_ref()?;
534        if origin.source != self.registry.origin() {
535            return None;
536        }
537        let entry = self.registry.entry_for_tool(&request.tool_name)?;
538        let id = request.args_redacted.get("item").and_then(serde_json::Value::as_str)?;
539        match self.registry.scope(&request.scope.user_id, None).item(id).await {
540            Ok(item) => Some(item.title),
541            Err(_) if entry.spec.name == "snooze" => {
542                words::title_of_move(&request.summary).map(str::to_string)
543            }
544            Err(_) => None,
545        }
546    }
547}