adk-website 3.0.0

A prebuilt AWP 2.0 website for ADK-Rust: site kinds, a team of eight agents, agent-led onboarding, themes, capability packs, playbooks, jobs, alarms and the weekly review
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! The adapters that join the agent edge to the back office and the pipeline (spec 3.5
//! §7.9, §7.10, §7.8.2 step 7, §7.8.3).
//!
//! | Adapter | Implements | Over |
//! |---|---|---|
//! | [`KernelSignals`] | the edge's `SignalEmitter` | the kernel's `SignalSink`, every text field through the harness's screen (A-I3) |
//! | [`ReleaseSearch`] | the edge's `SiteSearch` | the harness's index of the release's Markdown twins |
//! | [`InboxThreads`] | the edge's `ThreadSink` | `adk-drivers`' `ReplyInThread` over the inbox drivers |
//! | [`SiteSubjectData`] | the edge's `SubjectData` | the edge's leads and the site's contact book |
//! | [`EdgeAnnouncer`] | `adk-site`'s `Announcer` | `site.release.published` and `catalog.changed` on the edge's events |
//! | [`DeferredAnnouncer`] | `adk-site`'s `Announcer` | the edge's announcer once it exists: the runtime is built before the edge that reads it |
//! | [`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) |
//! | [`EdgeLiveStore`] | `adk-site`'s `LiveStore` | the live lane's values, read by the edge's read-only capabilities |
//! | [`ReceiptEntrySigner`] | `adk-site`'s `stream::EntrySigner` | the edge's delegated `receipt` key |
//! | [`ReceiptKey`] | `adk-payments`' `ReceiptSigner` and `ReceiptVerifier` | the edge's delegated `receipt` key, for commerce receipts (§7.5) |

use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};

use adk_awp::signing::jws::DocumentSigner;
use adk_awp::v2::store::{ConsentRecord, LeadStore};
use adk_core::{AdkError, Result};
use adk_harness::website::{SIGNAL_FIELD_MAX_CHARS, screen_bounded};
use adk_kernel::charter::SignalSink;
use adk_server::awp::{EdgeEvents, SignalEmitter, SiteHit, SiteSearch, SubjectData, ThreadSink};
use adk_site::live::{LiveStore, LiveValue};
use adk_site::pipeline::{Announcement, Announcer};
use async_trait::async_trait;
use awp_types::{Bounded, ContentId, PublicKeyJwk, Signal, SignalKind, ThreadRef};
use serde_json::{Value, json};
use tokio::sync::RwLock;
use tracing::Instrument as _;
use uuid::Uuid;

use super::handlers::ContactBook;

async fn screened(text: &Bounded) -> Bounded {
    screen_bounded(text.as_str(), SIGNAL_FIELD_MAX_CHARS).await
}

/// Files the edge's signals in the back office's agenda through the kernel's `SignalSink`,
/// every text field screened, redacted, cut and marked untrusted (spec 3.5 §7.10, A-I3).
/// Each signal is filed in a [`KERNEL_SIGNAL`](crate::observability::spans::KERNEL_SIGNAL)
/// span carrying its kind, id and emitter (spec 3.5 §7.24).
pub struct KernelSignals {
    sink: std::sync::RwLock<SignalSink>,
}

impl KernelSignals {
    /// Signals into `sink`, the back office's.
    pub fn new(sink: SignalSink) -> Self {
        Self { sink: std::sync::RwLock::new(sink) }
    }

    /// Files signals through `sink` from now on, such as the kernel's
    /// (`Kernel::signal_sink`), which wakes its `Wake::Signal` sleepers and triggers (spec 3.5
    /// §7.10, §7.20): the edge is built before the kernel that serves it, so the served site
    /// connects its signals once the kernel exists.
    pub fn attach(&self, sink: SignalSink) {
        *self.sink.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
    }
}

