1pub mod a2a;
62pub mod beacon;
63pub mod chat;
64pub mod conformance;
65pub mod consent;
66pub mod control;
67pub mod events;
68pub mod executor;
69pub mod limits;
70pub mod mcp;
71pub mod policy;
72pub mod public;
73#[cfg(any(feature = "awp-sqlite", feature = "awp-postgres", feature = "awp-redis"))]
74pub mod stores;
75pub mod tiers;
76
77use std::sync::{Arc, Weak};
78use std::time::Duration;
79
80use adk_auth::VisitorTokens;
81use adk_awp::signing::jws::DocumentSigner;
82use adk_awp::v2::capability::CapabilityRegistry;
83use adk_awp::v2::response::envelope_response;
84use adk_awp::v2::routes::{EdgeState, awp_v2_routes};
85use adk_awp::v2::store::{
86 ConsentReceiptStore, HeldCallStore, IdempotencyStore, LeadStore, MemoryEdgeStores, StatusStore,
87 StoreError, SubscriptionStore,
88};
89use adk_awp::v2::tier::TierAssigner;
90use adk_core::audit_log::AuditTrail;
91use adk_core::subject::{
92 ConsentGate, ConsentStore, InMemorySubjectRegistry, PseudonymousRecorder, SubjectDataStore,
93 SubjectRegistry, SubjectRights, VisitorId,
94};
95use adk_core::{
96 ActionLedger, AdkError, Agent, AgentId, AgentPrincipal, ApprovalService, ApprovalStore,
97 ErrorCategory, ErrorComponent, GovernanceControl, InMemoryActionLedger, InMemoryApprovalStore,
98 Url,
99};
100use adk_session::SessionSubjectData;
101use adk_session::{InMemorySessionService, SessionService};
102use adk_tool::mcp::server::McpSessions;
103use awp_types::{
104 CapabilityEffect, ErrorBody, ErrorCode, ErrorEnvelope, HeldCall, SiteStatus, TrustRules,
105 TrustTier,
106};
107use axum::Router;
108use axum::extract::{FromRequest as _, Request, State};
109use axum::http::{HeaderValue, Method, StatusCode, header};
110use axum::middleware::{Next, from_fn_with_state};
111use axum::response::{IntoResponse, Response};
112use axum::routing::get;
113use tracing::Instrument as _;
114
115pub use a2a::AgentCardInfo;
116pub use beacon::{BeaconCounts, BeaconStore, BeaconSubjectData, InMemoryBeaconStore};
117pub use consent::{ConsentConfig, ConsentPolicy, LeadsData, ReceiptConsentStore, SubjectData};
118pub use control::{EdgeMode, StatusError};
119pub use events::{
120 EdgeEvents, EventLog, EventsConfig, InMemoryEventLog, PendingDelivery, RetainedEvent,
121};
122pub use executor::{GovernedExecutor, KeySources};
123pub use limits::{EdgeLimits, InMemoryRateLimitStore, RateLimitStore, RateWindow};
124pub use policy::{CapabilityPolicy, PublicPartitionPolicy};
125pub use public::{
126 ConversationScreen, InjectionScreen, META_BINDING, META_LIMIT_KEY, META_THREAD, PublicTools,
127 RecordingSignals, RecordingThreadSink, ReplyPolicy, SignalEmitter, SiteHit, SiteSearch,
128 StaticSiteIndex, ThreadSink,
129};
130pub use tiers::{EdgeCaller, EdgeTiers, WebBotAuthTrustAssigner};
131
132use control::EdgeControl;
133use executor::CURRENT_CALLER;
134use public::{LiveThreads, PublicPartition, PublicParts, TurnWatch, Watch};
135
136#[derive(Clone)]
140pub struct EdgeKeys {
141 pub card: Arc<dyn DocumentSigner>,
143 pub receipt: Arc<dyn DocumentSigner>,
145}
146
147impl std::fmt::Debug for EdgeKeys {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 f.debug_struct("EdgeKeys")
150 .field("card", &self.card.kid())
151 .field("receipt", &self.receipt.kid())
152 .finish()
153 }
154}
155
156#[derive(Clone)]
158#[non_exhaustive]
159pub struct EdgeStores {
160 pub status: Arc<dyn StatusStore>,
162 pub held_calls: Arc<dyn HeldCallStore>,
164 pub idempotency: Arc<dyn IdempotencyStore>,
166 pub consent: Arc<dyn ConsentReceiptStore>,
168 pub subscriptions: Arc<dyn SubscriptionStore>,
170 pub leads: Arc<dyn LeadStore>,
172 pub event_log: Option<Arc<dyn EventLog>>,
175 pub beacon: Option<Arc<dyn BeaconStore>>,
178}
179
180impl EdgeStores {
181 pub fn new(
183 status: Arc<dyn StatusStore>,
184 held_calls: Arc<dyn HeldCallStore>,
185 idempotency: Arc<dyn IdempotencyStore>,
186 consent: Arc<dyn ConsentReceiptStore>,
187 ) -> Self {
188 let memory = MemoryEdgeStores::default();
189 Self {
190 status,
191 held_calls,
192 idempotency,
193 consent,
194 subscriptions: Arc::new(memory.subscriptions),
195 leads: Arc::new(memory.leads),
196 event_log: None,
197 beacon: None,
198 }
199 }
200
201 #[must_use]
203 pub fn with_subscriptions(mut self, subscriptions: Arc<dyn SubscriptionStore>) -> Self {
204 self.subscriptions = subscriptions;
205 self
206 }
207
208 #[must_use]
210 pub fn with_leads(mut self, leads: Arc<dyn LeadStore>) -> Self {
211 self.leads = leads;
212 self
213 }
214
215 #[must_use]
218 pub fn with_event_log(mut self, log: Arc<dyn EventLog>) -> Self {
219 self.event_log = Some(log);
220 self
221 }
222
223 #[must_use]
225 pub fn with_beacon(mut self, beacon: Arc<dyn BeaconStore>) -> Self {
226 self.beacon = Some(beacon);
227 self
228 }
229
230 pub fn in_memory(stores: &MemoryEdgeStores) -> Self {
232 Self::new(
233 Arc::new(stores.status.clone()),
234 Arc::new(stores.held_calls.clone()),
235 Arc::new(stores.idempotency.clone()),
236 Arc::new(stores.consent.clone()),
237 )
238 .with_subscriptions(Arc::new(stores.subscriptions.clone()))
239 .with_leads(Arc::new(stores.leads.clone()))
240 }
241}
242
243impl std::fmt::Debug for EdgeStores {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 f.debug_struct("EdgeStores").finish_non_exhaustive()
246 }
247}
248
249pub(crate) fn envelope(error: ErrorBody, status: Option<SiteStatus>) -> Response {
251 let mut response =
252 envelope_response(&ErrorEnvelope { awp: awp_types::VERSION_2_0, error, status });
253 response.headers_mut().insert("awp-version", HeaderValue::from_static("2.0"));
254 response
255}
256
257type AgentFactory = Box<dyn FnOnce(&PublicTools) -> Arc<dyn Agent> + Send>;
258
259pub struct AwpEdgeBuilder {
261 registry: CapabilityRegistry,
262 keys: EdgeKeys,
263 public_url: Url,
264 tiers: EdgeTiers,
265 limits: EdgeLimits,
266 stores: Option<EdgeStores>,
267 approval_service: Option<Arc<dyn ApprovalService>>,
268 approval_store: Option<Arc<dyn ApprovalStore>>,
269 ledger: Option<Arc<dyn ActionLedger>>,
270 audit: Option<AuditTrail>,
271 principal: Option<AgentPrincipal>,
272 governance: Option<GovernanceControl>,
273 hold_expiry: Option<chrono::Duration>,
274 card: Option<AgentCardInfo>,
275 agent: Option<AgentFactory>,
276 search: Option<Arc<dyn SiteSearch>>,
277 threads: Option<Arc<dyn ThreadSink>>,
278 signals: Option<Arc<dyn SignalEmitter>>,
279 screen: Option<Arc<dyn ConversationScreen>>,
280 reply_policy: ReplyPolicy,
281 sessions: Option<Arc<dyn SessionService>>,
282 mcp_sessions: McpSessions,
283 events: EventsConfig,
284 event_log: Option<Arc<dyn EventLog>>,
285 consent: ConsentConfig,
286 subject_data: Option<Arc<dyn SubjectData>>,
287 beacon: Option<Arc<dyn BeaconStore>>,
288 subject_registry: Option<Arc<dyn SubjectRegistry>>,
289 subject_stores: Vec<Arc<dyn SubjectDataStore>>,
290}
291
292impl AwpEdgeBuilder {
293 #[must_use]
295 pub fn tiers(mut self, tiers: EdgeTiers) -> Self {
296 self.tiers = tiers;
297 self
298 }
299
300 #[must_use]
302 pub fn limits(mut self, limits: EdgeLimits) -> Self {
303 self.limits = limits;
304 self
305 }
306
307 #[must_use]
309 pub fn stores(mut self, stores: EdgeStores) -> Self {
310 self.stores = Some(stores);
311 self
312 }
313
314 #[must_use]
317 pub fn approval_service(mut self, service: Arc<dyn ApprovalService>) -> Self {
318 self.approval_service = Some(service);
319 self
320 }
321
322 #[must_use]
324 pub fn approval_store(mut self, store: Arc<dyn ApprovalStore>) -> Self {
325 self.approval_store = Some(store);
326 self
327 }
328
329 #[must_use]
331 pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
332 self.ledger = Some(ledger);
333 self
334 }
335
336 #[must_use]
341 pub fn audit(mut self, audit: AuditTrail) -> Self {
342 self.audit = Some(audit);
343 self
344 }
345
346 #[must_use]
349 pub fn principal(mut self, principal: AgentPrincipal) -> Self {
350 self.principal = Some(principal);
351 self
352 }
353
354 #[must_use]
357 pub fn governance(mut self, control: GovernanceControl) -> Self {
358 self.governance = Some(control);
359 self
360 }
361
362 #[must_use]
365 pub fn hold_expiry(mut self, expiry: chrono::Duration) -> Self {
366 self.hold_expiry = Some(expiry);
367 self
368 }
369
370 #[must_use]
372 pub fn agent_card(mut self, card: AgentCardInfo) -> Self {
373 self.card = Some(card);
374 self
375 }
376
377 #[must_use]
382 pub fn public_agent(
383 mut self,
384 factory: impl FnOnce(&PublicTools) -> Arc<dyn Agent> + Send + 'static,
385 ) -> Self {
386 self.agent = Some(Box::new(factory));
387 self
388 }
389
390 #[must_use]
392 pub fn site_search(mut self, search: Arc<dyn SiteSearch>) -> Self {
393 self.search = Some(search);
394 self
395 }
396
397 #[must_use]
399 pub fn threads(mut self, threads: Arc<dyn ThreadSink>) -> Self {
400 self.threads = Some(threads);
401 self
402 }
403
404 #[must_use]
406 pub fn signals(mut self, signals: Arc<dyn SignalEmitter>) -> Self {
407 self.signals = Some(signals);
408 self
409 }
410
411 #[must_use]
415 pub fn conversation_screen(mut self, screen: Arc<dyn ConversationScreen>) -> Self {
416 self.screen = Some(screen);
417 self
418 }
419
420 #[must_use]
422 pub fn reply_policy(mut self, policy: ReplyPolicy) -> Self {
423 self.reply_policy = policy;
424 self
425 }
426
427 #[must_use]
429 pub fn sessions(mut self, sessions: Arc<dyn SessionService>) -> Self {
430 self.sessions = Some(sessions);
431 self
432 }
433
434 #[must_use]
436 pub fn mcp_sessions(mut self, sessions: McpSessions) -> Self {
437 self.mcp_sessions = sessions;
438 self
439 }
440
441 #[must_use]
443 pub fn events(mut self, events: EventsConfig) -> Self {
444 self.events = events;
445 self
446 }
447
448 #[must_use]
450 pub fn event_log(mut self, log: Arc<dyn EventLog>) -> Self {
451 self.event_log = Some(log);
452 self
453 }
454
455 #[must_use]
460 pub fn consent(mut self, consent: ConsentConfig) -> Self {
461 self.consent = consent;
462 self
463 }
464
465 #[must_use]
468 pub fn subject_data(mut self, data: Arc<dyn SubjectData>) -> Self {
469 self.subject_data = Some(data);
470 self
471 }
472
473 #[must_use]
475 pub fn beacon_store(mut self, store: Arc<dyn BeaconStore>) -> Self {
476 self.beacon = Some(store);
477 self
478 }
479
480 #[must_use]
483 pub fn subject_registry(mut self, registry: Arc<dyn SubjectRegistry>) -> Self {
484 self.subject_registry = Some(registry);
485 self
486 }
487
488 #[must_use]
492 pub fn subject_store(mut self, store: Arc<dyn SubjectDataStore>) -> Self {
493 self.subject_stores.push(store);
494 self
495 }
496
497 pub fn build(self) -> Result<AwpEdge, AdkError> {
505 let invalid = |code: &'static str, message: String| {
506 AdkError::new(ErrorComponent::Server, ErrorCategory::InvalidInput, code, message)
507 };
508 if !matches!(self.public_url.scheme(), "http" | "https") {
509 return Err(invalid(
510 "awp.edge.url",
511 "the edge's public URL must be http or https".to_owned(),
512 ));
513 }
514 let domain = self.registry.domain().to_owned();
515 let registry = Arc::new(self.registry);
516 let stores =
517 self.stores.unwrap_or_else(|| EdgeStores::in_memory(&MemoryEdgeStores::default()));
518 let control =
519 Arc::new(EdgeControl::new(Arc::clone(&stores.status), Arc::clone(&self.keys.receipt)));
520 if let Some(governance) = self.governance {
521 control.attach_governance(governance);
522 }
523 let events = EdgeEvents::new(
524 Arc::clone(&stores.subscriptions),
525 self.event_log
526 .or_else(|| stores.event_log.clone())
527 .unwrap_or_else(|| Arc::new(InMemoryEventLog::new())),
528 self.events,
529 self.public_url.as_str(),
530 )?;
531 control.attach_events(events.clone());
532 let references = events.references();
533 let principal = match self.principal {
534 Some(principal) => principal,
535 None => AgentPrincipal::new(
536 AgentId::new(format!("urn:adk:agent:{domain}/awp-edge"))
537 .map_err(|error| invalid("awp.edge.principal", error.to_string()))?,
538 ),
539 };
540 let approval_store = self
541 .approval_service
542 .as_ref()
543 .and_then(|service| service.approval_store())
544 .or(self.approval_store)
545 .unwrap_or_else(|| Arc::new(InMemoryApprovalStore::new()));
546 let subject_registry: Arc<dyn SubjectRegistry> =
547 self.subject_registry.unwrap_or_else(|| Arc::new(InMemorySubjectRegistry::new()));
548 let audit = self.audit.map(|trail| {
550 let recorder = PseudonymousRecorder::new(
551 Arc::clone(trail.recorder()),
552 Arc::clone(&subject_registry),
553 );
554 AuditTrail::new(Arc::new(recorder)).with_failure_mode(trail.failure_mode())
555 });
556 let tiers = Arc::new(self.tiers);
557 let limits = Arc::new(self.limits.classes(tiers.rules().rate_classes.clone()));
558 let policy =
559 Arc::new(CapabilityPolicy::new(Arc::clone(®istry), Arc::clone(&stores.consent)));
560 let executor = GovernedExecutor::from_inner(executor::Inner {
561 registry: Arc::clone(®istry),
562 held_calls: Arc::clone(&stores.held_calls),
563 idempotency: Arc::clone(&stores.idempotency),
564 consent: Arc::clone(&stores.consent),
565 approval_service: self.approval_service,
566 approval_store,
567 ledger: self.ledger.unwrap_or_else(|| Arc::new(InMemoryActionLedger::new())),
568 audit: audit.clone(),
569 principal: principal.clone(),
570 policy,
571 control: Arc::clone(&control),
572 limits: Arc::clone(&limits),
573 hold_expiry: self.hold_expiry,
574 references: references.clone(),
575 });
576 let card = self.card.unwrap_or_else(|| AgentCardInfo {
577 name: domain.clone(),
578 description: format!("The agent edge of {domain}"),
579 version: "2.0".to_owned(),
580 });
581
582 let consent_store: Arc<dyn ConsentStore> =
584 Arc::new(ReceiptConsentStore::new(Arc::clone(&stores.consent)));
585 let gate = ConsentGate::new(Arc::clone(&consent_store))
586 .with_registry(Arc::clone(&subject_registry));
587 let visitors = VisitorTokens::new(Arc::clone(&self.consent.subject_key))
588 .with_ttl(self.consent.session_ttl);
589 let beacon_store = self
590 .beacon
591 .or_else(|| stores.beacon.clone())
592 .unwrap_or_else(|| Arc::new(InMemoryBeaconStore::new()));
593
594 let live = LiveThreads::default();
595 let public = match self.agent {
596 None => None,
597 Some(factory) => {
598 let signals: Arc<dyn SignalEmitter> =
599 self.signals.unwrap_or_else(|| Arc::new(RecordingSignals::new()));
600 let turns = TurnWatch::default();
601 let tools = public::public_tools(
602 &executor,
603 PublicParts {
604 search: self.search.unwrap_or_else(|| Arc::new(StaticSiteIndex::new())),
605 threads: self
606 .threads
607 .unwrap_or_else(|| Arc::new(RecordingThreadSink::new())),
608 signals: Arc::clone(&signals),
609 reply_policy: self.reply_policy,
610 emitted_by: format!("{}#public", principal.id.as_str()),
611 watch: turns.clone(),
612 },
613 &live,
614 );
615 let agent = factory(&tools);
616 let sessions =
617 self.sessions.unwrap_or_else(|| Arc::new(InMemorySessionService::new()));
618 let watch = Watch {
619 turns,
620 screen: self.screen.unwrap_or_else(|| Arc::new(InjectionScreen)),
621 signals,
622 edge: principal.id.as_str().to_owned(),
623 };
624 Some(Arc::new(PublicPartition::new(
625 agent,
626 &tools,
627 sessions,
628 PUBLIC_APP,
629 audit.as_ref(),
630 watch,
631 gate.clone(),
632 )?))
633 }
634 };
635
636 let v2 = awp_v2_routes(
637 EdgeState::builder((*registry).clone())
638 .executor(Arc::new(executor.clone()))
639 .tiers(Arc::clone(&tiers) as Arc<dyn TierAssigner>)
640 .stores(Arc::clone(&stores.status), Arc::clone(&stores.held_calls))
641 .trust_rules(tiers.published_rules().clone())
642 .build(),
643 );
644 let a2a = Arc::new(a2a::A2aBinding::new(
645 executor.clone(),
646 public.clone(),
647 live.clone(),
648 Arc::clone(&control),
649 card.clone(),
650 self.public_url.as_str(),
651 Arc::clone(&self.keys.card),
652 ));
653 let mcp_name = format!("{}/awp", domain.split('.').rev().collect::<Vec<_>>().join("."));
655 let mcp = mcp::router(
656 &executor,
657 Arc::clone(&control),
658 mcp::McpInfo {
659 name: &mcp_name,
660 description: &card.description,
661 version: &card.version,
662 },
663 &self.public_url,
664 self.mcp_sessions,
665 )?;
666 let mut rights =
667 SubjectRights::new(Arc::clone(&subject_registry), Arc::clone(&consent_store))
668 .with_app(PUBLIC_APP)
669 .with_store(Arc::new(BeaconSubjectData::new(Arc::clone(&beacon_store))));
670 if let Some(public) = &public {
671 rights = rights.with_store(Arc::new(SessionSubjectData::new(public.sessions())));
672 }
673 for store in self.subject_stores {
674 rights = rights.with_store(store);
675 }
676 if let Some(audit) = &audit {
677 rights = rights.with_audit(audit.clone());
678 }
679 let consent = consent::ConsentState {
680 tokens: visitors.clone(),
681 rights,
682 config: Arc::new(self.consent),
683 store: Arc::clone(&stores.consent),
684 held_calls: Arc::clone(&stores.held_calls),
685 references,
686 events: events.clone(),
687 signer: Arc::clone(&self.keys.receipt),
688 data: self
689 .subject_data
690 .unwrap_or_else(|| Arc::new(LeadsData::new(Arc::clone(&stores.leads)))),
691 audit: audit.clone(),
692 };
693 let beacon = beacon::BeaconState {
694 store: Arc::clone(&beacon_store),
695 consent: Arc::clone(&stores.consent),
696 };
697 let mut router = Router::new()
698 .merge(v2)
699 .merge(a2a.router())
700 .merge(mcp)
701 .merge(events.router())
702 .merge(consent.router())
703 .merge(beacon.router());
704 if let Some(public) = &public {
705 router = router.route(
706 chat::CHAT_PATH,
707 get(chat::chat).with_state(chat::ChatState {
708 public: Arc::clone(public),
709 live: live.clone(),
710 control: Arc::clone(&control),
711 tokens: visitors.clone(),
712 }),
713 );
714 }
715 let guard = Arc::new(Guard {
716 tiers: Arc::clone(&tiers),
717 limits,
718 control: Arc::clone(&control),
719 executor: executor.clone(),
720 visitors,
721 });
722 let router = router.layer(from_fn_with_state(guard, edge_guard));
723 Ok(AwpEdge {
724 inner: Arc::new(EdgeInner {
725 executor,
726 control,
727 tiers,
728 router,
729 events,
730 beacon: beacon_store,
731 }),
732 })
733 }
734}
735
736struct EdgeInner {
737 executor: GovernedExecutor,
738 control: Arc<EdgeControl>,
739 tiers: Arc<EdgeTiers>,
740 router: Router,
741 events: EdgeEvents,
742 beacon: Arc<dyn BeaconStore>,
743}
744
745#[derive(Clone)]
749pub struct AwpEdge {
750 inner: Arc<EdgeInner>,
751}
752
753impl std::fmt::Debug for AwpEdge {
754 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
755 f.debug_struct("AwpEdge")
756 .field("domain", &self.inner.executor.registry().domain())
757 .field("mode", &self.inner.control.mode())
758 .finish_non_exhaustive()
759 }
760}
761
762impl AwpEdge {
763 pub fn builder(
766 registry: CapabilityRegistry,
767 keys: EdgeKeys,
768 public_url: Url,
769 ) -> AwpEdgeBuilder {
770 AwpEdgeBuilder {
771 registry,
772 keys,
773 public_url,
774 tiers: EdgeTiers::builder().build(),
775 limits: EdgeLimits::default(),
776 stores: None,
777 approval_service: None,
778 approval_store: None,
779 ledger: None,
780 audit: None,
781 principal: None,
782 governance: None,
783 hold_expiry: None,
784 card: None,
785 agent: None,
786 search: None,
787 threads: None,
788 signals: None,
789 screen: None,
790 reply_policy: ReplyPolicy::default(),
791 sessions: None,
792 mcp_sessions: McpSessions::default(),
793 events: EventsConfig::default(),
794 event_log: None,
795 consent: ConsentConfig::default(),
796 subject_data: None,
797 beacon: None,
798 subject_registry: None,
799 subject_stores: Vec::new(),
800 }
801 }
802
803 pub fn router(&self) -> Router {
805 self.inner.router.clone()
806 }
807
808 pub fn executor(&self) -> &GovernedExecutor {
810 &self.inner.executor
811 }
812
813 pub fn published_trust_rules(&self) -> &TrustRules {
815 self.inner.tiers.published_rules()
816 }
817
818 pub fn mode(&self) -> EdgeMode {
820 self.inner.control.mode()
821 }
822
823 pub async fn set_mode(&self, mode: EdgeMode) -> Result<Option<SiteStatus>, StatusError> {
829 self.inner.control.set_mode(mode).await
830 }
831
832 pub fn set_release_seq(&self, seq: u64) {
834 self.inner.control.set_release_seq(seq);
835 }
836
837 pub fn attach_governance(&self, control: GovernanceControl) -> bool {
839 self.inner.control.attach_governance(control)
840 }
841
842 pub fn events(&self) -> &EdgeEvents {
844 &self.inner.events
845 }
846
847 pub fn beacon(&self) -> BeaconCounts {
849 BeaconCounts::new(Arc::clone(&self.inner.beacon))
850 }
851
852 pub fn spawn_delivery_resumer(&self, interval: Duration) -> tokio::task::JoinHandle<()> {
857 let weak: Weak<EdgeInner> = Arc::downgrade(&self.inner);
858 tokio::spawn(async move {
859 let mut ticker = tokio::time::interval(interval);
860 loop {
861 ticker.tick().await;
862 let Some(inner) = weak.upgrade() else { break };
863 if let Err(error) = inner.events.resume_deliveries().await {
864 tracing::warn!(error = %error, "awp delivery resumer failed");
865 }
866 }
867 })
868 }
869
870 pub fn status_control(&self) -> EdgeStatusControl {
873 EdgeStatusControl { control: Arc::clone(&self.inner.control) }
874 }
875
876 pub async fn resolve_held(&self, id: &str) -> Result<Option<HeldCall>, StoreError> {
882 self.inner.executor.resolve(id).await
883 }
884
885 pub fn spawn_resolver(&self, interval: Duration) -> tokio::task::JoinHandle<()> {
888 let weak: Weak<EdgeInner> = Arc::downgrade(&self.inner);
889 tokio::spawn(async move {
890 let mut ticker = tokio::time::interval(interval);
891 loop {
892 ticker.tick().await;
893 let Some(inner) = weak.upgrade() else { break };
894 if let Err(error) = inner.executor.resolve_pending().await {
895 tracing::warn!(error = %error, "awp held-call resolver failed");
896 }
897 }
898 })
899 }
900}
901
902#[derive(Clone)]
917pub struct EdgeStatusControl {
918 control: Arc<EdgeControl>,
919}
920
921impl std::fmt::Debug for EdgeStatusControl {
922 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
923 f.debug_struct("EdgeStatusControl").field("mode", &self.control.mode()).finish()
924 }
925}
926
927impl EdgeStatusControl {
928 pub async fn read_only(&self, reason: &str) -> Result<Option<SiteStatus>, StatusError> {
935 self.control.set_mode(EdgeMode::read_only(reason)).await
936 }
937
938 pub async fn resume(&self) -> Result<Option<SiteStatus>, StatusError> {
944 self.control.set_mode(EdgeMode::Serving).await
945 }
946
947 pub fn mode(&self) -> EdgeMode {
949 self.control.mode()
950 }
951
952 pub fn is_read_only(&self) -> bool {
954 self.control.is_read_only()
955 }
956
957 pub async fn status(&self) -> Option<SiteStatus> {
959 self.control.current_status().await
960 }
961}
962
963struct Guard {
964 tiers: Arc<EdgeTiers>,
965 limits: Arc<EdgeLimits>,
966 control: Arc<EdgeControl>,
967 executor: GovernedExecutor,
968 visitors: VisitorTokens,
969}
970
971const PUBLIC_APP: &str = "awp-public";
973
974async fn edge_guard(State(guard): State<Arc<Guard>>, request: Request, next: Next) -> Response {
976 guard.control.sync_kill_switch().await;
977 if guard.control.is_off() {
978 return StatusCode::NOT_FOUND.into_response();
979 }
980 let (mut parts, mut body) = request.into_parts();
981 let mut caller = match guard.tiers.assess(&parts).await {
982 Ok(caller) => caller,
983 Err(refusal) => {
984 tracing::info!(awp.identity = ?refusal.method, "awp.request.refused");
985 return envelope(
986 ErrorBody::new(
987 ErrorCode::Unauthorized,
988 "the request's credential failed verification",
989 ),
990 None,
991 );
992 }
993 };
994 let standing = match guard.limits.admit_request(&caller).await {
995 Ok(standing) => standing,
996 Err(limited) => {
997 let mut body = ErrorBody::new(
998 ErrorCode::RateLimitExceeded,
999 format!("the caller passed its limit of {} requests a minute", limited.limit),
1000 );
1001 body.retry_after = Some(limited.retry_after);
1002 let mut response = envelope(body, None);
1003 rate_headers(&mut response, &limited.class, limited.limit, 0, limited.retry_after);
1004 return response;
1005 }
1006 };
1007 let mut issued = None;
1010 if caller.requester.is_none() {
1011 let link = parts.uri.query().and_then(|query| {
1012 query
1013 .split('&')
1014 .find_map(|pair| pair.strip_prefix("subject="))
1015 .map(|token| token.replace("%3A", ":").replace("%3a", ":"))
1016 });
1017 let presented = consent::presented_token(&parts.headers, link.as_deref())
1018 .and_then(|token| guard.visitors.verify(&token));
1019 caller.visitor = Some(presented.unwrap_or_else(|| {
1020 let visitor = VisitorId::generate();
1021 issued = Some(guard.visitors.issue(&visitor));
1022 visitor
1023 }));
1024 }
1025 let path = parts.uri.path().to_owned();
1026 if parts.method == Method::POST
1027 && let Some(name) = path.strip_prefix("/awp/v2/capabilities/")
1028 && guard.control.is_read_only()
1029 && guard
1030 .executor
1031 .registry()
1032 .visible(name, caller.tier)
1033 .is_some_and(|tool| tool.declaration().effect != CapabilityEffect::ReadOnly)
1034 {
1035 let mut body = ErrorBody::new(
1036 ErrorCode::ReadOnly,
1037 "the site is read-only; only read-only capabilities answer",
1038 );
1039 body.retryable = true;
1040 return envelope(body, guard.control.current_status().await);
1041 }
1042 if parts.method == Method::POST
1044 && let Some(name) = path.strip_prefix("/awp/v2/capabilities/")
1045 && is_form(&parts.headers)
1046 {
1047 let schema = guard
1048 .executor
1049 .registry()
1050 .visible(name, caller.tier)
1051 .and_then(|tool| tool.declaration().input_schema.clone());
1052 let Ok(bytes) = axum::body::to_bytes(body, adk_awp::v2::routes::MAX_CALL_BODY).await else {
1053 return envelope(
1054 ErrorBody::new(ErrorCode::InvalidRequest, "the body is too large"),
1055 None,
1056 );
1057 };
1058 let form = Request::builder()
1059 .method(Method::POST)
1060 .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1061 .body(axum::body::Body::from(bytes))
1062 .unwrap_or_default();
1063 let Ok(axum::Form(fields)) =
1064 axum::Form::<Vec<(String, String)>>::from_request(form, &()).await
1065 else {
1066 return envelope(
1067 ErrorBody::new(ErrorCode::InvalidRequest, "the form body could not be read"),
1068 None,
1069 );
1070 };
1071 let json = serde_json::to_vec(&form_input(fields, schema.as_ref())).unwrap_or_default();
1072 parts.headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
1073 parts.headers.remove(header::CONTENT_LENGTH);
1074 body = axum::body::Body::from(json);
1075 }
1076 if parts.method == Method::GET
1077 && let Some(id) = path.strip_prefix("/awp/v2/calls/")
1078 && let Err(error) = guard.executor.resolve(id).await
1079 {
1080 tracing::warn!(error = %error, "awp held call could not be resolved");
1081 }
1082 let span = tracing::info_span!(
1083 "awp.request",
1084 awp.requester = caller.requester.as_ref().map_or("", |requester| requester.as_str()),
1085 awp.tier = %caller.tier,
1086 awp.claimed_agent = caller.claimed_agent.as_deref().unwrap_or(""),
1087 http.path = %path,
1088 );
1089 parts.extensions.insert(caller.clone());
1090 let discovery = (parts.method == Method::GET).then(|| discovery_surface(&path)).flatten();
1091 let verified = caller.tier > TrustTier::Public;
1092 let mut response = CURRENT_CALLER
1093 .scope(caller.clone(), next.run(Request::from_parts(parts, body)))
1094 .instrument(span)
1095 .await;
1096 if let Some(surface) = discovery
1097 && verified
1098 && response.status().is_success()
1099 {
1100 guard.executor.record_discovery(&caller, surface).await;
1101 }
1102 rate_headers(
1103 &mut response,
1104 &standing.class,
1105 standing.limit,
1106 standing.remaining,
1107 standing.reset,
1108 );
1109 if let Some(token) = issued
1110 && !response.headers().contains_key(consent::SUBJECT_HEADER)
1111 && let Ok(value) = HeaderValue::from_str(&token)
1112 {
1113 response.headers_mut().insert(consent::SUBJECT_HEADER, value);
1114 }
1115 response
1116}
1117
1118fn discovery_surface(path: &str) -> Option<&'static str> {
1120 match path {
1121 a2a::AGENT_CARD_PATH => Some("agent_card"),
1122 "/awp/v2/manifest" => Some("manifest"),
1123 "/mcp/server-card" | "/.well-known/mcp/server-card.json" => Some("mcp_server_card"),
1124 _ => None,
1125 }
1126}
1127
1128fn is_form(headers: &axum::http::HeaderMap) -> bool {
1129 headers
1130 .get(header::CONTENT_TYPE)
1131 .and_then(|value| value.to_str().ok())
1132 .and_then(|value| value.split(';').next())
1133 .is_some_and(|media| media.trim().eq_ignore_ascii_case("application/x-www-form-urlencoded"))
1134}
1135
1136pub(crate) fn form_input(
1140 fields: Vec<(String, String)>,
1141 schema: Option<&serde_json::Value>,
1142) -> serde_json::Value {
1143 use serde_json::Value;
1144 let declared = |name: &str| -> (Option<String>, Option<String>) {
1145 let property = schema.and_then(|schema| {
1146 schema.pointer(&format!("/properties/{}", name.replace('~', "~0").replace('/', "~1")))
1147 });
1148 let kind = property
1149 .and_then(|property| property.get("type"))
1150 .and_then(Value::as_str)
1151 .map(str::to_owned);
1152 let items = property
1153 .and_then(|property| property.pointer("/items/type"))
1154 .and_then(Value::as_str)
1155 .map(str::to_owned);
1156 (kind, items)
1157 };
1158 let coerce = |raw: &str, kind: Option<&str>| -> Value {
1159 match kind {
1160 Some("integer") => raw
1161 .trim()
1162 .parse::<i64>()
1163 .map_or_else(|_| Value::String(raw.to_owned()), Value::from),
1164 Some("number") => raw
1165 .trim()
1166 .parse::<f64>()
1167 .ok()
1168 .and_then(serde_json::Number::from_f64)
1169 .map_or_else(|| Value::String(raw.to_owned()), Value::Number),
1170 Some("boolean") => match raw.trim().to_ascii_lowercase().as_str() {
1171 "true" | "on" | "1" | "yes" => Value::Bool(true),
1172 "false" | "off" | "0" | "no" => Value::Bool(false),
1173 _ => Value::String(raw.to_owned()),
1174 },
1175 _ => Value::String(raw.to_owned()),
1176 }
1177 };
1178 let mut object = serde_json::Map::new();
1179 let mut grouped: Vec<(String, Vec<String>)> = Vec::new();
1180 for (name, value) in fields {
1181 match grouped.iter_mut().find(|(existing, _)| *existing == name) {
1182 Some((_, values)) => values.push(value),
1183 None => grouped.push((name, vec![value])),
1184 }
1185 }
1186 for (name, values) in grouped {
1187 let (kind, items) = declared(&name);
1188 let value = if kind.as_deref() == Some("array") || values.len() > 1 {
1189 let item_kind = if kind.as_deref() == Some("array") { items } else { kind };
1190 Value::Array(values.iter().map(|value| coerce(value, item_kind.as_deref())).collect())
1191 } else {
1192 coerce(&values[0], kind.as_deref())
1193 };
1194 object.insert(name, value);
1195 }
1196 Value::Object(object)
1197}
1198
1199fn rate_headers(response: &mut Response, class: &str, limit: u32, remaining: u32, reset: u64) {
1201 let headers = response.headers_mut();
1202 if let Ok(policy) = HeaderValue::from_str(&format!("\"{class}\";q={limit};w=60")) {
1203 headers.insert("ratelimit-policy", policy);
1204 }
1205 if let Ok(state) = HeaderValue::from_str(&format!("\"{class}\";r={remaining};t={reset}")) {
1206 headers.insert("ratelimit", state);
1207 }
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212 use super::*;
1213 use serde_json::json;
1214
1215 #[test]
1216 fn form_fields_take_their_schema_types() {
1217 let schema = json!({ "type": "object", "properties": {
1218 "panels": { "type": "integer" },
1219 "kw": { "type": "number" },
1220 "roof": { "type": "boolean" },
1221 "days": { "type": "array", "items": { "type": "integer" } },
1222 } });
1223 let fields = [
1224 ("panels", "4"),
1225 ("kw", "5.5"),
1226 ("roof", "on"),
1227 ("days", "1"),
1228 ("days", "3"),
1229 ("name", "Ana"),
1230 ("tag", "a"),
1231 ("tag", "b"),
1232 ]
1233 .into_iter()
1234 .map(|(name, value)| (name.to_owned(), value.to_owned()))
1235 .collect();
1236 assert_eq!(
1237 form_input(fields, Some(&schema)),
1238 json!({ "panels": 4, "kw": 5.5, "roof": true, "days": [1, 3], "name": "Ana", "tag": ["a", "b"] })
1239 );
1240 let unparsable = vec![("panels".to_owned(), "four".to_owned())];
1241 assert_eq!(form_input(unparsable, Some(&schema)), json!({ "panels": "four" }));
1242 }
1243}