Skip to main content

adk_surface/verbs/
tools.rs

1//! An agent's screen-action tools, `verb_<name>`, published as `verbs:<app>` (spec 3.3 §2
2//! item 7, §7.1).
3
4use std::sync::Arc;
5
6use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
7use adk_core::{
8    AdkError, ApprovalRequest, ApprovalRequestQuery, ApprovalScope, ApprovalState, ReadonlyContext,
9    Tool, ToolConfirmationRequest, ToolContext, ToolEffect, Toolset,
10};
11use adk_harness::{OriginClasses, ToolKind, driver_tool_kind};
12use adk_kernel::PartitionId;
13use adk_kernel::drivers::EffectClass;
14use async_trait::async_trait;
15use serde_json::{Value, json};
16
17use super::registry::VerbRegistry;
18use super::{Callers, SURFACE_AUDIT_VERB, VerbDone, VerbError, VerbSpec};
19
20/// The tools of the screen actions agents may ask for, for one agent's area (spec 3.3 §2 item
21/// 7): `verb_coming_up` reads, `verb_snooze` asks the person every time ([`VerbPolicy`](super::VerbPolicy)).
22///
23/// An agent sees only its own area's items. Attach the toolset, [`VerbClasses`] and
24/// [`VerbPolicy`](super::VerbPolicy) together, as `kernel_drivers` attaches a driver's:
25///
26/// ```rust,ignore
27/// let agent = HarnessAgent::builder("finance")
28///     .toolset(Arc::new(registry.toolset("work")))
29///     .tool_classes(Arc::new(registry.classes()))
30///     .add_operator_policy(Arc::new(registry.policy("work")))
31///     .build()?;
32/// ```
33///
34/// # Example
35///
36/// ```rust,no_run
37/// use adk_core::Toolset;
38///
39/// # fn example(registry: adk_surface::verbs::VerbRegistry) {
40/// let toolset = registry.toolset("work");
41/// assert_eq!(toolset.name(), "verbs");
42/// # }
43/// ```
44#[derive(Debug, Clone)]
45pub struct VerbToolset {
46    registry: VerbRegistry,
47    area: PartitionId,
48}
49
50impl VerbToolset {
51    pub(crate) fn new(registry: VerbRegistry, area: PartitionId) -> Self {
52        Self { registry, area }
53    }
54
55    /// The tools, one per action an agent may ask for.
56    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
57        self.registry
58            .entries()
59            .iter()
60            .filter(|entry| entry.spec.callers == Callers::PersonAndAgents)
61            .map(|entry| {
62                Arc::new(VerbTool::new(&self.registry, &entry.spec, Some(self.area.clone())))
63                    as Arc<dyn Tool>
64            })
65            .collect()
66    }
67}
68
69#[async_trait]
70impl Toolset for VerbToolset {
71    fn name(&self) -> &str {
72        "verbs"
73    }
74
75    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> adk_core::Result<Vec<Arc<dyn Tool>>> {
76        Ok(VerbToolset::tools(self))
77    }
78}
79
80/// One action as a tool. The person's own calls are governed through the same declaration,
81/// so a decision's origin digest is the same whoever calls.
82pub(crate) struct VerbTool {
83    registry: VerbRegistry,
84    verb: String,
85    tool_name: String,
86    description: String,
87    parameters: Value,
88    origin: String,
89    effect: EffectClass,
90    area: Option<PartitionId>,
91}
92
93impl VerbTool {
94    pub(crate) fn new(registry: &VerbRegistry, spec: &VerbSpec, area: Option<PartitionId>) -> Self {
95        Self {
96            registry: registry.clone(),
97            verb: spec.name.clone(),
98            tool_name: spec.tool_name(),
99            description: spec.description.clone(),
100            parameters: spec.args.clone(),
101            origin: registry.origin(),
102            effect: spec.effect,
103            area,
104        }
105    }
106
107    /// The record of an agent's call that changed, or tried to change, something (spec 3.3
108    /// §11): the agent and invocation as its actor, how the person said yes when they did.
109    async fn record(
110        &self,
111        ctx: &dyn ToolContext,
112        args: &Value,
113        outcome: Result<&VerbDone, &VerbError>,
114    ) {
115        let registry = self.registry.inner();
116        let Some(trail) = &registry.audit else {
117            return;
118        };
119        let acting = ctx.acting_context();
120        let mut draft =
121            AuditRecordDraft::new(AuditRecordKind::Other("surface".into()), SURFACE_AUDIT_VERB)
122                .actor(AuditActor::new(&acting, ctx.invocation_id()))
123                .ext("origin", json!({ "kind": "agent", "agent": ctx.agent_name() }))
124                .ext("verb", json!(self.verb))
125                .ext("argsDigest", json!(trail.digest(args)))
126                .ext("effect", json!(self.effect.to_string()))
127                .ext("functionCallId", json!(ctx.function_call_id()))
128                .ext("sessionId", json!(ctx.session_id()));
129        draft = match outcome {
130            Ok(done) => {
131                let mut draft = draft.ext("outcome", json!("done"));
132                if let Some(target) = &done.target {
133                    draft = draft.ext("target", json!(target));
134                }
135                if let Some(title) = &done.title {
136                    draft = draft.ext("title", json!(title));
137                }
138                draft
139            }
140            Err(error) => {
141                let item = args.get("item").and_then(Value::as_str);
142                let mut draft = draft
143                    .ext("outcome", json!("refused"))
144                    .ext("code", json!(error.code()))
145                    .ext("target", json!(item.map(|id| format!("agenda:{id}"))));
146                // The item's title, so the record names it as the person knows it (§8).
147                let scope = self.registry.scope(ctx.user_id(), self.area.clone());
148                if let Some(id) = item
149                    && let Ok(found) = scope.item(id).await
150                {
151                    draft = draft.ext("title", json!(found.title));
152                }
153                draft
154            }
155        };
156        if let Some((approval, answered)) = self.answered(ctx, args).await {
157            draft = draft.ext("approvalId", json!(approval));
158            if let Some(answered) = answered {
159                draft = draft.ext("answered", answered);
160            }
161        }
162        if let Err(error) = trail.record(draft).await {
163            tracing::warn!(error = %error, verb = %self.verb, "the screen action's record failed");
164        }
165    }
166
167    /// The decision that let this call with `args` run, and where the person gave it, when
168    /// the registry reads the inbox: the approved request of this session for this very call —
169    /// its fingerprint, or the arguments the person's Edit gave it — the newest if several.
170    async fn answered(
171        &self,
172        ctx: &dyn ToolContext,
173        args: &Value,
174    ) -> Option<(String, Option<Value>)> {
175        let registry = self.registry.inner();
176        let store = registry.approvals.as_ref()?;
177        let scope = ApprovalScope::new(&registry.app, ctx.user_id(), ctx.session_id());
178        let acting = ctx.acting_context();
179        let fingerprint = ToolConfirmationRequest::for_tool(self, args.clone())
180            .with_acting_context(acting.clone())
181            .fingerprint();
182        let this_call = |request: &ApprovalRequest| {
183            request.tool_name == self.tool_name
184                && request.origin.as_ref().is_some_and(|origin| origin.source == self.origin)
185                && request.acting.as_ref().is_some_and(|by| by.agent.id == acting.agent.id)
186                && (request.fingerprint == fingerprint
187                    || request
188                        .decisions
189                        .last()
190                        .and_then(|decision| decision.edited_args.as_ref())
191                        .is_some_and(|edited| edited == args))
192        };
193        let query = ApprovalRequestQuery::default()
194            .with_session(&scope)
195            .with_states([ApprovalState::Approved]);
196        let mut found: Option<ApprovalRequest> = None;
197        super::policy::every_request(store.as_ref(), query, |request| {
198            if this_call(request)
199                && found.as_ref().is_none_or(|newest| request.resolved_at > newest.resolved_at)
200            {
201                found = Some(request.clone());
202            }
203            false
204        })
205        .await
206        .ok()?;
207        let request = found?;
208        let answered = match &registry.answers {
209            Some(answers) => answers.find(&request.id).await.ok().flatten().map(|record| {
210                json!({
211                    "surface": record.via.surface,
212                    "origin": record.via.origin,
213                    "answer": record.answer,
214                })
215            }),
216            None => None,
217        };
218        Some((request.id, answered))
219    }
220}
221
222#[async_trait]
223impl Tool for VerbTool {
224    fn name(&self) -> &str {
225        &self.tool_name
226    }
227
228    fn description(&self) -> &str {
229        &self.description
230    }
231
232    fn parameters_schema(&self) -> Option<Value> {
233        Some(self.parameters.clone())
234    }
235
236    fn origin(&self) -> &str {
237        &self.origin
238    }
239
240    fn effect(&self) -> ToolEffect {
241        self.effect.tool_effect()
242    }
243
244    fn is_read_only(&self) -> bool {
245        self.effect == EffectClass::Read
246    }
247
248    fn is_concurrency_safe(&self) -> bool {
249        self.effect == EffectClass::Read
250    }
251
252    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
253        let Some(entry) = self.registry.entry(&self.verb) else {
254            return Err(VerbError::Unknown { verb: self.verb.clone() }.into());
255        };
256        let scope = self.registry.scope(ctx.user_id(), self.area.clone());
257        let reads = entry.spec.reads();
258        match entry.handler.run(&scope, &args).await {
259            Ok(done) => {
260                if !reads {
261                    self.record(ctx.as_ref(), &args, Ok(&done)).await;
262                }
263                Ok(json!({ "status": "done", "text": done.text, "result": done.result }))
264            }
265            Err(error) => {
266                if !reads {
267                    self.record(ctx.as_ref(), &args, Err(&error)).await;
268                }
269                Err(AdkError::from(error))
270            }
271        }
272    }
273}
274
275/// The classes of the action tools, from their declared effects (spec 3.2 §7.7): a read is a
276/// trusted read-only tool, every other action a trusted tool with effects, which the modes ask
277/// about — and which [`VerbPolicy`](super::VerbPolicy) holds whatever the mode.
278///
279/// # Example
280///
281/// ```rust,no_run
282/// use adk_harness::OriginClasses;
283///
284/// # fn example(registry: adk_surface::verbs::VerbRegistry) {
285/// let classes = registry.classes();
286/// assert!(classes.class_of("verbs:adk-rust", "verb_snooze").is_some());
287/// assert!(classes.class_of("mcp:calendar", "verb_snooze").is_none());
288/// # }
289/// ```
290#[derive(Debug, Clone)]
291pub struct VerbClasses {
292    registry: VerbRegistry,
293}
294
295impl VerbClasses {
296    pub(crate) fn new(registry: VerbRegistry) -> Self {
297        Self { registry }
298    }
299}
300
301impl OriginClasses for VerbClasses {
302    fn class_of(&self, source: &str, tool: &str) -> Option<ToolKind> {
303        if source != self.registry.origin() {
304            return None;
305        }
306        self.registry.entry_for_tool(tool).map(|entry| driver_tool_kind(entry.spec.effect))
307    }
308}