#[async_trait]
impl SignalEmitter for KernelSignals {
    async fn emit(&self, signal: Signal) -> Result<()> {
        let span = tracing::info_span!(
            crate::observability::spans::KERNEL_SIGNAL,
            signal.kind = signal.kind.name(),
            signal.id = %signal.id,
            signal.emitted_by = %signal.emitted_by,
        );
        self.file(signal).instrument(span).await
    }
}

impl KernelSignals {
    async fn file(&self, mut signal: Signal) -> Result<()> {
        match &mut signal.kind {
            SignalKind::LeadCaptured { answers, .. } => {
                for value in answers.values_mut() {
                    *value = screened(value).await;
                }
            }
            SignalKind::ContentGap { topic, samples, .. } => {
                *topic = screened(topic).await;
                for sample in samples.iter_mut() {
                    *sample = screened(sample).await;
                }
            }
            SignalKind::ReviewSeen { excerpt, .. } => *excerpt = screened(excerpt).await,
            _ => {}
        }
        let sink = self.sink.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
        sink.emit(signal).await.map(|_| ()).map_err(|e| AdkError::config(e.to_string()))
    }
}

/// The edge's search over the harness's index of the release (spec 3.5 §7.10).
pub struct ReleaseSearch {
    index: Arc<adk_harness::website::SiteSearch>,
}

impl ReleaseSearch {
    /// Search over `index`, reindexed after each release.
    pub fn new(index: Arc<adk_harness::website::SiteSearch>) -> Self {
        Self { index }
    }
}

#[async_trait]
impl SiteSearch for ReleaseSearch {
    async fn search(&self, query: &str, limit: usize) -> Result<Vec<SiteHit>> {
        Ok(self
            .index
            .search(query, limit)
            .into_iter()
            .map(|hit| SiteHit { path: hit.url, title: hit.title, snippet: hit.snippet })
            .collect())
    }
}

/// In-thread replies through the inbox drivers (spec 3.5 §7.10 `reply_in_thread`).
pub struct InboxThreads {
    reply: Arc<adk_drivers::ReplyInThread>,
    template: String,
}

impl InboxThreads {
    /// Replies through `reply` with the playbook template `template`, whose `body` field
    /// carries the text.
    pub fn new(reply: Arc<adk_drivers::ReplyInThread>, template: impl Into<String>) -> Self {
        Self { reply, template: template.into() }
    }
}

#[async_trait]
impl ThreadSink for InboxThreads {
    async fn reply(&self, thread: &ThreadRef, text: &str) -> Result<()> {
        let fields = BTreeMap::from([("body".to_string(), text.to_string())]);
        self.reply
            .reply(&thread.0, &self.template, &fields)
            .await
            .map(|_| ())
            .map_err(|e| AdkError::config(e.to_string()))
    }
}

/// A subject's data for export and erasure: the leads and the contacts their consent
/// receipts reference (spec 3.5 §7.5 "Consent").
pub struct SiteSubjectData {
    leads: Arc<dyn LeadStore>,
    contacts: Arc<dyn ContactBook>,
}

impl SiteSubjectData {
    /// The data in `leads` and `contacts`.
    pub fn new(leads: Arc<dyn LeadStore>, contacts: Arc<dyn ContactBook>) -> Self {
        Self { leads, contacts }
    }
}

fn receipt_ids(receipts: &[ConsentRecord]) -> Vec<Uuid> {
    receipts.iter().map(|record| record.receipt.id).collect()
}

