Skip to main content

adk_awp/v2/
executor.rs

1//! The governed path a capability call enters from every binding (spec 3.5 §7.4, A-I7, A-I8;
2//! AWP 2.0 §7.5).
3//!
4//! A [`CapabilityExecutor`] takes an [`Invocation`] — the capability, its input, the caller's
5//! tier and requester id, its idempotency key and consent references — and answers an
6//! [`InvocationOutcome`]: an output, a held call, or an error. Every binding (HTTP, A2A, MCP)
7//! calls the same executor, so the outcome never depends on the binding.
8//!
9//! [`DirectExecutor`] is the built-in executor. In order it checks visibility by tier,
10//! deprecation, the input schema, the idempotency key, consent, and the idempotency record;
11//! then it holds the call for the owner when the approval hint says so, or runs the
12//! capability. A runtime that routes calls through an agent's governed path supplies its own
13//! executor.
14
15use std::collections::HashMap;
16use std::sync::{Arc, Mutex};
17
18use adk_core::context::{Artifacts, CallbackContext, MemoryEntry, ReadonlyContext};
19use adk_core::types::Content;
20use adk_core::{EventActions, Tool, ToolContext, json_digest};
21use async_trait::async_trait;
22use awp_types::{ErrorBody, ErrorCode, HeldCall, HeldCallState, RequesterId, TrustTier};
23use chrono::{DateTime, Utc};
24use serde_json::Value;
25use uuid::Uuid;
26
27use super::capability::{
28    CapabilityRegistry, CapabilityTool, META_CONSENT, META_REQUESTER, META_TIER, adk_error_to_body,
29};
30use super::store::{
31    ConsentReceiptStore, HeldCallRecord, HeldCallStore, HeldCallTransition, IdempotencyBegin,
32    IdempotencyStore, RecordedOutcome, StoreError, has_live_receipt,
33};
34
35/// The binding a call arrived over; it changes only the representation of the outcome.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum Binding {
39    /// `POST /awp/v2/capabilities/{name}`.
40    Http,
41    /// An A2A message.
42    A2a,
43    /// An MCP `tools/call`.
44    Mcp,
45}
46
47/// One capability call as it enters the governed path (spec 3.5 §7.4).
48#[derive(Debug, Clone, PartialEq)]
49pub struct Invocation {
50    /// The capability's name.
51    pub capability: String,
52    /// The input object.
53    pub input: Value,
54    /// The caller's tier.
55    pub tier: TrustTier,
56    /// The caller's verified requester id, from `known` up.
57    pub requester: Option<RequesterId>,
58    /// The idempotency key the binding carried.
59    pub idempotency_key: Option<String>,
60    /// Consent receipt ids the call references.
61    pub consent: Vec<Uuid>,
62    /// The binding it arrived over.
63    pub binding: Binding,
64}
65
66impl Invocation {
67    /// A call over `binding` with no key, no consent references and a `public` caller.
68    pub fn new(capability: impl Into<String>, input: Value, binding: Binding) -> Self {
69        Self {
70            capability: capability.into(),
71            input,
72            tier: TrustTier::Public,
73            requester: None,
74            idempotency_key: None,
75            consent: Vec::new(),
76            binding,
77        }
78    }
79}
80
81/// How a capability call ended (spec 3.5 §7.4).
82#[derive(Debug, Clone, PartialEq)]
83#[non_exhaustive]
84pub enum InvocationOutcome {
85    /// The output object.
86    Completed(Value),
87    /// The call is held for the owner; HTTP answers `202` with its status URL.
88    Held(HeldCall),
89    /// The call failed or was refused.
90    Failed(ErrorBody),
91}
92
93/// The governed path every binding calls (spec 3.5 §7.4, D-4).
94#[async_trait]
95pub trait CapabilityExecutor: Send + Sync {
96    /// Executes, holds or refuses `invocation`.
97    async fn invoke(&self, invocation: Invocation) -> InvocationOutcome;
98}
99
100/// The owner's decision on a held call (spec 3.5 §7.4).
101#[derive(Debug, Clone, PartialEq)]
102#[non_exhaustive]
103pub enum HeldDecision {
104    /// Run the call.
105    Approve,
106    /// Refuse it, with a message for the requester.
107    Reject {
108        /// Why, with no internal detail.
109        message: String,
110    },
111}
112
113/// The built-in [`CapabilityExecutor`] (spec 3.5 §7.4, A-I7, A-I8).
114///
115/// # Example
116///
117/// ```
118/// use std::sync::Arc;
119///
120/// use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityRegistry};
121/// use adk_awp::v2::executor::{Binding, CapabilityExecutor, DirectExecutor, Invocation, InvocationOutcome};
122/// use adk_awp::v2::store::MemoryEdgeStores;
123/// use awp_types::{CapabilityEffect, CapabilityV2};
124/// use serde_json::{Value, json};
125///
126/// struct Search;
127/// #[async_trait::async_trait]
128/// impl CapabilityHandler for Search {
129///     async fn handle(&self, _call: CapabilityCall) -> Result<Value, CapabilityError> {
130///         Ok(json!({ "results": [] }))
131///     }
132/// }
133///
134/// # #[tokio::main(flavor = "current_thread")]
135/// # async fn main() {
136/// let mut registry = CapabilityRegistry::new("example.com");
137/// registry.declare(CapabilityV2::new("search_site", "Search", CapabilityEffect::ReadOnly), Arc::new(Search)).unwrap();
138/// let executor = DirectExecutor::in_memory(Arc::new(registry), &MemoryEdgeStores::default());
139/// let outcome = executor.invoke(Invocation::new("search_site", json!({}), Binding::Http)).await;
140/// assert_eq!(outcome, InvocationOutcome::Completed(json!({ "results": [] })));
141/// # }
142/// ```
143pub struct DirectExecutor {
144    registry: Arc<CapabilityRegistry>,
145    held_calls: Arc<dyn HeldCallStore>,
146    idempotency: Arc<dyn IdempotencyStore>,
147    consent: Arc<dyn ConsentReceiptStore>,
148    hold_expiry: Option<chrono::Duration>,
149}
150
151impl std::fmt::Debug for DirectExecutor {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.debug_struct("DirectExecutor").field("registry", &self.registry).finish_non_exhaustive()
154    }
155}
156
157fn refused(code: ErrorCode, message: impl Into<String>) -> InvocationOutcome {
158    InvocationOutcome::Failed(ErrorBody::new(code, message))
159}
160
161fn store_failed(error: &StoreError) -> InvocationOutcome {
162    tracing::error!(error = %error, "awp edge store failed during a capability call");
163    refused(ErrorCode::InternalError, "the site could not record the call")
164}
165
166impl DirectExecutor {
167    /// Creates an executor over `registry` and the given stores.
168    pub fn new(
169        registry: Arc<CapabilityRegistry>,
170        held_calls: Arc<dyn HeldCallStore>,
171        idempotency: Arc<dyn IdempotencyStore>,
172        consent: Arc<dyn ConsentReceiptStore>,
173    ) -> Self {
174        Self { registry, held_calls, idempotency, consent, hold_expiry: None }
175    }
176
177    /// Gives every held call an `expiresAt` this long after it is held; an undecided call
178    /// then expires through [`Self::expire_due`]. Without it a call waits as long as the owner
179    /// takes.
180    pub fn with_hold_expiry(mut self, expiry: chrono::Duration) -> Self {
181        self.hold_expiry = Some(expiry);
182        self
183    }
184
185    /// Creates an executor over `registry` and the in-memory `stores`, sharing their records.
186    pub fn in_memory(
187        registry: Arc<CapabilityRegistry>,
188        stores: &super::store::MemoryEdgeStores,
189    ) -> Self {
190        Self::new(
191            registry,
192            Arc::new(stores.held_calls.clone()),
193            Arc::new(stores.idempotency.clone()),
194            Arc::new(stores.consent.clone()),
195        )
196    }
197
198    /// The scope of an idempotency key: the capability and, from `known` up, the requester.
199    fn idempotency_scope(invocation: &Invocation, key: &str) -> String {
200        let requester = invocation.requester.as_ref().map_or("", RequesterId::as_str);
201        format!("{}\u{1f}{requester}\u{1f}{key}", invocation.capability)
202    }
203
204    async fn replay(&self, outcome: RecordedOutcome) -> InvocationOutcome {
205        match outcome {
206            RecordedOutcome::Completed { output } => InvocationOutcome::Completed(output),
207            RecordedOutcome::Failed { error } => InvocationOutcome::Failed(error),
208            RecordedOutcome::Held { call_id } => match self.held_calls.get(&call_id).await {
209                Ok(Some(record)) => InvocationOutcome::Held(record.call),
210                Ok(None) => refused(ErrorCode::InternalError, "the held call was not found"),
211                Err(error) => store_failed(&error),
212            },
213        }
214    }
215
216    async fn record(&self, scope: Option<&str>, outcome: &InvocationOutcome) {
217        let Some(scope) = scope else { return };
218        let recorded = match outcome {
219            InvocationOutcome::Completed(output) => {
220                RecordedOutcome::Completed { output: output.clone() }
221            }
222            InvocationOutcome::Held(call) => RecordedOutcome::Held { call_id: call.id.clone() },
223            InvocationOutcome::Failed(error) => RecordedOutcome::Failed { error: error.clone() },
224        };
225        if let Err(error) = self.idempotency.complete(scope, recorded).await {
226            tracing::error!(error = %error, "awp idempotency outcome was not recorded");
227        }
228    }
229
230    async fn run(
231        tool: &Arc<CapabilityTool>,
232        invocation: &Invocation,
233        input: Value,
234        call_id: &str,
235    ) -> InvocationOutcome {
236        let context = Arc::new(EdgeToolContext::new(tool, invocation, call_id));
237        match Arc::clone(tool).execute(context, input).await {
238            Ok(output) => InvocationOutcome::Completed(output),
239            Err(error) => InvocationOutcome::Failed(adk_error_to_body(&error)),
240        }
241    }
242
243    /// Resolves held call `id` with the owner's `decision`: an approved call runs and
244    /// completes with its output or error; a rejected call ends `rejected` (spec 3.5 §7.4).
245    ///
246    /// # Errors
247    ///
248    /// [`StoreError::NotFound`] for an unknown call; [`StoreError::Conflict`] for a call
249    /// that is not pending.
250    pub async fn decide(&self, id: &str, decision: HeldDecision) -> Result<HeldCall, StoreError> {
251        let record = self
252            .held_calls
253            .get(id)
254            .await?
255            .ok_or_else(|| StoreError::NotFound(format!("held call {id}")))?;
256        match decision {
257            HeldDecision::Reject { message } => {
258                let rejected = self
259                    .held_calls
260                    .transition(
261                        id,
262                        HeldCallTransition {
263                            to: HeldCallState::Rejected,
264                            result: None,
265                            error: Some(ErrorBody::new(ErrorCode::Forbidden, message)),
266                        },
267                    )
268                    .await?;
269                Ok(rejected.call)
270            }
271            HeldDecision::Approve => {
272                self.held_calls
273                    .transition(
274                        id,
275                        HeldCallTransition {
276                            to: HeldCallState::Approved,
277                            result: None,
278                            error: None,
279                        },
280                    )
281                    .await?;
282                let Some(tool) = self.registry.get(&record.call.capability) else {
283                    return Err(StoreError::Conflict(format!(
284                        "capability {} is no longer declared",
285                        record.call.capability
286                    )));
287                };
288                let mut invocation = Invocation::new(
289                    record.call.capability.clone(),
290                    record.input.clone(),
291                    Binding::Http,
292                );
293                invocation.requester = record.requester.clone();
294                invocation.tier = record.tier;
295                invocation.consent = record.consent.clone();
296                invocation.idempotency_key = record.idempotency_key.clone();
297                let transition = match Self::run(tool, &invocation, record.input, id).await {
298                    InvocationOutcome::Completed(output) => HeldCallTransition {
299                        to: HeldCallState::Completed,
300                        result: Some(output),
301                        error: None,
302                    },
303                    InvocationOutcome::Failed(error) => HeldCallTransition {
304                        to: HeldCallState::Completed,
305                        result: None,
306                        error: Some(error),
307                    },
308                    InvocationOutcome::Held(_) => HeldCallTransition {
309                        to: HeldCallState::Completed,
310                        result: None,
311                        error: Some(ErrorBody::new(
312                            ErrorCode::InternalError,
313                            "the call was held again",
314                        )),
315                    },
316                };
317                Ok(self.held_calls.transition(id, transition).await?.call)
318            }
319        }
320    }
321
322    /// Expires every pending call whose `expiresAt` is at or before `now`; returns their ids.
323    ///
324    /// # Errors
325    ///
326    /// As the held-call store.
327    pub async fn expire_due(&self, now: DateTime<Utc>) -> Result<Vec<String>, StoreError> {
328        let mut expired = Vec::new();
329        for record in self.held_calls.pending().await? {
330            if record.call.expires_at.is_some_and(|expires_at| expires_at <= now) {
331                self.held_calls
332                    .transition(
333                        &record.call.id,
334                        HeldCallTransition {
335                            to: HeldCallState::Expired,
336                            result: None,
337                            error: Some(ErrorBody::new(
338                                ErrorCode::Forbidden,
339                                "the owner did not decide in time",
340                            )),
341                        },
342                    )
343                    .await?;
344                expired.push(record.call.id);
345            }
346        }
347        Ok(expired)
348    }
349}
350
351#[async_trait]
352impl CapabilityExecutor for DirectExecutor {
353    async fn invoke(&self, invocation: Invocation) -> InvocationOutcome {
354        let now = Utc::now();
355        // A capability above the caller's tier, or past its sunset, is reported as absent.
356        let Some(tool) = self.registry.visible(&invocation.capability, invocation.tier) else {
357            return refused(ErrorCode::CapabilityNotFound, "no such capability");
358        };
359        let declaration = tool.declaration();
360        if declaration
361            .deprecated
362            .as_ref()
363            .and_then(|deprecated| deprecated.sunset)
364            .is_some_and(|sunset| sunset <= now)
365        {
366            return refused(ErrorCode::CapabilityNotFound, "no such capability");
367        }
368        if let Err(errors) = tool.validate_input(&invocation.input) {
369            return refused(
370                ErrorCode::SchemaValidationFailed,
371                format!("the input does not match the input schema: {}", errors.join("; ")),
372            );
373        }
374        if declaration.requires_idempotency() && invocation.idempotency_key.is_none() {
375            return refused(
376                ErrorCode::IdempotencyKeyRequired,
377                "this capability needs an idempotency key on every call",
378            );
379        }
380        if let Some(requirement) = &declaration.consent {
381            match has_live_receipt(self.consent.as_ref(), &invocation.consent, requirement, now)
382                .await
383            {
384                Ok(true) => {}
385                Ok(false) => {
386                    return refused(
387                        ErrorCode::ConsentRequired,
388                        format!(
389                            "this capability needs a live consent receipt for {} under policy {}",
390                            requirement.scope, requirement.policy_version
391                        ),
392                    );
393                }
394                Err(error) => return store_failed(&error),
395            }
396        }
397
398        let scope = invocation
399            .idempotency_key
400            .as_deref()
401            .map(|key| Self::idempotency_scope(&invocation, key));
402        if let Some(scope) = &scope {
403            match self.idempotency.begin(scope, &json_digest(&invocation.input), now).await {
404                Ok(IdempotencyBegin::Started) => {}
405                Ok(IdempotencyBegin::Recorded(outcome)) => return self.replay(outcome).await,
406                Ok(IdempotencyBegin::InFlight) => {
407                    let mut body = ErrorBody::new(
408                        ErrorCode::IdempotencyConflict,
409                        "a call with this idempotency key is still executing",
410                    );
411                    body.retryable = true;
412                    body.retry_after = Some(1);
413                    return InvocationOutcome::Failed(body);
414                }
415                Ok(IdempotencyBegin::Conflict) => {
416                    return refused(
417                        ErrorCode::IdempotencyConflict,
418                        "the idempotency key was used with a different input",
419                    );
420                }
421                Err(error) => return store_failed(&error),
422            }
423        }
424
425        let call_id = format!("call_{}", Uuid::new_v4().simple());
426        let outcome = if declaration.approval.holds(tool.amount(&invocation.input).await) {
427            let mut call = HeldCall::pending(call_id, declaration.name.clone(), now);
428            call.expires_at = self.hold_expiry.map(|expiry| now + expiry);
429            let record = HeldCallRecord {
430                call,
431                requester: invocation.requester.clone(),
432                tier: invocation.tier,
433                input: invocation.input.clone(),
434                idempotency_key: invocation.idempotency_key.clone(),
435                consent: invocation.consent.clone(),
436            };
437            match self.held_calls.create(record.clone()).await {
438                Ok(()) => InvocationOutcome::Held(record.call),
439                Err(error) => store_failed(&error),
440            }
441        } else {
442            Self::run(tool, &invocation, invocation.input.clone(), &call_id).await
443        };
444        self.record(scope.as_deref(), &outcome).await;
445        outcome
446    }
447}
448
449/// The tool context of a capability call at the edge: the call's identity, its idempotency
450/// key and the caller's tier, requester and consent references as request metadata.
451pub struct EdgeToolContext {
452    app_name: String,
453    user_id: String,
454    call_id: String,
455    idempotency_key: String,
456    metadata: HashMap<String, Value>,
457    user_content: Content,
458    actions: Mutex<EventActions>,
459}
460
461impl EdgeToolContext {
462    /// The context of call `call_id` of `tool` for `invocation`.
463    pub fn new(tool: &CapabilityTool, invocation: &Invocation, call_id: &str) -> Self {
464        let mut metadata = HashMap::new();
465        if let Some(requester) = &invocation.requester {
466            metadata.insert(META_REQUESTER.to_owned(), Value::String(requester.to_string()));
467        }
468        metadata.insert(
469            META_TIER.to_owned(),
470            serde_json::to_value(invocation.tier).unwrap_or(Value::Null),
471        );
472        metadata.insert(
473            META_CONSENT.to_owned(),
474            serde_json::to_value(&invocation.consent).unwrap_or(Value::Null),
475        );
476        let idempotency_key =
477            invocation.idempotency_key.clone().unwrap_or_else(|| call_id.to_owned());
478        Self {
479            app_name: tool.origin().to_owned(),
480            user_id: invocation
481                .requester
482                .as_ref()
483                .map_or_else(|| "public".to_owned(), ToString::to_string),
484            call_id: call_id.to_owned(),
485            idempotency_key,
486            metadata,
487            user_content: Content::new("user"),
488            actions: Mutex::new(EventActions::default()),
489        }
490    }
491}
492
493#[async_trait]
494impl ReadonlyContext for EdgeToolContext {
495    fn invocation_id(&self) -> &str {
496        &self.call_id
497    }
498
499    fn agent_name(&self) -> &str {
500        "awp-edge"
501    }
502
503    fn user_id(&self) -> &str {
504        &self.user_id
505    }
506
507    fn app_name(&self) -> &str {
508        &self.app_name
509    }
510
511    fn session_id(&self) -> &str {
512        ""
513    }
514
515    fn branch(&self) -> &str {
516        ""
517    }
518
519    fn user_content(&self) -> &Content {
520        &self.user_content
521    }
522}
523
524#[async_trait]
525impl CallbackContext for EdgeToolContext {
526    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
527        None
528    }
529}
530
531#[async_trait]
532impl ToolContext for EdgeToolContext {
533    fn function_call_id(&self) -> &str {
534        &self.call_id
535    }
536
537    fn idempotency_key(&self) -> String {
538        self.idempotency_key.clone()
539    }
540
541    fn actions(&self) -> EventActions {
542        self.actions.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
543    }
544
545    fn set_actions(&self, actions: EventActions) {
546        *self.actions.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = actions;
547    }
548
549    async fn search_memory(&self, _query: &str) -> adk_core::Result<Vec<MemoryEntry>> {
550        Ok(Vec::new())
551    }
552
553    fn request_metadata(&self) -> HashMap<String, Value> {
554        self.metadata.clone()
555    }
556}