Skip to main content

adk_website/edge/
adapters.rs

1//! The adapters that join the agent edge to the back office and the pipeline (spec 3.5
2//! §7.9, §7.10, §7.8.2 step 7, §7.8.3).
3//!
4//! | Adapter | Implements | Over |
5//! |---|---|---|
6//! | [`KernelSignals`] | the edge's `SignalEmitter` | the kernel's `SignalSink`, every text field through the harness's screen (A-I3) |
7//! | [`ReleaseSearch`] | the edge's `SiteSearch` | the harness's index of the release's Markdown twins |
8//! | [`InboxThreads`] | the edge's `ThreadSink` | `adk-drivers`' `ReplyInThread` over the inbox drivers |
9//! | [`SiteSubjectData`] | the edge's `SubjectData` | the edge's leads and the site's contact book |
10//! | [`EdgeAnnouncer`] | `adk-site`'s `Announcer` | `site.release.published` and `catalog.changed` on the edge's events |
11//! | [`DeferredAnnouncer`] | `adk-site`'s `Announcer` | the edge's announcer once it exists: the runtime is built before the edge that reads it |
12//! | [`DeferredFetcher`] | `adk-awp`'s verifier `Fetcher` | the served site's router once it exists, for the launch gate's `awp verify` against the preview (§7.8.1) |
13//! | [`EdgeLiveStore`] | `adk-site`'s `LiveStore` | the live lane's values, read by the edge's read-only capabilities |
14//! | [`ReceiptEntrySigner`] | `adk-site`'s `stream::EntrySigner` | the edge's delegated `receipt` key |
15//! | [`ReceiptKey`] | `adk-payments`' `ReceiptSigner` and `ReceiptVerifier` | the edge's delegated `receipt` key, for commerce receipts (§7.5) |
16
17use std::collections::BTreeMap;
18use std::sync::{Arc, OnceLock};
19
20use adk_awp::signing::jws::DocumentSigner;
21use adk_awp::v2::store::{ConsentRecord, LeadStore};
22use adk_core::{AdkError, Result};
23use adk_harness::website::{SIGNAL_FIELD_MAX_CHARS, screen_bounded};
24use adk_kernel::charter::SignalSink;
25use adk_server::awp::{EdgeEvents, SignalEmitter, SiteHit, SiteSearch, SubjectData, ThreadSink};
26use adk_site::live::{LiveStore, LiveValue};
27use adk_site::pipeline::{Announcement, Announcer};
28use async_trait::async_trait;
29use awp_types::{Bounded, ContentId, PublicKeyJwk, Signal, SignalKind, ThreadRef};
30use serde_json::{Value, json};
31use tokio::sync::RwLock;
32use tracing::Instrument as _;
33use uuid::Uuid;
34
35use super::handlers::ContactBook;
36
37async fn screened(text: &Bounded) -> Bounded {
38    screen_bounded(text.as_str(), SIGNAL_FIELD_MAX_CHARS).await
39}
40
41/// Files the edge's signals in the back office's agenda through the kernel's `SignalSink`,
42/// every text field screened, redacted, cut and marked untrusted (spec 3.5 §7.10, A-I3).
43/// Each signal is filed in a [`KERNEL_SIGNAL`](crate::observability::spans::KERNEL_SIGNAL)
44/// span carrying its kind, id and emitter (spec 3.5 §7.24).
45pub struct KernelSignals {
46    sink: std::sync::RwLock<SignalSink>,
47}
48
49impl KernelSignals {
50    /// Signals into `sink`, the back office's.
51    pub fn new(sink: SignalSink) -> Self {
52        Self { sink: std::sync::RwLock::new(sink) }
53    }
54
55    /// Files signals through `sink` from now on, such as the kernel's
56    /// (`Kernel::signal_sink`), which wakes its `Wake::Signal` sleepers and triggers (spec 3.5
57    /// §7.10, §7.20): the edge is built before the kernel that serves it, so the served site
58    /// connects its signals once the kernel exists.
59    pub fn attach(&self, sink: SignalSink) {
60        *self.sink.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
61    }
62}
63
64#[async_trait]
65impl SignalEmitter for KernelSignals {
66    async fn emit(&self, signal: Signal) -> Result<()> {
67        let span = tracing::info_span!(
68            crate::observability::spans::KERNEL_SIGNAL,
69            signal.kind = signal.kind.name(),
70            signal.id = %signal.id,
71            signal.emitted_by = %signal.emitted_by,
72        );
73        self.file(signal).instrument(span).await
74    }
75}
76
77impl KernelSignals {
78    async fn file(&self, mut signal: Signal) -> Result<()> {
79        match &mut signal.kind {
80            SignalKind::LeadCaptured { answers, .. } => {
81                for value in answers.values_mut() {
82                    *value = screened(value).await;
83                }
84            }
85            SignalKind::ContentGap { topic, samples, .. } => {
86                *topic = screened(topic).await;
87                for sample in samples.iter_mut() {
88                    *sample = screened(sample).await;
89                }
90            }
91            SignalKind::ReviewSeen { excerpt, .. } => *excerpt = screened(excerpt).await,
92            _ => {}
93        }
94        let sink = self.sink.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
95        sink.emit(signal).await.map(|_| ()).map_err(|e| AdkError::config(e.to_string()))
96    }
97}
98
99/// The edge's search over the harness's index of the release (spec 3.5 §7.10).
100pub struct ReleaseSearch {
101    index: Arc<adk_harness::website::SiteSearch>,
102}
103
104impl ReleaseSearch {
105    /// Search over `index`, reindexed after each release.
106    pub fn new(index: Arc<adk_harness::website::SiteSearch>) -> Self {
107        Self { index }
108    }
109}
110
111#[async_trait]
112impl SiteSearch for ReleaseSearch {
113    async fn search(&self, query: &str, limit: usize) -> Result<Vec<SiteHit>> {
114        Ok(self
115            .index
116            .search(query, limit)
117            .into_iter()
118            .map(|hit| SiteHit { path: hit.url, title: hit.title, snippet: hit.snippet })
119            .collect())
120    }
121}
122
123/// In-thread replies through the inbox drivers (spec 3.5 §7.10 `reply_in_thread`).
124pub struct InboxThreads {
125    reply: Arc<adk_drivers::ReplyInThread>,
126    template: String,
127}
128
129impl InboxThreads {
130    /// Replies through `reply` with the playbook template `template`, whose `body` field
131    /// carries the text.
132    pub fn new(reply: Arc<adk_drivers::ReplyInThread>, template: impl Into<String>) -> Self {
133        Self { reply, template: template.into() }
134    }
135}
136
137#[async_trait]
138impl ThreadSink for InboxThreads {
139    async fn reply(&self, thread: &ThreadRef, text: &str) -> Result<()> {
140        let fields = BTreeMap::from([("body".to_string(), text.to_string())]);
141        self.reply
142            .reply(&thread.0, &self.template, &fields)
143            .await
144            .map(|_| ())
145            .map_err(|e| AdkError::config(e.to_string()))
146    }
147}
148
149/// A subject's data for export and erasure: the leads and the contacts their consent
150/// receipts reference (spec 3.5 §7.5 "Consent").
151pub struct SiteSubjectData {
152    leads: Arc<dyn LeadStore>,
153    contacts: Arc<dyn ContactBook>,
154}
155
156impl SiteSubjectData {
157    /// The data in `leads` and `contacts`.
158    pub fn new(leads: Arc<dyn LeadStore>, contacts: Arc<dyn ContactBook>) -> Self {
159        Self { leads, contacts }
160    }
161}
162
163fn receipt_ids(receipts: &[ConsentRecord]) -> Vec<Uuid> {
164    receipts.iter().map(|record| record.receipt.id).collect()
165}
166
167#[async_trait]
168impl SubjectData for SiteSubjectData {
169    async fn export(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<Value> {
170        let ids = receipt_ids(receipts);
171        let leads: Vec<Value> = self
172            .leads
173            .since(chrono::DateTime::<chrono::Utc>::MIN_UTC)
174            .await
175            .map_err(|e| AdkError::config(e.to_string()))?
176            .into_iter()
177            .filter(|lead| lead.consent.iter().any(|r| ids.contains(&r.0)))
178            .map(|lead| json!(lead))
179            .collect();
180        let contacts = self.contacts.by_receipts(&ids).await?;
181        Ok(json!({ "leads": leads, "contacts": contacts }))
182    }
183
184    async fn erase(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<usize> {
185        // A lead keeps only a reference; the contact book holds the person's details.
186        self.contacts.erase(&receipt_ids(receipts)).await
187    }
188}
189
190/// Announces releases on the edge's events (spec 3.5 §7.8.2 step 7, §7.8.3 "Events").
191pub struct EdgeAnnouncer {
192    events: EdgeEvents,
193}
194
195impl EdgeAnnouncer {
196    /// Announces on `events`, the edge's.
197    pub fn new(events: EdgeEvents) -> Self {
198        Self { events }
199    }
200}
201
202#[async_trait]
203impl Announcer for EdgeAnnouncer {
204    async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
205        let fail = |e: adk_awp::v2::store::StoreError| adk_site::SiteError::Pipeline(e.to_string());
206        self.events.release_published(announcement.release.clone()).await.map_err(fail)?;
207        if let Some(catalog) = &announcement.catalog {
208            self.events
209                .announce_catalog(catalog.clone(), announcement.catalog_pages.clone())
210                .await
211                .map_err(fail)?;
212        }
213        Ok(())
214    }
215}
216
217/// The pipeline's announcer, set once the edge exists (spec 3.5 §7.8.2 step 7): the site
218/// runtime is built first, so its pipeline announces through this; a release published
219/// before the edge is set is not announced.
220///
221/// # Example
222///
223/// ```rust
224/// use std::sync::Arc;
225///
226/// use adk_website::edge::adapters::DeferredAnnouncer;
227///
228/// let deferred = Arc::new(DeferredAnnouncer::default());
229/// assert!(!deferred.is_set());
230/// ```
231#[derive(Default)]
232pub struct DeferredAnnouncer {
233    target: OnceLock<Arc<dyn Announcer>>,
234}
235
236impl DeferredAnnouncer {
237    /// Announces through `target` from now on; returns `false` when one was already set.
238    pub fn set(&self, target: Arc<dyn Announcer>) -> bool {
239        self.target.set(target).is_ok()
240    }
241
242    /// Whether the target is set.
243    pub fn is_set(&self) -> bool {
244        self.target.get().is_some()
245    }
246}
247
248#[async_trait]
249impl Announcer for DeferredAnnouncer {
250    async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
251        match self.target.get() {
252            Some(target) => target.announce(announcement).await,
253            None => {
254                tracing::debug!(
255                    release = announcement.release.seq,
256                    "no edge yet; release not announced"
257                );
258                Ok(())
259            }
260        }
261    }
262}
263
264/// The served site's documents for the launch gate's `awp verify` against the preview (spec
265/// 3.5 §7.8.1 "Machine views"): what the release does not hold, such as the Agent Card the
266/// edge serves, is read from the site's router once it exists. The runtime and its gate are
267/// built before the edge, so the router is set afterwards; until then such a document is
268/// unavailable.
269///
270/// # Example
271///
272/// ```rust
273/// use std::sync::Arc;
274///
275/// use adk_awp::verify::fetch::RouterFetcher;
276/// use adk_website::edge::adapters::DeferredFetcher;
277///
278/// let deferred = Arc::new(DeferredFetcher::default());
279/// assert!(deferred.set(Arc::new(RouterFetcher::new(axum::Router::new()))));
280/// ```
281#[derive(Default)]
282pub struct DeferredFetcher {
283    target: OnceLock<Arc<dyn adk_awp::verify::fetch::Fetcher>>,
284}
285
286impl DeferredFetcher {
287    /// Fetches through `target` from now on; returns `false` when one was already set.
288    pub fn set(&self, target: Arc<dyn adk_awp::verify::fetch::Fetcher>) -> bool {
289        self.target.set(target).is_ok()
290    }
291}
292
293#[async_trait]
294impl adk_awp::verify::fetch::Fetcher for DeferredFetcher {
295    async fn get(
296        &self,
297        url: &str,
298        headers: &axum::http::HeaderMap,
299    ) -> std::result::Result<adk_awp::verify::fetch::Fetched, adk_awp::verify::fetch::FetchError>
300    {
301        match self.target.get() {
302            Some(target) => target.get(url, headers).await,
303            None => Err(adk_awp::verify::fetch::FetchError {
304                url: url.to_string(),
305                reason: "the site's edge is not serving yet".into(),
306            }),
307        }
308    }
309}
310
311/// The live lane's values (spec 3.5 §7.8.3 "Three lanes"): written by the update engine,
312/// read by the edge's read-only capabilities; never a claim (A-I26).
313#[derive(Debug, Default)]
314pub struct EdgeLiveStore {
315    values: RwLock<BTreeMap<ContentId, BTreeMap<String, LiveValue>>>,
316}
317
318#[async_trait]
319impl LiveStore for EdgeLiveStore {
320    async fn set(
321        &self,
322        id: &ContentId,
323        values: BTreeMap<String, LiveValue>,
324    ) -> adk_site::Result<()> {
325        self.values.write().await.entry(id.clone()).or_default().extend(values);
326        Ok(())
327    }
328
329    async fn get(&self, id: &ContentId) -> adk_site::Result<BTreeMap<String, LiveValue>> {
330        Ok(self.values.read().await.get(id).cloned().unwrap_or_default())
331    }
332}
333
334/// Signs stream entries with the edge's delegated `receipt` key (spec 3.5 §7.8.3 "Stream").
335pub struct ReceiptEntrySigner {
336    signer: Arc<dyn DocumentSigner>,
337}
338
339impl ReceiptEntrySigner {
340    /// Entries signed by `signer`, the edge's `receipt` key.
341    pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
342        Self { signer }
343    }
344}
345
346#[async_trait]
347impl adk_site::stream::EntrySigner for ReceiptEntrySigner {
348    fn kid(&self) -> &str {
349        self.signer.kid()
350    }
351
352    fn public_key(&self) -> PublicKeyJwk {
353        self.signer.public_key()
354    }
355
356    async fn sign(&self, message: &[u8]) -> adk_site::Result<Vec<u8>> {
357        self.signer.sign(message).await.map_err(|e| adk_site::SiteError::Pipeline(e.to_string()))
358    }
359}
360
361/// Signs and checks commerce receipts with the edge's delegated `receipt` key (spec 3.5
362/// §7.5 "Commerce"): a detached JWS over the receipt's JCS form, which any agent verifies
363/// against the site's published keys.
364///
365/// # Example
366///
367/// ```rust
368/// use std::sync::Arc;
369///
370/// use adk_awp::signing::jws::Ed25519DocumentSigner;
371/// use adk_payments::wallet::{ReceiptDetails, issue_receipt, verify_receipt};
372/// use adk_website::edge::adapters::ReceiptKey;
373///
374/// # #[tokio::main(flavor = "current_thread")]
375/// # async fn main() {
376/// let key = ReceiptKey::new(Arc::new(Ed25519DocumentSigner::from_seed("receipt-2026-10", [7; 32]).unwrap()));
377/// let details = ReceiptDetails::new("pay_order", "order-1", 1_350, "KES").with_rail("ap2");
378/// let receipt = issue_receipt(&key, details, chrono::Utc::now()).await.unwrap();
379/// assert!(verify_receipt(&key, &receipt).await.is_ok());
380/// # }
381/// ```
382pub struct ReceiptKey {
383    signer: Arc<dyn DocumentSigner>,
384}
385
386impl ReceiptKey {
387    /// Receipts signed by `signer`, the edge's `receipt` key.
388    pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
389        Self { signer }
390    }
391}
392
393fn receipt_error(code: &'static str, error: impl std::fmt::Display) -> AdkError {
394    AdkError::new(
395        adk_core::ErrorComponent::Tool,
396        adk_core::ErrorCategory::Unauthorized,
397        code,
398        format!("the receipt's signature: {error}"),
399    )
400}
401
402#[async_trait]
403impl adk_payments::wallet::ReceiptSigner for ReceiptKey {
404    async fn sign(&self, document: &Value) -> Result<awp_types::Proof> {
405        adk_awp::signing::jws::sign(document, self.signer.as_ref())
406            .await
407            .map_err(|error| receipt_error("website.receipt.unsigned", error))
408    }
409}
410
411#[async_trait]
412impl adk_payments::wallet::ReceiptVerifier for ReceiptKey {
413    async fn verify(&self, document: &Value, proof: &awp_types::Proof) -> Result<()> {
414        adk_awp::signing::jws::verify(document, proof, &self.signer.public_key())
415            .map_err(|error| receipt_error("website.receipt.invalid", error))
416    }
417}