Skip to main content

adk_surface/verbs/
mod.rs

1//! Screen actions people and agents share (spec 3.3 §2 item 7, §5.6, §6.1 `verb-ui`;
2//! Experimental): one way to change something a surface shows — first, snoozing something in
3//! Coming up — from the home, the terminal, voice and an agent, always through the governed
4//! path.
5//!
6//! An action is declared once, as a [`VerbSpec`], with a [`VerbHandler`] that runs it, in a
7//! [`VerbRegistry`] over the kernel's agenda. Every caller reaches the same handler:
8//!
9//! | Caller | How | Governed as | Waits for a person |
10//! |---|---|---|---|
11//! | A person on the home, the terminal or by voice | [`VerbGate::call`] with the server-authenticated [`Caller`](crate::Caller) | `urn:adk:agent:<app>/surface.verbs`, acting for the person, through `authorize_tool_call` | No: the person is the one asking |
12//! | An agent | Its `verb_<name>` tool from [`VerbToolset`], published as `verbs:<app>` | The agent itself, with [`VerbPolicy`] in the operator layer | Yes, every call that changes something ([`VerbPolicy`]) |
13//!
14//! What no action can do (spec 3.3 §7.4, S-I4, S-I10, S-I11): a handler gets only a
15//! [`VerbScope`] — the caller's own agenda items and the one change of moving a wake later —
16//! so it can never answer a decision, change an agent, a standing rule, a mode or Stop all, or
17//! resume work. [`VerbRegistry`] refuses the names of those actions ([`RESERVED`]) and every
18//! object kind but [`ObjectKind::ComingUp`].
19//!
20//! | Piece | What it does |
21//! |---|---|
22//! | [`VerbRegistry`] | The catalogue — `coming_up` and `snooze` — and any action a host declares |
23//! | [`VerbGate`] | A person's call: the §7.2 row check, ownership (S-I8), the governed path, the `surface.verb` record |
24//! | [`VerbToolset`], [`VerbClasses`] | An agent's tools, `verb_<name>`, classed by their declared effect |
25//! | [`VerbPolicy`] | Holds every agent call that changes something, whatever the mode or standing rules (spec 3.2 K-I9 pattern); at most [`MAX_WAITING`] waiting per agent |
26//! | [`VerbRouter`] | The card of an agent's call: a kernel-text summary, its risk, Allow once · Edit · Deny |
27//! | [`VerbHints`] | The card's chat heading, "You can change it back", no **Always allow**, what the agent read first |
28//! | [`spoken`] | "Snooze news digest" by voice, after the engine's cancel window |
29//!
30//! Chat channels and the tray cannot take a screen action (spec 3.3 §7.2): "/snooze" typed in
31//! Telegram reaches the agent as text, and text an agent writes is never a command.
32//!
33//! # Example
34//!
35//! ```rust,no_run
36//! use std::sync::Arc;
37//! use adk_surface::verbs::{KernelAgenda, VerbRegistry};
38//!
39//! # fn example(kernel: &adk_kernel::Kernel) -> Result<(), adk_surface::verbs::VerbError> {
40//! let registry = VerbRegistry::builder("adk-rust", Arc::new(KernelAgenda::of(kernel))).build()?;
41//! assert!(registry.spec("snooze").is_some());
42//! assert_eq!(registry.origin(), "verbs:adk-rust");
43//! # Ok(())
44//! # }
45//! ```
46
47mod error;
48mod gate;
49mod policy;
50mod registry;
51mod snooze;
52pub mod spoken;
53mod terminal;
54mod tools;
55pub mod words;
56
57use adk_core::AgentPrincipal;
58use adk_kernel::drivers::EffectClass;
59use schemars::JsonSchema;
60use serde::{Deserialize, Serialize};
61use serde_json::{Value, json};
62
63pub use error::VerbError;
64pub use gate::VerbGate;
65pub use policy::{VERB_POLICY_REF, VerbHints, VerbPolicy, VerbRouter};
66pub use registry::{
67    AgendaAccess, KernelAgenda, VerbHandler, VerbRegistry, VerbRegistryBuilder, VerbScope,
68};
69pub use snooze::{ComingUpItem, SnoozeChoice, find_by_title};
70#[cfg(feature = "tui")]
71pub use terminal::SnoozeCommand;
72pub use terminal::{SnoozeText, parse_snooze, problem_line, snooze_text};
73pub use tools::{VerbClasses, VerbToolset};
74
75/// The agent name a person's own screen actions run under: `urn:adk:agent:<app>/surface.verbs`
76/// acting for the person (spec 3.3 §2 item 7, owner question 23).
77pub const VERBS_AGENT: &str = "surface.verbs";
78
79/// The audit action of a screen action taken (spec 3.3 §11).
80pub const SURFACE_AUDIT_VERB: &str = "surface.verb";
81
82/// The tool-name prefix of an action an agent calls: `verb_snooze`.
83pub const VERB_TOOL_PREFIX: &str = "verb_";
84
85/// The most actions one agent may have waiting for a person at once (owner question 22).
86pub const MAX_WAITING: usize = 3;
87
88/// The id a host's grant of screen actions carries on an agent's detail (spec 3.3 §5.7).
89pub const GRANT_ID: &str = "verb-ui";
90
91/// Names no screen action may take: answering a decision, changing an agent, governance and
92/// resuming work stay with the surfaces' own controls (spec 3.3 §7.4, S-I4, S-I10, S-I11).
93pub const RESERVED: &[&str] = &[
94    "approve",
95    "reject",
96    "allow",
97    "deny",
98    "decide",
99    "answer",
100    "always_allow",
101    "add_agent",
102    "change_agent",
103    "remove_agent",
104    "resume",
105    "resume_all",
106    "unfreeze",
107    "mount",
108];
109
110/// The publisher of every action tool of `app`: `verbs:<app>`, the [`ToolOrigin`](adk_core::ToolOrigin)
111/// source a card, a policy and a router tell them by (spec 3.3 §7.1).
112///
113/// # Example
114///
115/// ```rust
116/// assert_eq!(adk_surface::verbs::verbs_origin("adk-rust"), "verbs:adk-rust");
117/// ```
118pub fn verbs_origin(app: &str) -> String {
119    format!("verbs:{app}")
120}
121
122/// The principal a person's screen actions run under: `urn:adk:agent:<app>/surface.verbs`.
123///
124/// # Example
125///
126/// ```rust
127/// let principal = adk_surface::verbs::verbs_principal("adk-rust");
128/// assert_eq!(principal.id.as_str(), "urn:adk:agent:adk-rust/surface.verbs");
129/// ```
130pub fn verbs_principal(app: &str) -> AgentPrincipal {
131    AgentPrincipal::derived(app, VERBS_AGENT)
132}
133
134/// What a screen action acts on (spec 3.3 §2 item 7). This wave allows only Coming up.
135///
136/// # Example
137///
138/// ```rust
139/// use adk_surface::verbs::ObjectKind;
140///
141/// assert_eq!(serde_json::to_value(ObjectKind::ComingUp).unwrap(), "comingUp");
142/// ```
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
144#[serde(rename_all = "camelCase")]
145pub enum ObjectKind {
146    /// Something in Coming up: an agenda item scheduled to run (spec 3.3 §5.1).
147    ComingUp,
148}
149
150/// The object kinds a [`VerbSpec`] may name this wave.
151pub const ALLOWED_OBJECTS: &[ObjectKind] = &[ObjectKind::ComingUp];
152
153/// One thing an action acts on (spec 3.3 §2 item 7).
154///
155/// # Example
156///
157/// ```rust
158/// use adk_surface::verbs::{ObjectKind, ObjectRef};
159///
160/// let item = ObjectRef::coming_up("agenda-7f3");
161/// assert_eq!(serde_json::to_value(&item).unwrap(), serde_json::json!({ "kind": "comingUp", "id": "agenda-7f3" }));
162/// assert_eq!(item.kind, ObjectKind::ComingUp);
163/// ```
164#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
165#[serde(rename_all = "camelCase")]
166pub struct ObjectRef {
167    /// What kind of thing.
168    pub kind: ObjectKind,
169    /// Its id: the agenda item's id for Coming up.
170    pub id: String,
171}
172
173impl ObjectRef {
174    /// The Coming up item `id`.
175    pub fn coming_up(id: impl Into<String>) -> Self {
176        Self { kind: ObjectKind::ComingUp, id: id.into() }
177    }
178}
179
180/// Who may take an action (spec 3.3 §2 item 7).
181#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
182#[serde(rename_all = "camelCase")]
183pub enum Callers {
184    /// Only a person, through a surface: an agent's call is refused.
185    PersonOnly,
186    /// A person, and an agent through its tool, every changing call waiting for a person.
187    PersonAndAgents,
188}
189
190/// One screen action, declared once for every caller (spec 3.3 §2 item 7, §6.1).
191///
192/// # Example
193///
194/// ```rust
195/// use adk_kernel::drivers::EffectClass;
196/// use adk_surface::verbs::{Callers, ObjectKind, VerbSpec};
197///
198/// let snooze = VerbSpec::new("snooze", "Snooze", "Snooze something in Coming up", EffectClass::WriteLocal)
199///     .with_objects([ObjectKind::ComingUp])
200///     .with_callers(Callers::PersonAndAgents)
201///     .only_delays()
202///     .reversible()
203///     .with_voice_phrase("snooze");
204/// assert_eq!(snooze.tool_name(), "verb_snooze");
205/// assert!(snooze.only_delays);
206/// ```
207#[derive(Debug, Clone, PartialEq)]
208pub struct VerbSpec {
209    /// The name: `^[a-z][a-z0-9_]{0,58}$`, never one of [`RESERVED`].
210    pub name: String,
211    /// The button's words: "Snooze".
212    pub label: String,
213    /// What it does, in plain words, for a person and for the model: "Snooze something in
214    /// Coming up". Also the chat heading of an agent's card.
215    pub description: String,
216    /// What it acts on; an allowlist, of [`ALLOWED_OBJECTS`] only.
217    pub objects: Vec<ObjectKind>,
218    /// The JSON Schema of its arguments, the tool's parameters.
219    pub args: Value,
220    /// What it changes, as a driver tool's manifest says it.
221    pub effect: EffectClass,
222    /// Who may take it.
223    pub callers: Callers,
224    /// It only delays work: a person may take it while everything is stopped (owner question
225    /// 23).
226    pub only_delays: bool,
227    /// It can be changed back: its card says "You can change it back".
228    pub reversible: bool,
229    /// The words that start it by voice, such as "snooze"; `None`: not by voice.
230    pub voice_phrase: Option<String>,
231}
232
233impl VerbSpec {
234    /// An action `name` with no objects and no arguments, for a person only.
235    pub fn new(
236        name: impl Into<String>,
237        label: impl Into<String>,
238        description: impl Into<String>,
239        effect: EffectClass,
240    ) -> Self {
241        Self {
242            name: name.into(),
243            label: label.into(),
244            description: description.into(),
245            objects: Vec::new(),
246            args: json!({ "type": "object", "properties": {} }),
247            effect,
248            callers: Callers::PersonOnly,
249            only_delays: false,
250            reversible: false,
251            voice_phrase: None,
252        }
253    }
254
255    /// Acts on `objects`.
256    #[must_use]
257    pub fn with_objects(mut self, objects: impl IntoIterator<Item = ObjectKind>) -> Self {
258        self.objects = objects.into_iter().collect();
259        self
260    }
261
262    /// Takes arguments of the JSON Schema `schema`.
263    #[must_use]
264    pub fn with_args(mut self, schema: Value) -> Self {
265        self.args = schema;
266        self
267    }
268
269    /// May be taken by `callers`.
270    #[must_use]
271    pub fn with_callers(mut self, callers: Callers) -> Self {
272        self.callers = callers;
273        self
274    }
275
276    /// Only delays work, so it still runs while everything is stopped.
277    #[must_use]
278    pub fn only_delays(mut self) -> Self {
279        self.only_delays = true;
280        self
281    }
282
283    /// Can be changed back.
284    #[must_use]
285    pub fn reversible(mut self) -> Self {
286        self.reversible = true;
287        self
288    }
289
290    /// Starts by voice with `phrase`.
291    #[must_use]
292    pub fn with_voice_phrase(mut self, phrase: impl Into<String>) -> Self {
293        self.voice_phrase = Some(phrase.into());
294        self
295    }
296
297    /// The tool an agent calls it by: `verb_<name>`.
298    pub fn tool_name(&self) -> String {
299        format!("{VERB_TOOL_PREFIX}{}", self.name)
300    }
301
302    /// Whether it only reads.
303    pub fn reads(&self) -> bool {
304        self.effect == EffectClass::Read
305    }
306}
307
308/// A request to take an action (spec 3.3 §2 item 7): the shape of agentrix's `VerbIntent`,
309/// re-declared. It carries no origin and no surface: those come from the server-authenticated
310/// [`Caller`](crate::Caller).
311///
312/// The arguments are the action's own; an object the action acts on fills the argument
313/// `item` when the arguments leave it out.
314///
315/// # Example
316///
317/// ```rust
318/// use adk_surface::verbs::{ObjectRef, VerbIntent};
319///
320/// let intent: VerbIntent = serde_json::from_value(serde_json::json!({
321///     "verb": "snooze",
322///     "objects": [{ "kind": "comingUp", "id": "agenda-7f3" }],
323///     "args": { "to": "2026-10-26T19:00:00+03:00" },
324/// }))
325/// .unwrap();
326/// assert_eq!(intent.objects, vec![ObjectRef::coming_up("agenda-7f3")]);
327/// assert_eq!(intent.call_args()["item"], "agenda-7f3");
328/// ```
329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
330#[serde(rename_all = "camelCase")]
331pub struct VerbIntent {
332    /// The action's name.
333    pub verb: String,
334    /// What it acts on.
335    #[serde(default)]
336    pub objects: Vec<ObjectRef>,
337    /// The record's target, `agenda:<id>`; filled from `objects` when absent.
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub target: Option<String>,
340    /// Its arguments.
341    #[serde(default)]
342    pub args: Value,
343}
344
345impl VerbIntent {
346    /// An intent to take `verb` with `args`.
347    pub fn new(verb: impl Into<String>, args: Value) -> Self {
348        Self { verb: verb.into(), objects: Vec::new(), target: None, args }
349    }
350
351    /// Acts on `object` too.
352    #[must_use]
353    pub fn on(mut self, object: ObjectRef) -> Self {
354        self.objects.push(object);
355        self
356    }
357
358    /// The arguments the handler runs with: `args`, with `item` from the first object when
359    /// `args` names none.
360    pub fn call_args(&self) -> Value {
361        let mut args = match &self.args {
362            Value::Object(map) => map.clone(),
363            _ => serde_json::Map::new(),
364        };
365        if !args.contains_key("item")
366            && let Some(object) = self.objects.first()
367        {
368            args.insert("item".to_string(), json!(object.id));
369        }
370        Value::Object(args)
371    }
372}
373
374/// One action of the catalogue, as `GET /surface/verbs` lists it (spec 3.3 §6.1).
375///
376/// # Example
377///
378/// ```rust
379/// use adk_surface::verbs::VerbView;
380///
381/// let view: VerbView = serde_json::from_value(serde_json::json!({
382///     "name": "snooze", "label": "Snooze", "description": "Snooze something in Coming up",
383///     "objects": ["comingUp"], "effect": "write_local", "agentsAsk": true,
384///     "onlyDelays": true, "reversible": true,
385/// }))
386/// .unwrap();
387/// assert!(view.agents_ask);
388/// ```
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
390#[serde(rename_all = "camelCase")]
391pub struct VerbView {
392    /// The name.
393    pub name: String,
394    /// The button's words.
395    pub label: String,
396    /// What it does.
397    pub description: String,
398    /// What it acts on.
399    pub objects: Vec<ObjectKind>,
400    /// What it changes: `read`, `write_local`, …
401    pub effect: String,
402    /// Agents may ask for it; it always waits for a person when it changes something.
403    pub agents_ask: bool,
404    /// It only delays work, so it still runs while everything is stopped.
405    pub only_delays: bool,
406    /// It can be changed back.
407    pub reversible: bool,
408}
409
410impl From<&VerbSpec> for VerbView {
411    fn from(spec: &VerbSpec) -> Self {
412        Self {
413            name: spec.name.clone(),
414            label: spec.label.clone(),
415            description: spec.description.clone(),
416            objects: spec.objects.clone(),
417            effect: spec.effect.to_string(),
418            agents_ask: spec.callers == Callers::PersonAndAgents,
419            only_delays: spec.only_delays,
420            reversible: spec.reversible,
421        }
422    }
423}
424
425/// What an action did (spec 3.3 §2 item 7): shown once it ran, never before.
426///
427/// # Example
428///
429/// ```rust
430/// use adk_surface::verbs::VerbDone;
431///
432/// let done = VerbDone::new("snooze", "Moved News digest to 19:00")
433///     .with_target("agenda:agenda-7f3", "News digest");
434/// assert_eq!(done.target.as_deref(), Some("agenda:agenda-7f3"));
435/// ```
436#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
437#[serde(rename_all = "camelCase")]
438pub struct VerbDone {
439    /// The action.
440    pub verb: String,
441    /// What it acted on: `agenda:<id>`.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub target: Option<String>,
444    /// What it acted on, in plain words: the item's title.
445    #[serde(default, skip_serializing_if = "Option::is_none")]
446    pub title: Option<String>,
447    /// What happened, in plain words: "Moved News digest to 19:00".
448    pub text: String,
449    /// What a read returned, or the changed thing; `null` when nothing more.
450    #[serde(default)]
451    pub result: Value,
452}
453
454impl VerbDone {
455    /// `verb` did `text`.
456    pub fn new(verb: impl Into<String>, text: impl Into<String>) -> Self {
457        Self {
458            verb: verb.into(),
459            target: None,
460            title: None,
461            text: text.into(),
462            result: Value::Null,
463        }
464    }
465
466    /// It acted on `target`, titled `title`.
467    #[must_use]
468    pub fn with_target(mut self, target: impl Into<String>, title: impl Into<String>) -> Self {
469        self.target = Some(target.into());
470        self.title = Some(title.into());
471        self
472    }
473
474    /// It returned `result`.
475    #[must_use]
476    pub fn with_result(mut self, result: Value) -> Self {
477        self.result = result;
478        self
479    }
480}
481
482/// Whether `name` may name a screen action: `^[a-z][a-z0-9_]{0,58}$` and none of
483/// [`RESERVED`].
484///
485/// # Errors
486///
487/// [`VerbError::Invalid`] for a name outside the pattern, [`VerbError::Reserved`] for a
488/// reserved one.
489///
490/// # Example
491///
492/// ```rust
493/// use adk_surface::verbs::check_name;
494///
495/// assert!(check_name("snooze").is_ok());
496/// assert_eq!(check_name("approve").unwrap_err().code(), "surface.verb.reserved");
497/// assert_eq!(check_name("Snooze").unwrap_err().code(), "surface.verb.invalid");
498/// ```
499pub fn check_name(name: &str) -> Result<(), VerbError> {
500    let mut chars = name.chars();
501    let shaped = name.len() <= 59
502        && chars.next().is_some_and(|first| first.is_ascii_lowercase())
503        && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
504    if !shaped {
505        return Err(VerbError::invalid(format!(
506            "`{name}` is not a screen action's name: use 1 to 59 lower-case letters, digits and \
507             underscores, starting with a letter"
508        )));
509    }
510    if RESERVED.contains(&name) {
511        return Err(VerbError::Reserved { name: name.to_string() });
512    }
513    Ok(())
514}