#[async_trait]
impl SubjectData for SiteSubjectData {
    async fn export(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<Value> {
        let ids = receipt_ids(receipts);
        let leads: Vec<Value> = self
            .leads
            .since(chrono::DateTime::<chrono::Utc>::MIN_UTC)
            .await
            .map_err(|e| AdkError::config(e.to_string()))?
            .into_iter()
            .filter(|lead| lead.consent.iter().any(|r| ids.contains(&r.0)))
            .map(|lead| json!(lead))
            .collect();
        let contacts = self.contacts.by_receipts(&ids).await?;
        Ok(json!({ "leads": leads, "contacts": contacts }))
    }

    async fn erase(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<usize> {
        // A lead keeps only a reference; the contact book holds the person's details.
        self.contacts.erase(&receipt_ids(receipts)).await
    }
}

/// Announces releases on the edge's events (spec 3.5 §7.8.2 step 7, §7.8.3 "Events").
pub struct EdgeAnnouncer {
    events: EdgeEvents,
}

impl EdgeAnnouncer {
    /// Announces on `events`, the edge's.
    pub fn new(events: EdgeEvents) -> Self {
        Self { events }
    }
}

#[async_trait]
impl Announcer for EdgeAnnouncer {
    async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
        let fail = |e: adk_awp::v2::store::StoreError| adk_site::SiteError::Pipeline(e.to_string());
        self.events.release_published(announcement.release.clone()).await.map_err(fail)?;
        if let Some(catalog) = &announcement.catalog {
            self.events
                .announce_catalog(catalog.clone(), announcement.catalog_pages.clone())
                .await
                .map_err(fail)?;
        }
        Ok(())
    }
}

/// The pipeline's announcer, set once the edge exists (spec 3.5 §7.8.2 step 7): the site
/// runtime is built first, so its pipeline announces through this; a release published
/// before the edge is set is not announced.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use adk_website::edge::adapters::DeferredAnnouncer;
///
/// let deferred = Arc::new(DeferredAnnouncer::default());
/// assert!(!deferred.is_set());
/// ```
#[derive(Default)]
pub struct DeferredAnnouncer {
    target: OnceLock<Arc<dyn Announcer>>,
}

impl DeferredAnnouncer {
    /// Announces through `target` from now on; returns `false` when one was already set.
    pub fn set(&self, target: Arc<dyn Announcer>) -> bool {
        self.target.set(target).is_ok()
    }

    /// Whether the target is set.
    pub fn is_set(&self) -> bool {
        self.target.get().is_some()
    }
}

#[async_trait]
impl Announcer for DeferredAnnouncer {
    async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
        match self.target.get() {
            Some(target) => target.announce(announcement).await,
            None => {
                tracing::debug!(
                    release = announcement.release.seq,
                    "no edge yet; release not announced"
                );
                Ok(())
            }
        }
    }
}

/// The served site's documents for the launch gate's `awp verify` against the preview (spec
/// 3.5 §7.8.1 "Machine views"): what the release does not hold, such as the Agent Card the
/// edge serves, is read from the site's router once it exists. The runtime and its gate are
/// built before the edge, so the router is set afterwards; until then such a document is
/// unavailable.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use adk_awp::verify::fetch::RouterFetcher;
/// use adk_website::edge::adapters::DeferredFetcher;
///
/// let deferred = Arc::new(DeferredFetcher::default());
/// assert!(deferred.set(Arc::new(RouterFetcher::new(axum::Router::new()))));
/// ```
#[derive(Default)]
pub struct DeferredFetcher {
    target: OnceLock<Arc<dyn adk_awp::verify::fetch::Fetcher>>,
}

impl DeferredFetcher {
    /// Fetches through `target` from now on; returns `false` when one was already set.
    pub fn set(&self, target: Arc<dyn adk_awp::verify::fetch::Fetcher>) -> bool {
        self.target.set(target).is_ok()
    }
}

#[async_trait]
impl adk_awp::verify::fetch::Fetcher for DeferredFetcher {
    async fn get(
        &self,
        url: &str,
        headers: &axum::http::HeaderMap,
    ) -> std::result::Result<adk_awp::verify::fetch::Fetched, adk_awp::verify::fetch::FetchError>
    {
        match self.target.get() {
            Some(target) => target.get(url, headers).await,
            None => Err(adk_awp::verify::fetch::FetchError {
                url: url.to_string(),
                reason: "the site's edge is not serving yet".into(),
            }),
        }
    }
}

