Skip to main content

adk_surface/verbs/
registry.rs

1//! The catalogue of screen actions, the agenda they act on, and the one narrow scope a handler
2//! gets (spec 3.3 §2 item 7, S-I4, S-I10, S-I11).
3
4use std::collections::HashMap;
5use std::fmt;
6use std::sync::Arc;
7
8use adk_core::audit_log::AuditTrail;
9use adk_core::principal::SubjectRef;
10use adk_core::{ApprovalRouter, ApprovalStore, Clock, GovernanceControl, RunState, SystemClock};
11use adk_kernel::{
12    Agenda, AgendaFilter, AgendaHandle, AgendaItem, AgendaState, AgendaStateKind, Kernel,
13    PartitionId, ProcessFilter, ProcessKind, ProcessTable, Wake, WakeSet,
14};
15use adk_session::SessionService;
16use async_trait::async_trait;
17use chrono::{DateTime, FixedOffset, Local, Utc};
18use serde_json::Value;
19
20use super::policy::{VerbHints, VerbPolicy, VerbRouter};
21use super::tools::{VerbClasses, VerbToolset};
22use super::{
23    ALLOWED_OBJECTS, GRANT_ID, VerbDone, VerbError, VerbSpec, VerbView, check_name, snooze, words,
24};
25use crate::agents::GrantedUse;
26use crate::answers::AnswerLog;
27
28/// The kernel's agenda as screen actions read and change it (spec 3.3 §2 item 7): over
29/// `Kernel::agenda()` in process, or a host's own reach.
30///
31/// # Example
32///
33/// ```rust,no_run
34/// use std::sync::Arc;
35/// use adk_surface::verbs::{AgendaAccess, KernelAgenda};
36///
37/// # fn example(kernel: &adk_kernel::Kernel) {
38/// let agenda: Arc<dyn AgendaAccess> = Arc::new(KernelAgenda::of(kernel));
39/// # let _ = agenda;
40/// # }
41/// ```
42#[async_trait]
43pub trait AgendaAccess: Send + Sync {
44    /// The open items of `subject` that are scheduled or running, in `area` when one is
45    /// named, oldest first.
46    ///
47    /// # Errors
48    ///
49    /// The kernel's or the store's error.
50    async fn items(
51        &self,
52        subject: &str,
53        area: Option<&PartitionId>,
54    ) -> Result<Vec<AgendaItem>, VerbError>;
55
56    /// The item `id`, whoever's it is.
57    ///
58    /// # Errors
59    ///
60    /// The kernel's or the store's error.
61    async fn item(&self, id: &str) -> Result<Option<AgendaItem>, VerbError>;
62
63    /// Whether `item`'s process runs, or is queued to run next: about to start, or started. A
64    /// process queued, or claimed, only to park on its wake has not started.
65    ///
66    /// # Errors
67    ///
68    /// The kernel's or the store's error.
69    async fn started(&self, item: &AgendaItem) -> Result<bool, VerbError>;
70
71    /// Has item `id`'s sleeping process wake on `wake` instead, as `by` (`Agenda::schedule`).
72    ///
73    /// # Errors
74    ///
75    /// The kernel's refusal, such as an item whose process started, or the store's error.
76    async fn reschedule(
77        &self,
78        id: &str,
79        wake: WakeSet,
80        by: &SubjectRef,
81    ) -> Result<AgendaItem, VerbError>;
82}
83
84/// The agenda of a kernel in this process (spec 3.2 §7.5).
85///
86/// [`of`](Self::of) reads a running kernel; [`new`](Self::new) reads through an
87/// [`AgendaHandle`] bound when the kernel is built, so a host can give the agents their tools
88/// before the kernel that hosts them exists, without the tools keeping it alive.
89///
90/// # Example
91///
92/// ```rust,no_run
93/// use std::sync::Arc;
94/// use adk_kernel::{AgendaHandle, InMemoryProcessStore, ProcessTable};
95/// use adk_surface::verbs::KernelAgenda;
96///
97/// # fn example(runs: Arc<dyn adk_core::DurableRunStore>) {
98/// let handle = AgendaHandle::new();
99/// let processes = ProcessTable::new(runs, Arc::new(InMemoryProcessStore::new()));
100/// let agenda = KernelAgenda::new(handle.clone(), processes);
101/// // ... KernelBuilder::agenda_handle(handle) binds it when the kernel is built.
102/// # let _ = agenda;
103/// # }
104/// ```
105#[derive(Clone)]
106pub struct KernelAgenda {
107    agenda: Slot,
108    processes: ProcessTable,
109}
110
111#[derive(Clone)]
112enum Slot {
113    Handle(AgendaHandle),
114    Bound(Agenda),
115}
116
117impl fmt::Debug for KernelAgenda {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        let bound = match &self.agenda {
120            Slot::Handle(handle) => handle.get().is_some(),
121            Slot::Bound(_) => true,
122        };
123        f.debug_struct("KernelAgenda").field("bound", &bound).finish_non_exhaustive()
124    }
125}
126
127impl KernelAgenda {
128    /// The agenda of `kernel`.
129    pub fn of(kernel: &Kernel) -> Self {
130        Self { agenda: Slot::Bound(kernel.agenda().clone()), processes: kernel.processes().clone() }
131    }
132
133    /// The agenda of the kernel `handle` is bound to when it is built, with its processes in
134    /// `processes`.
135    pub fn new(handle: AgendaHandle, processes: ProcessTable) -> Self {
136        Self { agenda: Slot::Handle(handle), processes }
137    }
138
139    fn agenda(&self) -> Result<Agenda, VerbError> {
140        match &self.agenda {
141            Slot::Bound(agenda) => Ok(agenda.clone()),
142            Slot::Handle(handle) => handle.get().ok_or_else(|| {
143                VerbError::refused("Coming up isn't available: the kernel is not running")
144            }),
145        }
146    }
147}
148
149#[async_trait]
150impl AgendaAccess for KernelAgenda {
151    async fn items(
152        &self,
153        subject: &str,
154        area: Option<&PartitionId>,
155    ) -> Result<Vec<AgendaItem>, VerbError> {
156        let mut filter =
157            AgendaFilter::default().states([AgendaStateKind::Scheduled, AgendaStateKind::Running]);
158        if let Some(area) = area {
159            filter = filter.partition(area.clone());
160        }
161        let items = self.agenda()?.list(&filter).await?;
162        Ok(items.into_iter().filter(|item| item.subject.id == subject).collect())
163    }
164
165    async fn item(&self, id: &str) -> Result<Option<AgendaItem>, VerbError> {
166        Ok(self.agenda()?.get(id).await?)
167    }
168
169    async fn started(&self, item: &AgendaItem) -> Result<bool, VerbError> {
170        let filter = ProcessFilter::default().partition(item.partition.clone());
171        let processes = self.processes.ps(filter).await?;
172        // A process queued or claimed with its wake set still on its row parks on it before
173        // its first model call (K-I2): it has not started. Without one, it runs.
174        Ok(processes.iter().any(|process| {
175            process.meta.agenda_item.as_deref() == Some(item.id.as_str())
176                && process.meta.kind == ProcessKind::Proposed
177                && match process.run.state {
178                    RunState::Running | RunState::Queued => process.meta.wake.is_none(),
179                    _ => false,
180                }
181        }))
182    }
183
184    async fn reschedule(
185        &self,
186        id: &str,
187        wake: WakeSet,
188        by: &SubjectRef,
189    ) -> Result<AgendaItem, VerbError> {
190        Ok(self.agenda()?.schedule(id, wake, by).await?)
191    }
192}
193
194/// No agenda: a process that only draws the cards of another process's actions.
195struct NoAgenda;
196
197impl NoAgenda {
198    fn refused() -> VerbError {
199        VerbError::refused("Coming up isn't available here — use the home")
200    }
201}
202
203#[async_trait]
204impl AgendaAccess for NoAgenda {
205    async fn items(&self, _: &str, _: Option<&PartitionId>) -> Result<Vec<AgendaItem>, VerbError> {
206        Err(Self::refused())
207    }
208
209    async fn item(&self, _: &str) -> Result<Option<AgendaItem>, VerbError> {
210        Err(Self::refused())
211    }
212
213    async fn started(&self, _: &AgendaItem) -> Result<bool, VerbError> {
214        Err(Self::refused())
215    }
216
217    async fn reschedule(
218        &self,
219        _: &str,
220        _: WakeSet,
221        _: &SubjectRef,
222    ) -> Result<AgendaItem, VerbError> {
223        Err(Self::refused())
224    }
225}
226
227/// Runs one screen action (spec 3.3 §2 item 7).
228///
229/// A handler gets a [`VerbScope`] and nothing else: no approval service, agent table, rules,
230/// modes or governance, so no action can answer a decision, change an agent, a rule, a mode or
231/// Stop all, or resume work (S-I4, S-I10, S-I11).
232///
233/// # Example
234///
235/// ```rust
236/// use adk_surface::verbs::{VerbDone, VerbError, VerbHandler, VerbScope};
237/// use serde_json::Value;
238///
239/// /// Lists the titles in Coming up.
240/// struct Titles;
241///
242/// #[async_trait::async_trait]
243/// impl VerbHandler for Titles {
244///     async fn describe(&self, _scope: &VerbScope, _args: &Value) -> Result<String, VerbError> {
245///         Ok("List what is coming up".into())
246///     }
247///
248///     async fn run(&self, scope: &VerbScope, _args: &Value) -> Result<VerbDone, VerbError> {
249///         let titles: Vec<String> = scope.items().await?.into_iter().map(|item| item.title).collect();
250///         Ok(VerbDone::new("titles", titles.join(", ")))
251///     }
252/// }
253/// ```
254#[async_trait]
255pub trait VerbHandler: Send + Sync {
256    /// What the call with `args` would do, in kernel text read from the agenda, for the card's
257    /// heading: "Move News digest to 19:00".
258    ///
259    /// # Errors
260    ///
261    /// The refusal the call would meet: something not found, not possible now, or arguments
262    /// the action refuses. An agent's call that fails here is refused before any card.
263    async fn describe(&self, scope: &VerbScope, args: &Value) -> Result<String, VerbError>;
264
265    /// Runs the call with `args`.
266    ///
267    /// # Errors
268    ///
269    /// Why it was refused, or the kernel's error.
270    async fn run(&self, scope: &VerbScope, args: &Value) -> Result<VerbDone, VerbError>;
271}
272
273/// What a handler may read and change: the caller's own agenda items — for an agent, only its
274/// own area's — and moving one's wake later (spec 3.3 §2 item 7, S-I8).
275///
276/// It holds no handle to the approval service, the agent table, standing rules, modes or
277/// governance:
278///
279/// ```rust,compile_fail
280/// # async fn example(scope: adk_surface::verbs::VerbScope) {
281/// // A handler cannot reach the inbox.
282/// scope.approvals().decide("apr_1", 1, todo!()).await;
283/// # }
284/// ```
285#[derive(Clone)]
286pub struct VerbScope {
287    subject: SubjectRef,
288    area: Option<PartitionId>,
289    agenda: Arc<dyn AgendaAccess>,
290    now: DateTime<Utc>,
291    offset: FixedOffset,
292    /// Held from reading a wake to moving it, so two moves of this registry never both pass
293    /// their checks against the same wake.
294    moving: Arc<tokio::sync::Mutex<()>>,
295}
296
297impl fmt::Debug for VerbScope {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        f.debug_struct("VerbScope")
300            .field("subject", &self.subject)
301            .field("area", &self.area)
302            .field("now", &self.now)
303            .finish_non_exhaustive()
304    }
305}
306
307impl VerbScope {
308    /// The person whose items these are.
309    pub fn subject(&self) -> &SubjectRef {
310        &self.subject
311    }
312
313    /// The area an agent's call is confined to; `None` for a person, who sees every area.
314    pub fn area(&self) -> Option<&PartitionId> {
315        self.area.as_ref()
316    }
317
318    /// Now, as the registry's clock reads it.
319    pub fn now(&self) -> DateTime<Utc> {
320        self.now
321    }
322
323    /// The offset times are shown at.
324    pub fn offset(&self) -> FixedOffset {
325        self.offset
326    }
327
328    /// `at` as a person reads it: "19:00" today, "Tue 18:00" on another day.
329    pub fn time_text(&self, at: DateTime<Utc>) -> String {
330        let local = at.with_timezone(&self.offset);
331        let today = self.now.with_timezone(&self.offset).date_naive();
332        if local.date_naive() == today {
333            local.format("%H:%M").to_string()
334        } else {
335            local.format("%a %H:%M").to_string()
336        }
337    }
338
339    /// The caller's scheduled and running items, oldest first.
340    ///
341    /// # Errors
342    ///
343    /// The kernel's or the store's error.
344    pub async fn items(&self) -> Result<Vec<AgendaItem>, VerbError> {
345        self.agenda.items(&self.subject.id, self.area.as_ref()).await
346    }
347
348    /// The item `id`, when it is the caller's (and in the agent's area).
349    ///
350    /// # Errors
351    ///
352    /// [`VerbError::NotFound`] for an item that does not exist or is not the caller's — the
353    /// same answer, so a caller learns nothing of other people's items (S-I8).
354    pub async fn item(&self, id: &str) -> Result<AgendaItem, VerbError> {
355        let item = self.agenda.item(id).await?;
356        item.filter(|item| self.sees(item)).ok_or_else(|| VerbError::not_found(id))
357    }
358
359    fn sees(&self, item: &AgendaItem) -> bool {
360        item.subject.id == self.subject.id
361            && self.area.as_ref().is_none_or(|area| *area == item.partition)
362    }
363
364    /// Whether `item`'s process is queued or running.
365    ///
366    /// # Errors
367    ///
368    /// The kernel's or the store's error.
369    pub async fn started(&self, item: &AgendaItem) -> Result<bool, VerbError> {
370        self.agenda.started(item).await
371    }
372
373    /// Moves item `id`'s one wake from `from` to the later `to`, the only change a screen
374    /// action makes: the item stays scheduled; only when it wakes changes.
375    ///
376    /// # Errors
377    ///
378    /// [`VerbError::NotFound`] for an item not the caller's; [`VerbError::Refused`] when it is
379    /// not scheduled, does not wait for one time, does not wait for `from` any more ("It moved
380    /// since you saw this"), `to` is not later than `from`, it ends before `to`, or its process
381    /// started; the kernel's error.
382    pub async fn move_wake(
383        &self,
384        id: &str,
385        from: DateTime<Utc>,
386        to: DateTime<Utc>,
387    ) -> Result<AgendaItem, VerbError> {
388        // The kernel moves the wake without comparing it with `from`: the check and the move
389        // are one step for every move this registry makes.
390        let _one_at_a_time = self.moving.lock().await;
391        let item = self.item(id).await?;
392        let wake = match &item.state {
393            AgendaState::Scheduled { wake } => wake,
394            AgendaState::Running { .. } => return Err(VerbError::refused(words::ALREADY_STARTED)),
395            AgendaState::Proposed | AgendaState::Approved => {
396                return Err(VerbError::refused(words::NOT_SCHEDULED));
397            }
398            _ => return Err(VerbError::refused(words::ENDED)),
399        };
400        let Some(current) = single_time(wake) else {
401            return Err(VerbError::refused(words::NOT_ONE_TIME));
402        };
403        if current != from {
404            return Err(VerbError::refused(words::IT_MOVED));
405        }
406        if to <= from {
407            return Err(VerbError::invalid("a screen action only moves a wake later"));
408        }
409        if let Some(ends) = item.expires_at.filter(|ends| to > *ends) {
410            return Err(VerbError::refused(words::ends_at(&self.time_text(ends))));
411        }
412        if self.agenda.started(&item).await? {
413            return Err(VerbError::refused(words::ALREADY_STARTED));
414        }
415        self.agenda.reschedule(id, WakeSet::any_of([Wake::At(to)]), &self.subject).await
416    }
417}
418
419/// The one time `wake` waits for, when it waits for exactly one and nothing else.
420pub(crate) fn single_time(wake: &WakeSet) -> Option<DateTime<Utc>> {
421    match wake.any_of.as_slice() {
422        [Wake::At(at)] => Some(*at),
423        _ => None,
424    }
425}
426
427/// One action and what runs it.
428#[derive(Clone)]
429pub(crate) struct Entry {
430    pub(crate) spec: VerbSpec,
431    pub(crate) handler: Arc<dyn VerbHandler>,
432}
433
434/// The screen actions a home offers (spec 3.3 §2 item 7, §6.1), over the kernel's agenda.
435///
436/// The first catalogue is built in: `coming_up`, which lists the caller's Coming up with the
437/// two times each item may move to, and `snooze`, which moves one by an hour or to the same
438/// time tomorrow. A host adds more with [`VerbRegistryBuilder::verb`], within the object kinds
439/// allowed ([`ALLOWED_OBJECTS`]) and never under a [`RESERVED`](super::RESERVED) name.
440///
441/// # Example
442///
443/// ```rust,no_run
444/// use std::sync::Arc;
445/// use adk_surface::verbs::{KernelAgenda, VerbRegistry};
446///
447/// # fn example(kernel: &adk_kernel::Kernel, approvals: Arc<dyn adk_core::ApprovalStore>) -> Result<(), adk_surface::verbs::VerbError> {
448/// let registry = VerbRegistry::builder("adk-rust", Arc::new(KernelAgenda::of(kernel)))
449///     .approval_store(approvals)
450///     .build()?;
451/// let names: Vec<String> = registry.views().into_iter().map(|view| view.name).collect();
452/// assert_eq!(names, ["coming_up", "snooze"]);
453/// # Ok(())
454/// # }
455/// ```
456#[derive(Clone)]
457pub struct VerbRegistry {
458    inner: Arc<Inner>,
459}
460
461pub(crate) struct Inner {
462    pub(crate) app: String,
463    pub(crate) entries: Vec<Entry>,
464    pub(crate) agenda: Arc<dyn AgendaAccess>,
465    pub(crate) clock: Arc<dyn Clock>,
466    pub(crate) offset: FixedOffset,
467    pub(crate) audit: Option<AuditTrail>,
468    pub(crate) approvals: Option<Arc<dyn ApprovalStore>>,
469    pub(crate) governance: Option<GovernanceControl>,
470    pub(crate) sessions: Option<Arc<dyn SessionService>>,
471    pub(crate) answers: Option<Arc<dyn AnswerLog>>,
472    pub(crate) names: HashMap<String, String>,
473    pub(crate) moving: Arc<tokio::sync::Mutex<()>>,
474}
475
476impl fmt::Debug for VerbRegistry {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        f.debug_struct("VerbRegistry")
479            .field("app", &self.inner.app)
480            .field(
481                "verbs",
482                &self.inner.entries.iter().map(|entry| &entry.spec.name).collect::<Vec<_>>(),
483            )
484            .finish_non_exhaustive()
485    }
486}
487
488/// Builds a [`VerbRegistry`].
489pub struct VerbRegistryBuilder {
490    app: String,
491    agenda: Arc<dyn AgendaAccess>,
492    entries: Vec<Entry>,
493    clock: Arc<dyn Clock>,
494    offset: FixedOffset,
495    audit: Option<AuditTrail>,
496    approvals: Option<Arc<dyn ApprovalStore>>,
497    governance: Option<GovernanceControl>,
498    sessions: Option<Arc<dyn SessionService>>,
499    answers: Option<Arc<dyn AnswerLog>>,
500    names: HashMap<String, String>,
501}
502
503impl fmt::Debug for VerbRegistryBuilder {
504    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505        f.debug_struct("VerbRegistryBuilder").field("app", &self.app).finish_non_exhaustive()
506    }
507}
508
509impl VerbRegistryBuilder {
510    /// Adds the action `spec`, run by `handler`, after the catalogue; checked by
511    /// [`build`](Self::build).
512    #[must_use]
513    pub fn verb(mut self, spec: VerbSpec, handler: Arc<dyn VerbHandler>) -> Self {
514        self.entries.push(Entry { spec, handler });
515        self
516    }
517
518    /// Reads now from `clock` (default: the system clock).
519    #[must_use]
520    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
521        self.clock = clock;
522        self
523    }
524
525    /// Shows times at `offset` east of UTC instead of the host's time zone.
526    #[must_use]
527    pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
528        self.offset = offset;
529        self
530    }
531
532    /// Records every governed call and every action taken on `trail` (spec 3.3 §11).
533    #[must_use]
534    pub fn audit(mut self, trail: AuditTrail) -> Self {
535        self.audit = Some(trail);
536        self
537    }
538
539    /// Counts each agent's waiting requests in `store`, the approval service's store, so an
540    /// agent has at most [`MAX_WAITING`](super::MAX_WAITING) at once, and finds the decision
541    /// that let an agent's call run, for its record. The store, not the service, because the
542    /// service routes through [`VerbRegistry::router`].
543    #[must_use]
544    pub fn approval_store(mut self, store: Arc<dyn ApprovalStore>) -> Self {
545        self.approvals = Some(store);
546        self
547    }
548
549    /// Refuses a person's actions while `control` is frozen, except those that only delay
550    /// work (owner question 23).
551    #[must_use]
552    pub fn governance(mut self, control: GovernanceControl) -> Self {
553        self.governance = Some(control);
554        self
555    }
556
557    /// Reads the asking turn from `sessions`, so an agent's card names what it read first
558    /// ("Finance read 1 web page (example.com)").
559    #[must_use]
560    pub fn sessions(mut self, sessions: Arc<dyn SessionService>) -> Self {
561        self.sessions = Some(sessions);
562        self
563    }
564
565    /// Reads where a person answered an agent's request from `answers`, for its record: "you
566    /// said yes on your phone".
567    #[must_use]
568    pub fn answers(mut self, answers: Arc<dyn AnswerLog>) -> Self {
569        self.answers = Some(answers);
570        self
571    }
572
573    /// Names the agent `name` as `display_name` in refusals: "Finance already has 3 changes
574    /// waiting for you".
575    #[must_use]
576    pub fn agent_name(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
577        self.names.insert(name.into(), display_name.into());
578        self
579    }
580
581    /// The registry.
582    ///
583    /// # Errors
584    ///
585    /// [`VerbError::Invalid`] for a name outside `^[a-z][a-z0-9_]{0,58}$`, a second action of
586    /// one name, or an object kind outside [`ALLOWED_OBJECTS`]; [`VerbError::Reserved`] for a
587    /// reserved name.
588    pub fn build(self) -> Result<VerbRegistry, VerbError> {
589        let mut seen = std::collections::HashSet::new();
590        for entry in &self.entries {
591            let spec = &entry.spec;
592            check_name(&spec.name)?;
593            if !seen.insert(spec.name.clone()) {
594                return Err(VerbError::invalid(format!(
595                    "two screen actions are called `{}`; give each its own name",
596                    spec.name
597                )));
598            }
599            if let Some(kind) = spec.objects.iter().find(|kind| !ALLOWED_OBJECTS.contains(kind)) {
600                return Err(VerbError::invalid(format!(
601                    "`{}` acts on {kind:?}, which no screen action may act on yet",
602                    spec.name
603                )));
604            }
605        }
606        Ok(VerbRegistry {
607            inner: Arc::new(Inner {
608                app: self.app,
609                entries: self.entries,
610                agenda: self.agenda,
611                clock: self.clock,
612                offset: self.offset,
613                audit: self.audit,
614                approvals: self.approvals,
615                governance: self.governance,
616                sessions: self.sessions,
617                answers: self.answers,
618                names: self.names,
619                moving: Arc::new(tokio::sync::Mutex::new(())),
620            }),
621        })
622    }
623}
624
625impl VerbRegistry {
626    /// A builder for the app `app` over `agenda`, with the first catalogue: `coming_up` and
627    /// `snooze`.
628    pub fn builder(app: impl Into<String>, agenda: Arc<dyn AgendaAccess>) -> VerbRegistryBuilder {
629        VerbRegistryBuilder {
630            app: app.into(),
631            agenda,
632            entries: snooze::catalogue(),
633            clock: Arc::new(SystemClock),
634            offset: *Local::now().offset(),
635            audit: None,
636            approvals: None,
637            governance: None,
638            sessions: None,
639            answers: None,
640            names: HashMap::new(),
641        }
642    }
643
644    /// A builder of the first catalogue in `app` with no agenda, for a process that draws the
645    /// cards and lists the grant of actions another process takes, such as a terminal attached
646    /// to `adk-rust up` (spec 3.3 §7.1): its [`hints`](Self::hints) and [`grant`](Self::grant)
647    /// are those of the process that hosts the actions, and every action it would run is
648    /// refused.
649    ///
650    /// # Example
651    ///
652    /// ```rust
653    /// use adk_surface::verbs::VerbRegistry;
654    ///
655    /// let drawn = VerbRegistry::catalogue("adk-rust").build().unwrap();
656    /// assert_eq!(drawn.origin(), "verbs:adk-rust");
657    /// let _hints = drawn.hints();
658    /// ```
659    pub fn catalogue(app: impl Into<String>) -> VerbRegistryBuilder {
660        Self::builder(app, Arc::new(NoAgenda))
661    }
662
663    pub(crate) fn inner(&self) -> &Inner {
664        &self.inner
665    }
666
667    /// The app the actions belong to.
668    pub fn app_name(&self) -> &str {
669        &self.inner.app
670    }
671
672    /// The publisher of the action tools: `verbs:<app>`.
673    pub fn origin(&self) -> String {
674        super::verbs_origin(&self.inner.app)
675    }
676
677    /// The action `name`.
678    pub fn spec(&self, name: &str) -> Option<&VerbSpec> {
679        self.entry(name).map(|entry| &entry.spec)
680    }
681
682    pub(crate) fn entry(&self, name: &str) -> Option<&Entry> {
683        self.inner.entries.iter().find(|entry| entry.spec.name == name)
684    }
685
686    pub(crate) fn entries(&self) -> &[Entry] {
687        &self.inner.entries
688    }
689
690    /// The action an agent calls as `tool`, `verb_<name>`.
691    pub(crate) fn entry_for_tool(&self, tool: &str) -> Option<&Entry> {
692        tool.strip_prefix(super::VERB_TOOL_PREFIX).and_then(|name| self.entry(name))
693    }
694
695    /// The catalogue, as `GET /surface/verbs` lists it.
696    pub fn views(&self) -> Vec<VerbView> {
697        self.inner.entries.iter().map(|entry| VerbView::from(&entry.spec)).collect()
698    }
699
700    /// What `user`'s action may read and change: every area for a person, only `area` for an
701    /// agent.
702    pub(crate) fn scope(&self, user: &str, area: Option<PartitionId>) -> VerbScope {
703        VerbScope {
704            subject: SubjectRef::human(user),
705            area,
706            agenda: Arc::clone(&self.inner.agenda),
707            now: self.inner.clock.now(),
708            offset: self.inner.offset,
709            moving: Arc::clone(&self.inner.moving),
710        }
711    }
712
713    /// The display name of the agent `name`: as [`VerbRegistryBuilder::agent_name`] set it,
714    /// else the name with its first letter upper-cased.
715    pub(crate) fn display_name(&self, name: &str) -> String {
716        if let Some(display) = self.inner.names.get(name) {
717            return display.clone();
718        }
719        let mut chars = name.chars();
720        match chars.next() {
721            Some(first) => first.to_uppercase().chain(chars).collect(),
722            None => String::new(),
723        }
724    }
725
726    /// The tools of the actions agents may ask for, for an agent working in `area`
727    /// (spec 3.3 §2 item 7): attach with `HarnessAgentBuilder::toolset`.
728    pub fn toolset(&self, area: impl Into<PartitionId>) -> VerbToolset {
729        VerbToolset::new(self.clone(), area.into())
730    }
731
732    /// The classes of the action tools, by their declared effects: attach with
733    /// `HarnessAgentBuilder::tool_classes`.
734    pub fn classes(&self) -> VerbClasses {
735        VerbClasses::new(self.clone())
736    }
737
738    /// The operator-layer policy of an agent working in `area`: attach with
739    /// `HarnessAgentBuilder::add_operator_policy`, so the strictest decision keeps it over
740    /// modes and standing rules.
741    pub fn policy(&self, area: impl Into<PartitionId>) -> VerbPolicy {
742        VerbPolicy::new(self.clone(), Some(area.into()))
743    }
744
745    /// The approval router of the action tools' cards, with `fallback` for every other call:
746    /// pass it to `StoreApprovalService::with_router`.
747    pub fn router(&self, fallback: impl ApprovalRouter + 'static) -> VerbRouter {
748        VerbRouter::new(self.clone(), Arc::new(fallback))
749    }
750
751    /// The card hints of the action tools' cards: pass them to
752    /// `SurfaceEngineBuilder::card_hints`.
753    pub fn hints(&self) -> VerbHints {
754        VerbHints::new(self.clone())
755    }
756
757    /// What a host grants every agent it gives the action tools, for
758    /// `SurfaceEngineBuilder::grant` (spec 3.3 §5.7, S-I12, S-I13): only in Ask first and Go
759    /// ahead, as Just look and Suggest refuse every change an agent asks for.
760    ///
761    /// # Example
762    ///
763    /// ```rust,no_run
764    /// # fn example(registry: adk_surface::verbs::VerbRegistry) {
765    /// assert_eq!(registry.grant().text, "Ask to change things on your screens — always asks you first");
766    /// # }
767    /// ```
768    pub fn grant(&self) -> GrantedUse {
769        GrantedUse::new(GRANT_ID, words::GRANTED)
770            .only_in([crate::model::Mode::AskFirst, crate::model::Mode::GoAhead])
771    }
772}