1use 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#[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 pub fn new(registry: VerbRegistry, engine: SurfaceEngine) -> Self {
70 Self { registry, engine }
71 }
72
73 pub fn registry(&self) -> &VerbRegistry {
75 &self.registry
76 }
77
78 pub fn engine(&self) -> &SurfaceEngine {
80 &self.engine
81 }
82
83 pub fn voice_cancel_window(&self) -> Duration {
86 self.engine.voice_cancel_window()
87 }
88
89 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 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 pub async fn call(&self, caller: &Caller, intent: VerbIntent) -> Result<VerbDone, VerbError> {
122 self.call_with(caller, intent, None).await
123 }
124
125 #[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 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 if !spec.only_delays
201 && let Some(control) = ®istry.governance
202 {
203 config = config.governance(control.clone());
204 }
205 if let Some(trail) = ®istry.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 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 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 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}