/// The live lane's values (spec 3.5 §7.8.3 "Three lanes"): written by the update engine,
/// read by the edge's read-only capabilities; never a claim (A-I26).
#[derive(Debug, Default)]
pub struct EdgeLiveStore {
    values: RwLock<BTreeMap<ContentId, BTreeMap<String, LiveValue>>>,
}

#[async_trait]
impl LiveStore for EdgeLiveStore {
    async fn set(
        &self,
        id: &ContentId,
        values: BTreeMap<String, LiveValue>,
    ) -> adk_site::Result<()> {
        self.values.write().await.entry(id.clone()).or_default().extend(values);
        Ok(())
    }

    async fn get(&self, id: &ContentId) -> adk_site::Result<BTreeMap<String, LiveValue>> {
        Ok(self.values.read().await.get(id).cloned().unwrap_or_default())
    }
}

/// Signs stream entries with the edge's delegated `receipt` key (spec 3.5 §7.8.3 "Stream").
pub struct ReceiptEntrySigner {
    signer: Arc<dyn DocumentSigner>,
}

impl ReceiptEntrySigner {
    /// Entries signed by `signer`, the edge's `receipt` key.
    pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
        Self { signer }
    }
}

#[async_trait]
impl adk_site::stream::EntrySigner for ReceiptEntrySigner {
    fn kid(&self) -> &str {
        self.signer.kid()
    }

    fn public_key(&self) -> PublicKeyJwk {
        self.signer.public_key()
    }

    async fn sign(&self, message: &[u8]) -> adk_site::Result<Vec<u8>> {
        self.signer.sign(message).await.map_err(|e| adk_site::SiteError::Pipeline(e.to_string()))
    }
}

/// Signs and checks commerce receipts with the edge's delegated `receipt` key (spec 3.5
/// §7.5 "Commerce"): a detached JWS over the receipt's JCS form, which any agent verifies
/// against the site's published keys.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
///
/// use adk_awp::signing::jws::Ed25519DocumentSigner;
/// use adk_payments::wallet::{ReceiptDetails, issue_receipt, verify_receipt};
/// use adk_website::edge::adapters::ReceiptKey;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
/// let key = ReceiptKey::new(Arc::new(Ed25519DocumentSigner::from_seed("receipt-2026-10", [7; 32]).unwrap()));
/// let details = ReceiptDetails::new("pay_order", "order-1", 1_350, "KES").with_rail("ap2");
/// let receipt = issue_receipt(&key, details, chrono::Utc::now()).await.unwrap();
/// assert!(verify_receipt(&key, &receipt).await.is_ok());
/// # }
/// ```
pub struct ReceiptKey {
    signer: Arc<dyn DocumentSigner>,
}

impl ReceiptKey {
    /// Receipts signed by `signer`, the edge's `receipt` key.
    pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
        Self { signer }
    }
}

fn receipt_error(code: &'static str, error: impl std::fmt::Display) -> AdkError {
    AdkError::new(
        adk_core::ErrorComponent::Tool,
        adk_core::ErrorCategory::Unauthorized,
        code,
        format!("the receipt's signature: {error}"),
    )
}

#[async_trait]
impl adk_payments::wallet::ReceiptSigner for ReceiptKey {
    async fn sign(&self, document: &Value) -> Result<awp_types::Proof> {
        adk_awp::signing::jws::sign(document, self.signer.as_ref())
            .await
            .map_err(|error| receipt_error("website.receipt.unsigned", error))
    }
}

#[async_trait]
impl adk_payments::wallet::ReceiptVerifier for ReceiptKey {
    async fn verify(&self, document: &Value, proof: &awp_types::Proof) -> Result<()> {
        adk_awp::signing::jws::verify(document, proof, &self.signer.public_key())
            .map_err(|error| receipt_error("website.receipt.invalid", error))
    }
}