1use 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
24pub const VERB_POLICY_REF: &str = "adk-surface/verbs";
26
27#[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 async fn waiting(&self, agent: &AgentId, user: &str) -> usize {
70 let registry = self.registry.inner();
71 let Some(store) = ®istry.approvals else {
72 return 0;
73 };
74 let query = ApprovalRequestQuery::default()
75 .with_states([ApprovalState::Pending])
76 .with_app_name(®istry.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 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
132pub(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#[derive(Clone)]
226pub struct VerbRouter {
227 origin: String,
228 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 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
275fn 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
286fn 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#[derive(Clone)]
341pub struct VerbHints {
342 registry: VerbRegistry,
343 source: Option<Arc<dyn Source>>,
344 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#[derive(Debug, Clone)]
359struct Reads {
360 agent: String,
362 pages: usize,
364 hosts: BTreeSet<String>,
366}
367
368const KEPT_TURNS: usize = 512;
370
371const 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 #[must_use]
384 pub fn reading(mut self, source: Arc<dyn Source>) -> Self {
385 self.source = Some(source);
386 self
387 }
388
389 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 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 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 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 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
482fn 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
497fn 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 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}