Skip to main content

adk_server/awp/
executor.rs

1//! The governed path every binding enters (spec 3.5 §7.4, D-4, A-I7, A-I8; AWP 2.0 §7.5).
2//!
3//! [`GovernedExecutor`] answers a capability call the same way whether it arrived over HTTP,
4//! A2A, MCP or a public agent's conversation. In order:
5//!
6//! 1. Visibility by tier and deprecation — a hidden or sunset capability is `capability_not_found`.
7//! 2. Read-only mode and the kill switch — a non-`read_only` capability answers `read_only`.
8//! 3. The caller's daily call limit — `rate_limit_exceeded`.
9//! 4. The input schema, the idempotency key a `non_idempotent` capability requires, and a live
10//!    consent receipt for a consent-bound one.
11//! 5. The idempotency record: a repeat with the same key and input returns the recorded
12//!    outcome — output, error or held call — without executing; the same key with another
13//!    input is `idempotency_conflict`.
14//! 6. `adk_core::authorize_tool_call` under [`CapabilityPolicy`], the owner's
15//!    `ApprovalService`, the action ledger and the audit trail: the call executes, is refused,
16//!    or is held for the owner (`202` with `Location: /awp/v2/calls/{id}`).
17//!
18//! A held call waits in the approval store for as long as the owner takes — spec 3.3's park on
19//! timeout — until its decision arrives; [`GovernedExecutor::resolve`] then runs it through the
20//! same path, or ends it `rejected` or `expired`.
21
22use std::sync::Arc;
23
24use adk_awp::v2::capability::{CapabilityRegistry, CapabilityTool, adk_error_to_body};
25use adk_awp::v2::executor::{
26    Binding, CapabilityExecutor, EdgeToolContext, Invocation, InvocationOutcome,
27};
28use adk_awp::v2::store::{
29    ConsentReceiptStore, HeldCallRecord, HeldCallStore, HeldCallTransition, IdempotencyBegin,
30    IdempotencyStore, RecordedOutcome, StoreError, has_live_receipt,
31};
32use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
33use adk_core::principal::SubjectRef;
34use adk_core::{
35    ActingContext, ActionLedger, ActionOutcome, ActionRecord, AgentPrincipal, ApprovalScope,
36    ApprovalService, ApprovalState, ApprovalStore, GovernedCall, InboxQuery, RunConfig, Tool,
37    ToolAuthorization, ToolConfirmationRequest, ToolEffect, ToolGate, ToolOrigin, json_digest,
38    not_run_text,
39};
40use async_trait::async_trait;
41use awp_types::{
42    CapabilityEffect, ErrorBody, ErrorCode, HeldCall, HeldCallState, IdempotencySource,
43    RequesterId, TrustTier,
44};
45use chrono::Utc;
46use serde_json::Value;
47use uuid::Uuid;
48
49use super::control::EdgeControl;
50use super::limits::EdgeLimits;
51use super::policy::{ATTR_CONSENT, ATTR_TIER, CapabilityPolicy};
52use super::tiers::EdgeCaller;
53
54/// The name the edge's governed calls are recorded under.
55pub const EDGE_AGENT_NAME: &str = "awp-edge";
56
57tokio::task_local! {
58    /// The caller of the request being served, for executors called without one.
59    pub(crate) static CURRENT_CALLER: EdgeCaller;
60}
61
62/// Where a binding found the idempotency key of a call (AWP 2.0 §7.7, C7, C8).
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct KeySources {
65    /// The explicit key: `Idempotency-Key`, the A2A metadata key, or the MCP `_meta` key.
66    pub explicit: Option<String>,
67    /// The binding's own id: the A2A `messageId`, or the MCP request id within its session.
68    pub binding_id: Option<String>,
69}
70
71impl KeySources {
72    /// The key `source` selects for a call over `binding` (AWP 2.0 §7.7): `idempotency_key`
73    /// takes only the explicit key; every other source takes the binding's own source —
74    /// `Idempotency-Key` on HTTP, the `messageId` on A2A, the `_meta` key else the request id
75    /// on MCP.
76    pub fn key_for(&self, source: IdempotencySource, binding: Binding) -> Option<String> {
77        match (source, binding) {
78            (IdempotencySource::IdempotencyKey, _) | (_, Binding::Http) => self.explicit.clone(),
79            (_, Binding::A2a) => self.binding_id.clone().or_else(|| self.explicit.clone()),
80            (_, Binding::Mcp) => self.explicit.clone().or_else(|| self.binding_id.clone()),
81            _ => self.explicit.clone(),
82        }
83    }
84}
85
86/// The governed [`CapabilityExecutor`] of the edge (spec 3.5 §7.4).
87///
88/// Build it through [`AwpEdge`](super::AwpEdge); every binding shares one.
89#[derive(Clone)]
90pub struct GovernedExecutor {
91    inner: Arc<Inner>,
92}
93
94impl std::fmt::Debug for GovernedExecutor {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("GovernedExecutor")
97            .field("domain", &self.inner.registry.domain())
98            .finish_non_exhaustive()
99    }
100}
101
102pub(crate) struct Inner {
103    pub(crate) registry: Arc<CapabilityRegistry>,
104    pub(crate) held_calls: Arc<dyn HeldCallStore>,
105    pub(crate) idempotency: Arc<dyn IdempotencyStore>,
106    pub(crate) consent: Arc<dyn ConsentReceiptStore>,
107    pub(crate) approval_service: Option<Arc<dyn ApprovalService>>,
108    pub(crate) approval_store: Arc<dyn ApprovalStore>,
109    pub(crate) ledger: Arc<dyn ActionLedger>,
110    pub(crate) audit: Option<AuditTrail>,
111    pub(crate) principal: AgentPrincipal,
112    pub(crate) policy: Arc<CapabilityPolicy>,
113    pub(crate) control: Arc<EdgeControl>,
114    pub(crate) limits: Arc<EdgeLimits>,
115    pub(crate) hold_expiry: Option<chrono::Duration>,
116    pub(crate) references: super::events::ConsentReferences,
117}
118
119fn refused(code: ErrorCode, message: impl Into<String>) -> InvocationOutcome {
120    InvocationOutcome::Failed(ErrorBody::new(code, message))
121}
122
123fn store_failed(error: &StoreError) -> InvocationOutcome {
124    tracing::error!(error = %error, "awp edge store failed during a capability call");
125    refused(ErrorCode::InternalError, "the site could not record the call")
126}
127
128fn binding_name(binding: Binding) -> &'static str {
129    match binding {
130        Binding::Http => "http",
131        Binding::A2a => "a2a",
132        Binding::Mcp => "mcp",
133        _ => "other",
134    }
135}
136
137fn outcome_name(outcome: &InvocationOutcome) -> String {
138    match outcome {
139        InvocationOutcome::Completed(_) => "completed".to_owned(),
140        InvocationOutcome::Held(_) => "held".to_owned(),
141        InvocationOutcome::Failed(error) => error.code.to_string(),
142        _ => "other".to_owned(),
143    }
144}
145
146impl GovernedExecutor {
147    pub(crate) fn from_inner(inner: Inner) -> Self {
148        Self { inner: Arc::new(inner) }
149    }
150
151    /// The capability registry.
152    pub fn registry(&self) -> &Arc<CapabilityRegistry> {
153        &self.inner.registry
154    }
155
156    /// The scope of an idempotency key: the capability and, from `known` up, the requester.
157    fn idempotency_scope(invocation: &Invocation, key: &str) -> String {
158        let requester = invocation.requester.as_ref().map_or("", RequesterId::as_str);
159        format!("{}\u{1f}{requester}\u{1f}{key}", invocation.capability)
160    }
161
162    fn acting(
163        &self,
164        tier: TrustTier,
165        requester: Option<&RequesterId>,
166        consent: &[Uuid],
167    ) -> ActingContext {
168        let consent = consent.iter().map(ToString::to_string).collect::<Vec<_>>().join(",");
169        let principal = self
170            .inner
171            .principal
172            .clone()
173            .with_attribute(ATTR_TIER, tier.as_str())
174            .with_attribute(ATTR_CONSENT, consent);
175        let acting = ActingContext::new(principal);
176        match requester {
177            // The verified requester is the call's counterparty (spec 3.5 §7.3).
178            Some(requester) => acting.on_behalf_of(SubjectRef::service(requester.as_str())),
179            None => acting,
180        }
181    }
182
183    fn scope(&self, requester: Option<&RequesterId>, call_id: &str) -> ApprovalScope {
184        ApprovalScope::new(
185            CapabilityTool::origin_for(self.inner.registry.domain()),
186            requester.map_or("public", RequesterId::as_str),
187            call_id,
188        )
189    }
190
191    fn run_config(&self, effect: CapabilityEffect) -> RunConfig {
192        let inner = &self.inner;
193        let mut builder = RunConfig::builder()
194            .tool_policy(Arc::clone(&inner.policy) as Arc<dyn adk_core::ToolPolicy>)
195            .action_ledger(Arc::clone(&inner.ledger))
196            .approval_store(Arc::clone(&inner.approval_store));
197        if let Some(service) = &inner.approval_service {
198            builder = builder.approval_service(Arc::clone(service));
199        }
200        if let Some(audit) = &inner.audit {
201            builder = builder.audit(audit.clone());
202        }
203        // Read-only capabilities keep answering under the kill switch (A-I12).
204        if effect != CapabilityEffect::ReadOnly
205            && let Some(control) = inner.control.governance()
206        {
207            builder = builder.governance(control.clone());
208        }
209        builder.build()
210    }
211
212    async fn audit(
213        &self,
214        action: &str,
215        acting: &ActingContext,
216        call_id: &str,
217        invocation: &Invocation,
218        outcome: &str,
219    ) {
220        let Some(trail) = &self.inner.audit else { return };
221        let draft = AuditRecordDraft::new(AuditRecordKind::Other("awp".to_owned()), action)
222            .actor(AuditActor::new(acting, call_id))
223            .args_digest(trail.digest(&invocation.input))
224            .ext("awp.capability", Value::String(invocation.capability.clone()))
225            .ext("awp.binding", Value::String(binding_name(invocation.binding).to_owned()))
226            .ext("awp.tier", Value::String(invocation.tier.as_str().to_owned()))
227            .ext(
228                "awp.requester",
229                invocation
230                    .requester
231                    .as_ref()
232                    .map_or(Value::Null, |requester| Value::String(requester.to_string())),
233            )
234            .ext("outcome", Value::String(outcome.to_owned()));
235        if let Err(error) = trail.record(draft).await {
236            tracing::warn!(audit.action = action, error = %error, "awp audit record not written");
237        }
238    }
239
240    /// Records `awp.request.verified` for a verified caller's fetch of a discovery surface —
241    /// the Agent Card, the capability manifest or the MCP Server Card — so verified agent
242    /// discovery is counted (spec 3.5 §7.12, §9.3). Public callers are not recorded.
243    pub(crate) async fn record_discovery(&self, caller: &EdgeCaller, surface: &str) {
244        let (Some(trail), Some(requester)) = (&self.inner.audit, &caller.requester) else {
245            return;
246        };
247        if caller.tier == TrustTier::Public {
248            return;
249        }
250        let acting = self.acting(caller.tier, Some(requester), &[]);
251        let request_id = format!("req_{}", Uuid::new_v4().simple());
252        let draft =
253            AuditRecordDraft::new(AuditRecordKind::Other("awp".to_owned()), "awp.request.verified")
254                .actor(AuditActor::new(&acting, request_id))
255                .ext("awp.surface", Value::String(surface.to_owned()))
256                .ext("awp.tier", Value::String(caller.tier.as_str().to_owned()))
257                .ext("awp.requester", Value::String(requester.to_string()));
258        if let Err(error) = trail.record(draft).await {
259            tracing::warn!(error = %error, "awp discovery audit record not written");
260        }
261    }
262
263    /// Executes an authorized call, ledgered when it is `non_idempotent` (A-I7).
264    async fn execute(
265        &self,
266        tool: &Arc<CapabilityTool>,
267        invocation: &Invocation,
268        args: Value,
269        call_id: &str,
270    ) -> InvocationOutcome {
271        let ledger = &self.inner.ledger;
272        let effect = adk_core::Tool::effect(tool.as_ref());
273        let ledger_key = format!(
274            "awp\u{1f}{}",
275            Self::idempotency_scope(
276                invocation,
277                invocation.idempotency_key.as_deref().unwrap_or(call_id)
278            )
279        );
280        if effect == ToolEffect::NonIdempotent {
281            match ledger.get(&ledger_key).await {
282                Ok(None) => {}
283                Ok(Some(record)) => {
284                    let mut body = ErrorBody::new(
285                        ErrorCode::IdempotencyConflict,
286                        if record.is_completed() {
287                            "this call already executed; its result is no longer retained"
288                        } else {
289                            "a call with this idempotency key is still executing"
290                        },
291                    );
292                    body.retryable = !record.is_completed();
293                    return InvocationOutcome::Failed(body);
294                }
295                Err(error) => {
296                    tracing::error!(error = %error, "awp action ledger read failed");
297                    return refused(ErrorCode::InternalError, "the site could not record the call");
298                }
299            }
300            let record =
301                ActionRecord::new(&ledger_key, tool.declaration().name.clone(), &args, effect);
302            if let Err(error) = ledger.begin(&record).await {
303                tracing::error!(error = %error, "awp action ledger begin failed");
304                return refused(ErrorCode::InternalError, "the site could not record the call");
305            }
306            // The kill switch may engage between the hold and the execution.
307            if let Some(control) = self.inner.control.governance()
308                && let Err(frozen) = control.check()
309            {
310                let _ = ledger
311                    .complete(&ledger_key, ActionOutcome::Failed { error: not_run_text(&frozen) })
312                    .await;
313                return refused(ErrorCode::ReadOnly, "the site is read-only");
314            }
315        }
316        let context = Arc::new(EdgeToolContext::new(tool, invocation, call_id));
317        let result = Arc::clone(tool).execute(context, args).await;
318        if effect == ToolEffect::NonIdempotent {
319            let outcome = match &result {
320                Ok(output) => ActionOutcome::Succeeded { result_digest: json_digest(output) },
321                Err(error) => ActionOutcome::Failed { error: error.message.clone() },
322            };
323            if let Err(error) = ledger.complete(&ledger_key, outcome).await {
324                tracing::error!(error = %error, "awp action ledger complete failed");
325            }
326        }
327        match result {
328            Ok(output) => InvocationOutcome::Completed(output),
329            Err(error) => InvocationOutcome::Failed(adk_error_to_body(&error)),
330        }
331    }
332
333    async fn record(&self, scope: Option<&str>, outcome: &InvocationOutcome) {
334        let Some(scope) = scope else { return };
335        let recorded = match outcome {
336            InvocationOutcome::Completed(output) => {
337                RecordedOutcome::Completed { output: output.clone() }
338            }
339            InvocationOutcome::Held(call) => RecordedOutcome::Held { call_id: call.id.clone() },
340            InvocationOutcome::Failed(error) => RecordedOutcome::Failed { error: error.clone() },
341            _ => return,
342        };
343        if let Err(error) = self.inner.idempotency.complete(scope, recorded).await {
344            tracing::error!(error = %error, "awp idempotency outcome was not recorded");
345        }
346    }
347
348    async fn replay(&self, outcome: RecordedOutcome) -> InvocationOutcome {
349        match outcome {
350            RecordedOutcome::Completed { output } => InvocationOutcome::Completed(output),
351            RecordedOutcome::Failed { error } => InvocationOutcome::Failed(error),
352            RecordedOutcome::Held { call_id } => match self.resolve(&call_id).await {
353                Ok(Some(call)) => InvocationOutcome::Held(call),
354                Ok(None) => refused(ErrorCode::InternalError, "the held call was not found"),
355                Err(error) => store_failed(&error),
356            },
357            _ => refused(ErrorCode::InternalError, "the recorded outcome could not be read"),
358        }
359    }
360
361    /// Executes, holds or refuses `invocation` for `caller` (spec 3.5 §7.4).
362    pub async fn invoke_as(
363        &self,
364        caller: &EdgeCaller,
365        invocation: Invocation,
366    ) -> InvocationOutcome {
367        let span = tracing::info_span!(
368            "awp.capability.call",
369            awp.capability = %invocation.capability,
370            awp.binding = binding_name(invocation.binding),
371            awp.tier = %invocation.tier,
372            awp.requester = invocation.requester.as_ref().map_or("", RequesterId::as_str),
373            awp.outcome = tracing::field::Empty,
374        );
375        let outcome =
376            tracing::Instrument::instrument(self.invoke_inner(caller, invocation), span.clone())
377                .await;
378        span.record("awp.outcome", outcome_name(&outcome).as_str());
379        outcome
380    }
381
382    async fn invoke_inner(&self, caller: &EdgeCaller, invocation: Invocation) -> InvocationOutcome {
383        let inner = &self.inner;
384        let now = Utc::now();
385        let Some(tool) = inner.registry.visible(&invocation.capability, invocation.tier) else {
386            return refused(ErrorCode::CapabilityNotFound, "no such capability");
387        };
388        let declaration = tool.declaration();
389        if declaration
390            .deprecated
391            .as_ref()
392            .and_then(|deprecated| deprecated.sunset)
393            .is_some_and(|sunset| sunset <= now)
394        {
395            return refused(ErrorCode::CapabilityNotFound, "no such capability");
396        }
397        if declaration.effect != CapabilityEffect::ReadOnly && inner.control.is_read_only() {
398            let mut body = ErrorBody::new(
399                ErrorCode::ReadOnly,
400                "the site is read-only; only read-only capabilities answer",
401            );
402            body.retryable = true;
403            return InvocationOutcome::Failed(body);
404        }
405        if let Err(limited) =
406            inner.limits.admit_call(caller, declaration.rate_class.as_deref()).await
407        {
408            let mut body = ErrorBody::new(
409                ErrorCode::RateLimitExceeded,
410                format!("the caller passed its daily call limit of {}", limited.limit),
411            );
412            body.retry_after = Some(limited.retry_after);
413            return InvocationOutcome::Failed(body);
414        }
415        if let Err(errors) = tool.validate_input(&invocation.input) {
416            return refused(
417                ErrorCode::SchemaValidationFailed,
418                format!("the input does not match the input schema: {}", errors.join("; ")),
419            );
420        }
421        if declaration.requires_idempotency() && invocation.idempotency_key.is_none() {
422            return refused(
423                ErrorCode::IdempotencyKeyRequired,
424                "this capability needs an idempotency key on every call",
425            );
426        }
427        if let Some(requirement) = &declaration.consent {
428            match has_live_receipt(inner.consent.as_ref(), &invocation.consent, requirement, now)
429                .await
430            {
431                Ok(true) => {}
432                Ok(false) => {
433                    return refused(
434                        ErrorCode::ConsentRequired,
435                        format!(
436                            "this capability needs a live consent receipt for {} under policy {}",
437                            requirement.scope, requirement.policy_version
438                        ),
439                    );
440                }
441                Err(error) => return store_failed(&error),
442            }
443        }
444
445        let scope = invocation
446            .idempotency_key
447            .as_deref()
448            .map(|key| Self::idempotency_scope(&invocation, key));
449        if let Some(scope) = &scope {
450            match inner.idempotency.begin(scope, &json_digest(&invocation.input), now).await {
451                Ok(IdempotencyBegin::Started) => {}
452                Ok(IdempotencyBegin::Recorded(outcome)) => {
453                    tracing::debug!("awp call answered from its idempotency record");
454                    return self.replay(outcome).await;
455                }
456                Ok(IdempotencyBegin::InFlight) => {
457                    let mut body = ErrorBody::new(
458                        ErrorCode::IdempotencyConflict,
459                        "a call with this idempotency key is still executing",
460                    );
461                    body.retryable = true;
462                    body.retry_after = Some(1);
463                    return InvocationOutcome::Failed(body);
464                }
465                Ok(IdempotencyBegin::Conflict) => {
466                    return refused(
467                        ErrorCode::IdempotencyConflict,
468                        "the idempotency key was used with a different input",
469                    );
470                }
471                Ok(_) => {
472                    return refused(
473                        ErrorCode::InternalError,
474                        "the idempotency record is unreadable",
475                    );
476                }
477                Err(error) => return store_failed(&error),
478            }
479        }
480
481        // Who referenced a receipt hears of its revocation (AWP 2.0 §9.2).
482        if let Some(requester) = &invocation.requester
483            && !invocation.consent.is_empty()
484        {
485            inner.references.note(&invocation.consent, requester).await;
486        }
487        // At least 128 bits of entropy (AWP 2.0 §7.6).
488        let call_id = format!("call_{}", Uuid::new_v4().simple());
489        let outcome = self.govern(tool, &invocation, &call_id).await;
490        self.record(scope.as_deref(), &outcome).await;
491        outcome
492    }
493
494    /// Runs the call through `adk_core::authorize_tool_call` and executes, refuses or holds it.
495    async fn govern(
496        &self,
497        tool: &Arc<CapabilityTool>,
498        invocation: &Invocation,
499        call_id: &str,
500    ) -> InvocationOutcome {
501        let inner = &self.inner;
502        let declaration = tool.declaration();
503        let run_config = self.run_config(declaration.effect);
504        let acting =
505            self.acting(invocation.tier, invocation.requester.as_ref(), &invocation.consent);
506        let gate = ToolGate::new(
507            &run_config,
508            EDGE_AGENT_NAME,
509            call_id,
510            self.scope(invocation.requester.as_ref(), call_id),
511        )
512        .with_acting_context(acting.clone());
513        let call = GovernedCall::for_tool(tool.as_ref(), call_id, invocation.input.clone());
514        let outcome = match adk_core::authorize_tool_call(&gate, call).await {
515            Ok(ToolAuthorization::Execute { args, .. }) => {
516                self.execute(tool, invocation, args, call_id).await
517            }
518            Ok(ToolAuthorization::Refuse { reason, .. }) => {
519                tracing::info!(reason = %reason, "awp capability call refused by the governed path");
520                refused(ErrorCode::Forbidden, "the owner's policy does not allow this call")
521            }
522            Ok(ToolAuthorization::Pending { .. }) => {
523                let now = Utc::now();
524                let mut held = HeldCall::pending(call_id, declaration.name.clone(), now);
525                held.expires_at = inner.hold_expiry.map(|expiry| now + expiry);
526                let record = HeldCallRecord {
527                    call: held,
528                    requester: invocation.requester.clone(),
529                    tier: invocation.tier,
530                    input: invocation.input.clone(),
531                    idempotency_key: invocation.idempotency_key.clone(),
532                    consent: invocation.consent.clone(),
533                };
534                match inner.held_calls.create(record.clone()).await {
535                    Ok(()) => {
536                        self.audit("awp.capability.held", &acting, call_id, invocation, "held")
537                            .await;
538                        InvocationOutcome::Held(record.call)
539                    }
540                    Err(error) => store_failed(&error),
541                }
542            }
543            Err(error) if inner.control.frozen() => {
544                tracing::info!(error = %error, "awp capability call stopped by the kill switch");
545                let mut body = ErrorBody::new(ErrorCode::ReadOnly, "the site is read-only");
546                body.retryable = true;
547                InvocationOutcome::Failed(body)
548            }
549            Err(error) => {
550                tracing::error!(error = %error, "awp governed path failed");
551                refused(ErrorCode::InternalError, "the call could not be authorized")
552            }
553        };
554        if !matches!(outcome, InvocationOutcome::Held(_)) {
555            self.audit(
556                "awp.capability.called",
557                &acting,
558                call_id,
559                invocation,
560                &outcome_name(&outcome),
561            )
562            .await;
563        }
564        outcome
565    }
566
567    async fn transition(
568        &self,
569        id: &str,
570        to: HeldCallState,
571        result: Option<Value>,
572        error: Option<ErrorBody>,
573    ) -> Result<HeldCall, StoreError> {
574        Ok(self
575            .inner
576            .held_calls
577            .transition(id, HeldCallTransition { to, result, error })
578            .await?
579            .call)
580    }
581
582    /// Whether the owner's approval request for `fingerprint` in `scope` expired.
583    async fn approval_expired(&self, scope: &ApprovalScope, fingerprint: &str) -> bool {
584        let Some(service) = &self.inner.approval_service else { return false };
585        let query = InboxQuery::default().with_session(scope).with_states(ApprovalState::ALL);
586        match service.inbox(query).await {
587            Ok(page) => page.items.iter().any(|item| {
588                item.fingerprint == fingerprint && item.state == ApprovalState::Expired
589            }),
590            Err(_) => false,
591        }
592    }
593
594    /// Resolves held call `id` once the owner decided it (spec 3.5 §7.4): an approved call runs
595    /// through the governed path again and completes with its output or error; a refused call
596    /// ends `rejected`, or `expired` when its approval request expired; a call past its
597    /// `expiresAt` expires. A call with no decision, or one decided while the kill switch is
598    /// engaged, stays pending. Returns the held call, or `None` for an unknown id.
599    ///
600    /// # Errors
601    ///
602    /// [`StoreError`] when the held-call store fails.
603    pub async fn resolve(&self, id: &str) -> Result<Option<HeldCall>, StoreError> {
604        let inner = &self.inner;
605        let Some(record) = inner.held_calls.get(id).await? else { return Ok(None) };
606        if record.call.state != HeldCallState::Pending {
607            return Ok(Some(record.call));
608        }
609        let now = Utc::now();
610        if record.call.expires_at.is_some_and(|expires_at| expires_at <= now) {
611            let error = ErrorBody::new(ErrorCode::Forbidden, "the owner did not decide in time");
612            return self.transition(id, HeldCallState::Expired, None, Some(error)).await.map(Some);
613        }
614        if inner.control.frozen() {
615            return Ok(Some(record.call));
616        }
617        let Some(tool) = inner.registry.get(&record.call.capability) else {
618            let error =
619                ErrorBody::new(ErrorCode::CapabilityNotFound, "the capability was withdrawn");
620            return self.transition(id, HeldCallState::Rejected, None, Some(error)).await.map(Some);
621        };
622        let mut invocation =
623            Invocation::new(record.call.capability.clone(), record.input.clone(), Binding::Http);
624        invocation.tier = record.tier;
625        invocation.requester = record.requester.clone();
626        invocation.consent = record.consent.clone();
627        invocation.idempotency_key = record.idempotency_key.clone();
628        let run_config = self.run_config(tool.declaration().effect);
629        let acting = self.acting(record.tier, record.requester.as_ref(), &record.consent);
630        let scope = self.scope(record.requester.as_ref(), id);
631        let gate = ToolGate::new(&run_config, EDGE_AGENT_NAME, id, scope.clone())
632            .with_acting_context(acting.clone());
633        let request = ToolConfirmationRequest {
634            tool_name: tool.declaration().name.clone(),
635            function_call_id: Some(id.to_owned()),
636            args: record.input.clone(),
637            acting: Some(Box::new(acting.clone())),
638            origin: Some(ToolOrigin::of(tool.as_ref() as &dyn Tool)),
639            evidence: Vec::new(),
640        };
641        let fingerprint = request.fingerprint();
642        match adk_core::confirmation_decision_available(&gate, &request).await {
643            Ok(true) => {}
644            Ok(false) => return Ok(Some(record.call)),
645            Err(error) => {
646                tracing::warn!(error = %error, "awp held call decision could not be read");
647                return Ok(Some(record.call));
648            }
649        }
650        let call =
651            GovernedCall::for_tool(tool.as_ref(), id, record.input.clone()).resuming(request);
652        let resolved = match adk_core::authorize_tool_call(&gate, call).await {
653            Ok(ToolAuthorization::Execute { args, .. }) => {
654                self.transition(id, HeldCallState::Approved, None, None).await?;
655                match self.execute(tool, &invocation, args, id).await {
656                    InvocationOutcome::Completed(output) => {
657                        self.transition(id, HeldCallState::Completed, Some(output), None).await?
658                    }
659                    InvocationOutcome::Failed(error) => {
660                        self.transition(id, HeldCallState::Completed, None, Some(error)).await?
661                    }
662                    _ => {
663                        let error =
664                            ErrorBody::new(ErrorCode::InternalError, "the call did not complete");
665                        self.transition(id, HeldCallState::Completed, None, Some(error)).await?
666                    }
667                }
668            }
669            Ok(ToolAuthorization::Refuse { reason, .. }) => {
670                tracing::info!(reason = %reason, "awp held call refused");
671                if self.approval_expired(&scope, &fingerprint).await {
672                    let error =
673                        ErrorBody::new(ErrorCode::Forbidden, "the owner did not decide in time");
674                    self.transition(id, HeldCallState::Expired, None, Some(error)).await?
675                } else {
676                    let error = ErrorBody::new(ErrorCode::Forbidden, "the owner declined the call");
677                    self.transition(id, HeldCallState::Rejected, None, Some(error)).await?
678                }
679            }
680            Ok(ToolAuthorization::Pending { .. }) => return Ok(Some(record.call)),
681            Err(error) => {
682                tracing::warn!(error = %error, "awp held call stays pending");
683                return Ok(Some(record.call));
684            }
685        };
686        let state = format!("{:?}", resolved.state).to_lowercase();
687        self.audit("awp.capability.decided", &acting, id, &invocation, &state).await;
688        Ok(Some(resolved))
689    }
690
691    /// Resolves every pending held call that has a decision or is past its expiry; returns
692    /// the calls that left `pending`.
693    ///
694    /// # Errors
695    ///
696    /// [`StoreError`] when the held-call store fails.
697    pub async fn resolve_pending(&self) -> Result<Vec<HeldCall>, StoreError> {
698        let mut resolved = Vec::new();
699        for record in self.inner.held_calls.pending().await? {
700            if let Some(call) = self.resolve(&record.call.id).await?
701                && call.state != HeldCallState::Pending
702            {
703                resolved.push(call);
704            }
705        }
706        Ok(resolved)
707    }
708}
709
710#[async_trait]
711impl CapabilityExecutor for GovernedExecutor {
712    /// Runs `invocation` for the caller of the request being served.
713    async fn invoke(&self, invocation: Invocation) -> InvocationOutcome {
714        let caller = CURRENT_CALLER.try_with(Clone::clone).unwrap_or_else(|_| {
715            let limit_key = invocation.requester.as_ref().map_or_else(
716                || "ip:unknown".to_owned(),
717                |requester| format!("id:{}", requester.as_str()),
718            );
719            EdgeCaller {
720                tier: invocation.tier,
721                requester: invocation.requester.clone(),
722                ..EdgeCaller::public(limit_key)
723            }
724        });
725        self.invoke_as(&caller, invocation).await
726    }
727}