1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum Binding {
39 Http,
41 A2a,
43 Mcp,
45}
46
47#[derive(Debug, Clone, PartialEq)]
49pub struct Invocation {
50 pub capability: String,
52 pub input: Value,
54 pub tier: TrustTier,
56 pub requester: Option<RequesterId>,
58 pub idempotency_key: Option<String>,
60 pub consent: Vec<Uuid>,
62 pub binding: Binding,
64}
65
66impl Invocation {
67 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#[derive(Debug, Clone, PartialEq)]
83#[non_exhaustive]
84pub enum InvocationOutcome {
85 Completed(Value),
87 Held(HeldCall),
89 Failed(ErrorBody),
91}
92
93#[async_trait]
95pub trait CapabilityExecutor: Send + Sync {
96 async fn invoke(&self, invocation: Invocation) -> InvocationOutcome;
98}
99
100#[derive(Debug, Clone, PartialEq)]
102#[non_exhaustive]
103pub enum HeldDecision {
104 Approve,
106 Reject {
108 message: String,
110 },
111}
112
113pub 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 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 pub fn with_hold_expiry(mut self, expiry: chrono::Duration) -> Self {
181 self.hold_expiry = Some(expiry);
182 self
183 }
184
185 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 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 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 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 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
449pub 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 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}