Skip to main content

adk_surface/verbs/
gate.rs

1//! A person's own screen action (spec 3.3 §2 item 7, §7.2, §11, owner question 23).
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use adk_core::principal::SubjectKind;
7use adk_core::{
8    ActingContext, ApprovalScope, GOVERNANCE_FROZEN_CODE, GovernedCall, RunConfig,
9    ToolAuthorization, ToolGate, authorize_tool_call,
10};
11use serde_json::{Map, Value, json};
12
13use super::policy::VerbPolicy;
14use super::registry::VerbRegistry;
15use super::tools::VerbTool;
16use super::{
17    ComingUpItem, SURFACE_AUDIT_VERB, VERBS_AGENT, VerbDone, VerbError, VerbIntent, VerbSpec, words,
18};
19use crate::engine::SurfaceEngine;
20use crate::origin::{Caller, Origin};
21use crate::rules::{self, Row};
22
23/// A person's screen actions, from any surface that may take them (spec 3.3 §2 item 7, §7.2).
24///
25/// [`call`](Self::call) runs one for an authenticated [`Caller`]:
26///
27/// 1. **Where** (§7.2): the home, the phone, a terminal and voice take screen actions; a chat
28///    channel and the tray do not, and an agent asks through its own tool.
29/// 2. **Whose** (S-I8): only the caller's own items, in any area.
30/// 3. **The governed path**: `authorize_tool_call` under `urn:adk:agent:<app>/surface.verbs`,
31///    acting for the person, so the call has a `tool_call` record like any other. Stop all
32///    applies, except to an action that only delays work, such as snooze (owner question 23).
33/// 4. **The record**: `surface.verb`, through the engine's record, stamped with the surface,
34///    how it was given, the device and presence; for voice, the transcript's digest, never the
35///    words.
36///
37/// What it did is answered only after it ran.
38///
39/// # Example
40///
41/// ```rust,no_run
42/// use adk_surface::verbs::{ObjectRef, VerbGate, VerbIntent};
43/// use adk_surface::{Caller, Origin, SurfaceKind};
44///
45/// # async fn example(gate: VerbGate, to: &str) -> Result<(), adk_surface::verbs::VerbError> {
46/// let ana = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
47/// let item = gate.coming_up(&ana).await?.remove(0);
48/// let snooze = VerbIntent::new("snooze", serde_json::json!({ "to": item.choices[0].to }))
49///     .on(ObjectRef::coming_up(&item.id));
50/// let done = gate.call(&ana, snooze).await?;
51/// println!("{}", done.text);
52/// # Ok(())
53/// # }
54/// ```
55#[derive(Clone)]
56pub struct VerbGate {
57    registry: VerbRegistry,
58    engine: SurfaceEngine,
59}
60
61impl std::fmt::Debug for VerbGate {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("VerbGate").field("registry", &self.registry).finish_non_exhaustive()
64    }
65}
66
67impl VerbGate {
68    /// A person's actions of `registry`, recorded through `engine`.
69    pub fn new(registry: VerbRegistry, engine: SurfaceEngine) -> Self {
70        Self { registry, engine }
71    }
72
73    /// The registry.
74    pub fn registry(&self) -> &VerbRegistry {
75        &self.registry
76    }
77
78    /// The engine the actions are recorded through.
79    pub fn engine(&self) -> &SurfaceEngine {
80        &self.engine
81    }
82
83    /// How long a spoken action waits before it runs, and can be cancelled: the engine's
84    /// window for a spoken "allow once" (spec 3.3 §5.6, owner question 26).
85    pub fn voice_cancel_window(&self) -> Duration {
86        self.engine.voice_cancel_window()
87    }
88
89    /// Refuses a caller who may not take a screen action from where they are.
90    fn check_row(caller: &Caller) -> Result<(), VerbError> {
91        match rules::row(caller) {
92            Row::Web | Row::Terminal | Row::Phone | Row::Voice => Ok(()),
93            Row::Chat | Row::Tray => Err(VerbError::NotHere(words::NOT_FROM_HERE.to_string())),
94            Row::Agent => {
95                Err(VerbError::NotHere(words::AGENTS_ASK_THROUGH_THEIR_TOOLS.to_string()))
96            }
97        }
98    }
99
100    /// The caller's Coming up, with the times each item may move to.
101    ///
102    /// # Errors
103    ///
104    /// [`VerbError::NotHere`] from a chat channel, the tray or an agent; the kernel's error.
105    pub async fn coming_up(&self, caller: &Caller) -> Result<Vec<ComingUpItem>, VerbError> {
106        Self::check_row(caller)?;
107        self.registry.scope(caller.user_id(), None).coming_up().await
108    }
109
110    /// Takes the action `intent` names, for `caller` (spec 3.3 §2 item 7).
111    ///
112    /// # Errors
113    ///
114    /// | Error | When |
115    /// |---|---|
116    /// | [`VerbError::NotHere`] | From a chat channel, the tray, or an agent |
117    /// | [`VerbError::Unknown`] | No such action |
118    /// | [`VerbError::Invalid`] | An object kind the action does not take, or its arguments are wrong |
119    /// | [`VerbError::NotFound`] | No such item of the caller's |
120    /// | [`VerbError::Refused`] | It cannot be done now, or the governed path refused it — Stop all for an action that does not only delay |
121    pub async fn call(&self, caller: &Caller, intent: VerbIntent) -> Result<VerbDone, VerbError> {
122        self.call_with(caller, intent, None).await
123    }
124
125    /// [`call`](Self::call) for words the person said, whose SHA-256 the record carries as
126    /// `transcriptDigest` (spec 3.3 §5.6).
127    #[cfg(feature = "voice")]
128    pub(crate) async fn call_spoken(
129        &self,
130        caller: &Caller,
131        intent: VerbIntent,
132        transcript: &str,
133    ) -> Result<VerbDone, VerbError> {
134        use sha2::Digest as _;
135        let digest = format!("{:x}", sha2::Sha256::digest(transcript.as_bytes()));
136        self.call_with(caller, intent, Some(digest)).await
137    }
138
139    async fn call_with(
140        &self,
141        caller: &Caller,
142        intent: VerbIntent,
143        transcript_digest: Option<String>,
144    ) -> Result<VerbDone, VerbError> {
145        Self::check_row(caller)?;
146        let entry = self
147            .registry
148            .entry(&intent.verb)
149            .ok_or_else(|| VerbError::Unknown { verb: intent.verb.clone() })?;
150        if let Some(object) =
151            intent.objects.iter().find(|object| !entry.spec.objects.contains(&object.kind))
152        {
153            return Err(VerbError::invalid(format!(
154                "`{}` does not act on {:?}",
155                entry.spec.name, object.kind
156            )));
157        }
158        let args = intent.call_args();
159        let call_id = format!("verb-{}", uuid::Uuid::new_v4());
160        let governed = self.authorize(caller, &entry.spec, &call_id, args).await;
161        let args = match governed {
162            Ok(args) => args,
163            Err(error) => {
164                self.record(
165                    caller,
166                    &entry.spec,
167                    &intent.call_args(),
168                    &call_id,
169                    Err(&error),
170                    transcript_digest,
171                )
172                .await;
173                return Err(error);
174            }
175        };
176        let scope = self.registry.scope(caller.user_id(), None);
177        let result = entry.handler.run(&scope, &args).await;
178        if !entry.spec.reads() {
179            self.record(caller, &entry.spec, &args, &call_id, result.as_ref(), transcript_digest)
180                .await;
181        }
182        result
183    }
184
185    /// The governed path for `caller`'s call (owner question 23): the arguments to run with, or
186    /// why not.
187    async fn authorize(
188        &self,
189        caller: &Caller,
190        spec: &VerbSpec,
191        call_id: &str,
192        args: Value,
193    ) -> Result<Value, VerbError> {
194        let registry = self.registry.inner();
195        let app = self.registry.app_name();
196        let user = caller.user_id();
197        let mut config = RunConfig::builder()
198            .tool_policy(Arc::new(VerbPolicy::new(self.registry.clone(), None)));
199        // Snoozing only delays work, so it still runs while everything is stopped.
200        if !spec.only_delays
201            && let Some(control) = &registry.governance
202        {
203            config = config.governance(control.clone());
204        }
205        if let Some(trail) = &registry.audit {
206            config = config.audit(trail.clone());
207        }
208        let config = config.build();
209        let invocation = format!("surface-verbs-{}", uuid::Uuid::new_v4());
210        let scope = ApprovalScope::new(app, user, VERBS_AGENT);
211        let acting = ActingContext::derived(app, VERBS_AGENT, user, SubjectKind::Human);
212        let gate =
213            ToolGate::new(&config, VERBS_AGENT, &invocation, scope).with_acting_context(acting);
214        let tool = VerbTool::new(&self.registry, spec, None);
215        let call = GovernedCall::for_tool(&tool, call_id, args);
216        match authorize_tool_call(&gate, call).await {
217            Ok(ToolAuthorization::Execute { args, .. }) => Ok(args),
218            Ok(ToolAuthorization::Refuse { reason, .. }) => Err(VerbError::refused(reason)),
219            Ok(ToolAuthorization::Pending { reason, .. }) => Err(VerbError::refused(reason)),
220            Err(error) if error.code == GOVERNANCE_FROZEN_CODE => Err(VerbError::refused(
221                "Everything is stopped: this changes what your agents do, so it waits for Resume all",
222            )),
223            Err(error) => Err(VerbError::Source(error)),
224        }
225    }
226
227    /// The `surface.verb` record of `caller`'s action (spec 3.3 §11).
228    async fn record(
229        &self,
230        caller: &Caller,
231        spec: &VerbSpec,
232        args: &Value,
233        call_id: &str,
234        outcome: Result<&VerbDone, &VerbError>,
235        transcript_digest: Option<String>,
236    ) {
237        let mut fields = Map::new();
238        fields.insert("verb".into(), json!(spec.name));
239        if let Some(trail) = &self.registry.inner().audit {
240            fields.insert("argsDigest".into(), json!(trail.digest(args)));
241        }
242        fields.insert("effect".into(), json!(spec.effect.to_string()));
243        fields.insert("functionCallId".into(), json!(call_id));
244        match outcome {
245            Ok(done) => {
246                fields.insert("outcome".into(), json!("done"));
247                if let Some(target) = &done.target {
248                    fields.insert("target".into(), json!(target));
249                }
250                if let Some(title) = &done.title {
251                    fields.insert("title".into(), json!(title));
252                }
253            }
254            Err(error) => {
255                fields.insert("outcome".into(), json!("refused"));
256                fields.insert("code".into(), json!(error.code()));
257                if let Some(item) = args.get("item").and_then(Value::as_str) {
258                    fields.insert("target".into(), json!(format!("agenda:{item}")));
259                    // The item's title, so the record names it as the person knows it (§8).
260                    let scope = self.registry.scope(caller.user_id(), None);
261                    if let Ok(found) = scope.item(item).await {
262                        fields.insert("title".into(), json!(found.title));
263                    }
264                }
265            }
266        }
267        if let Some(digest) = transcript_digest {
268            fields.insert("transcriptDigest".into(), json!(digest));
269        }
270        // An origin the caller declared is the caller's: a person's action never reads as an
271        // agent's.
272        debug_assert!(!matches!(caller.origin, Origin::Agent { .. }));
273        if let Err(error) =
274            self.engine.record(caller, SURFACE_AUDIT_VERB, Value::Object(fields)).await
275        {
276            tracing::warn!(error = %error, verb = %spec.name, "the screen action's record failed");
277        }
278    }
279}