Skip to main content

adk_server/awp/
mod.rs

1//! The AWP 2.0 agent edge (spec 3.5 §7.3, §7.4, §7.9, §7.10; feature `awp`).
2//!
3//! [`AwpEdge`] serves a site's capabilities to people and agents and hosts its public
4//! partition. Mount it with [`ServerBuilder::awp`](crate::ServerBuilder::awp), which merges it
5//! through `add_root_routes`, so the server's host guard, CORS, timeouts and security headers
6//! apply, and attaches the server's kill switch.
7//!
8//! | Route | Purpose | Module |
9//! |---|---|---|
10//! | `GET /.well-known/agent-card.json` | The signed A2A card, one skill per capability the caller sees | [`a2a`] |
11//! | `POST /awp/v2/a2a`, `/awp/v2/a2a/v1/…` | A2A v1.0 JSON-RPC and HTTP+JSON: capabilities and conversation | [`a2a`] |
12//! | `/mcp`, `/mcp/server-card`, `/.well-known/mcp/server-card.json` | The capabilities as MCP tools | [`mcp`] |
13//! | `GET /awp/v2/manifest`, `GET /awp/v2/status`, `GET /awp/v2/trust` | Contract surfaces | `adk_awp::v2::routes` |
14//! | `POST /awp/v2/capabilities/{name}`, `GET /awp/v2/calls/{id}` | Invocation and held-call status | `adk_awp::v2::routes`, [`executor`] |
15//! | `GET /awp/v2/chat` (WebSocket) | The on-site assistant | [`chat`] |
16//!
17//! Every request first passes the edge's guard: the edge's mode, the caller's tier from its
18//! verified credentials ([`tiers`]), and its rate limit ([`limits`]). All three capability
19//! bindings enter one governed path ([`executor`]) under a policy compiled from the manifest
20//! ([`policy`]). The edge exposes no owner route: the owner's control plane is the kernel's.
21//!
22//! A verified caller's fetch of the Agent Card, the capability manifest or the MCP Server
23//! Card is recorded as `awp.request.verified` with its `awp.surface`, so verified agent
24//! discovery is counted (spec 3.5 §7.12, §9.3).
25//!
26//! # Example
27//!
28//! ```rust,no_run
29//! use std::sync::Arc;
30//!
31//! use adk_awp::signing::jws::Ed25519DocumentSigner;
32//! use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityRegistry};
33//! use adk_core::Url;
34//! use adk_server::awp::{AwpEdge, EdgeKeys};
35//! use awp_types::{CapabilityEffect, CapabilityV2};
36//! use serde_json::{Value, json};
37//!
38//! struct Hours;
39//!
40//! #[async_trait::async_trait]
41//! impl CapabilityHandler for Hours {
42//!     async fn handle(&self, _call: CapabilityCall) -> Result<Value, CapabilityError> {
43//!         Ok(json!({ "open": "08:00", "close": "17:00" }))
44//!     }
45//! }
46//!
47//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
48//! let mut registry = CapabilityRegistry::new("example.com");
49//! registry.declare(CapabilityV2::new("opening_hours", "Opening hours", CapabilityEffect::ReadOnly), Arc::new(Hours))?;
50//! let keys = EdgeKeys {
51//!     card: Arc::new(Ed25519DocumentSigner::generate("edge-card-2026-10")?),
52//!     receipt: Arc::new(Ed25519DocumentSigner::generate("edge-receipt-2026-10")?),
53//! };
54//! let edge = AwpEdge::builder(registry, keys, Url::parse("https://agent.example.com")?).build()?;
55//! let app: axum::Router = edge.router();
56//! # let _ = app;
57//! # Ok(())
58//! # }
59//! ```
60
61pub 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/// The edge's delegated signing keys (spec 3.5 §7.2, D-11; AWP 2.0 §5.3, C3).
137///
138/// The root key never reaches the edge; these are short-lived keys the root delegated.
139#[derive(Clone)]
140pub struct EdgeKeys {
141    /// Signs the A2A Agent Card (scope `card`).
142    pub card: Arc<dyn DocumentSigner>,
143    /// Signs the site status, consent receipts and stream entries (scope `receipt`).
144    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/// The edge's durable stores (spec 3.5 §7.9).
157#[derive(Clone)]
158#[non_exhaustive]
159pub struct EdgeStores {
160    /// The current signed status.
161    pub status: Arc<dyn StatusStore>,
162    /// Calls held for the owner.
163    pub held_calls: Arc<dyn HeldCallStore>,
164    /// Outcomes of keyed calls, replayed in full.
165    pub idempotency: Arc<dyn IdempotencyStore>,
166    /// Consent receipts.
167    pub consent: Arc<dyn ConsentReceiptStore>,
168    /// Event subscriptions.
169    pub subscriptions: Arc<dyn SubscriptionStore>,
170    /// Leads captured at the edge.
171    pub leads: Arc<dyn LeadStore>,
172    /// Events retained for replay, catalogue pages, consent references and pending
173    /// deliveries; the builder's [`event_log`](AwpEdgeBuilder::event_log), else in memory.
174    pub event_log: Option<Arc<dyn EventLog>>,
175    /// The beacon's daily counts; the builder's
176    /// [`beacon_store`](AwpEdgeBuilder::beacon_store), else in memory.
177    pub beacon: Option<Arc<dyn BeaconStore>>,
178}
179
180impl EdgeStores {
181    /// Stores over the given backends.
182    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    /// Keeps event subscriptions in `subscriptions`; in memory by default.
202    #[must_use]
203    pub fn with_subscriptions(mut self, subscriptions: Arc<dyn SubscriptionStore>) -> Self {
204        self.subscriptions = subscriptions;
205        self
206    }
207
208    /// Keeps leads in `leads`; in memory by default.
209    #[must_use]
210    pub fn with_leads(mut self, leads: Arc<dyn LeadStore>) -> Self {
211        self.leads = leads;
212        self
213    }
214
215    /// Retains events, catalogue pages, consent references and pending deliveries in `log`,
216    /// so they survive a restart (spec 3.5 §7.5).
217    #[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    /// Keeps the beacon's daily counts in `beacon` (spec 3.5 §7.12).
224    #[must_use]
225    pub fn with_beacon(mut self, beacon: Arc<dyn BeaconStore>) -> Self {
226        self.beacon = Some(beacon);
227        self
228    }
229
230    /// The in-memory `stores`, shared with the caller's handle.
231    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
249/// Answers an AWP error envelope with the `AWP-Version` field.
250pub(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
259/// Builds an [`AwpEdge`].
260pub 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    /// Sets how callers earn tiers; the default makes every caller `public` (A-I6).
294    #[must_use]
295    pub fn tiers(mut self, tiers: EdgeTiers) -> Self {
296        self.tiers = tiers;
297        self
298    }
299
300    /// Sets the rate limits; rate classes the tiers define are added to them.
301    #[must_use]
302    pub fn limits(mut self, limits: EdgeLimits) -> Self {
303        self.limits = limits;
304        self
305    }
306
307    /// Sets the edge stores; the default keeps them in memory.
308    #[must_use]
309    pub fn stores(mut self, stores: EdgeStores) -> Self {
310        self.stores = Some(stores);
311        self
312    }
313
314    /// Sends held calls to the owner's approval service (spec 3.3); its store is where the
315    /// owner's decisions are read from.
316    #[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    /// Sets the approval store held calls wait in, when no approval service provides one.
323    #[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    /// Sets the action ledger `non_idempotent` calls are recorded in; in memory by default.
330    #[must_use]
331    pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
332        self.ledger = Some(ledger);
333        self
334    }
335
336    /// Records governed decisions, `awp.capability.*` records and verified discovery
337    /// (`awp.request.verified`) on `audit`. The edge wraps its recorder in a
338    /// [`PseudonymousRecorder`] over the subject
339    /// registry, so records name visitors by pseudonym, never by visitor id.
340    #[must_use]
341    pub fn audit(mut self, audit: AuditTrail) -> Self {
342        self.audit = Some(audit);
343        self
344    }
345
346    /// Sets the site's own principal, the acting agent of every call; by default
347    /// `urn:adk:agent:{domain}/awp-edge`.
348    #[must_use]
349    pub fn principal(mut self, principal: AgentPrincipal) -> Self {
350        self.principal = Some(principal);
351        self
352    }
353
354    /// Attaches the owner's kill switch; [`ServerBuilder::awp`](crate::ServerBuilder::awp)
355    /// attaches the server's when none is set.
356    #[must_use]
357    pub fn governance(mut self, control: GovernanceControl) -> Self {
358        self.governance = Some(control);
359        self
360    }
361
362    /// Gives every held call an `expiresAt` this long after it is held; without it a call
363    /// waits as long as the owner takes.
364    #[must_use]
365    pub fn hold_expiry(mut self, expiry: chrono::Duration) -> Self {
366        self.hold_expiry = Some(expiry);
367        self
368    }
369
370    /// Sets the Agent Card's name, description and version.
371    #[must_use]
372    pub fn agent_card(mut self, card: AgentCardInfo) -> Self {
373        self.card = Some(card);
374        self
375    }
376
377    /// Hosts the site's public agent, built from the tools the edge gives it (spec 3.5 §7.10).
378    ///
379    /// The agent answers A2A messages that name no capability and `GET /awp/v2/chat`, under
380    /// [`PublicPartitionPolicy`]: whatever tools it holds, only [`PublicTools`] run.
381    #[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    /// Sets the search behind `search_site`; an empty index by default.
391    #[must_use]
392    pub fn site_search(mut self, search: Arc<dyn SiteSearch>) -> Self {
393        self.search = Some(search);
394        self
395    }
396
397    /// Sets where `reply_in_thread` delivers replies outside the edge's own chat sockets.
398    #[must_use]
399    pub fn threads(mut self, threads: Arc<dyn ThreadSink>) -> Self {
400        self.threads = Some(threads);
401        self
402    }
403
404    /// Sets where `emit_signal` files signals; the kernel's `SignalSink` in `adk-website`.
405    #[must_use]
406    pub fn signals(mut self, signals: Arc<dyn SignalEmitter>) -> Self {
407        self.signals = Some(signals);
408        self
409    }
410
411    /// Sets the screen conversation input passes before the public agent reads it; a flagged
412    /// turn the agent files no signal for gets one from the edge (spec 3.5 §7.10, S7).
413    /// [`InjectionScreen`] by default.
414    #[must_use]
415    pub fn conversation_screen(mut self, screen: Arc<dyn ConversationScreen>) -> Self {
416        self.screen = Some(screen);
417        self
418    }
419
420    /// Sets the template and pace of `reply_in_thread`.
421    #[must_use]
422    pub fn reply_policy(mut self, policy: ReplyPolicy) -> Self {
423        self.reply_policy = policy;
424        self
425    }
426
427    /// Sets the session service public conversations are kept in; in memory by default.
428    #[must_use]
429    pub fn sessions(mut self, sessions: Arc<dyn SessionService>) -> Self {
430        self.sessions = Some(sessions);
431        self
432    }
433
434    /// Sets how the MCP endpoint keeps sessions; stateful by default.
435    #[must_use]
436    pub fn mcp_sessions(mut self, sessions: McpSessions) -> Self {
437        self.mcp_sessions = sessions;
438        self
439    }
440
441    /// Sets the event catalogue, retries, retention and egress policy (spec 3.5 §7.5).
442    #[must_use]
443    pub fn events(mut self, events: EventsConfig) -> Self {
444        self.events = events;
445        self
446    }
447
448    /// Sets where events are retained for replay; the stores' event log, else in memory.
449    #[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    /// Sets the consent scopes, policy versions and the subject session key (spec 3.5 §7.5).
456    ///
457    /// The subject key also keys the ids of public visitors, so a key kept across restarts
458    /// keeps their conversations; the default key is random per process.
459    #[must_use]
460    pub fn consent(mut self, consent: ConsentConfig) -> Self {
461        self.consent = consent;
462        self
463    }
464
465    /// Sets the data `GET /awp/v2/consent/export` and `POST /awp/v2/consent/erase` cover;
466    /// by default the leads referencing the subject's receipts ([`LeadsData`]).
467    #[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    /// Sets where the beacon counts; the stores' beacon store, else in memory.
474    #[must_use]
475    pub fn beacon_store(mut self, store: Arc<dyn BeaconStore>) -> Self {
476        self.beacon = Some(store);
477        self
478    }
479
480    /// Sets the subject registry: visitors' pseudonyms, links, and erasure state. A visitor
481    /// being erased can neither converse nor consent. In memory by default.
482    #[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    /// Adds a store that `GET /awp/v2/consent/export` and `POST /awp/v2/consent/erase` reach,
489    /// such as the memory or artifacts the public agent writes. The public partition's sessions
490    /// and the beacon's visitor sets are always reached.
491    #[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    /// Builds the edge.
498    ///
499    /// # Errors
500    ///
501    /// An `AdkError` when the public URL is not an `http` or `https` origin, the principal's id
502    /// is invalid, or the event delivery client, the MCP server or the public agent's runner
503    /// cannot be built.
504    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        // Records name visitors by pseudonym; erasure deletes the pseudonym.
549        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(&registry), Arc::clone(&stores.consent)));
560        let executor = GovernedExecutor::from_inner(executor::Inner {
561            registry: Arc::clone(&registry),
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        // One source of consent: the receipts, which the gates and subject rights both read.
583        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        // SEP-2127 names a server in reverse DNS with one '/': `com.example/awp`.
654        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/// The AWP 2.0 agent edge of one site (spec 3.5 §7.9).
746///
747/// Cheap to clone; clones share the edge.
748#[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    /// Starts a builder for the site whose capabilities `registry` holds, signing with `keys`,
764    /// served at `public_url`, the edge origin.
765    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    /// The edge's routes, guarded; [`ServerBuilder::awp`](crate::ServerBuilder::awp) mounts them.
804    pub fn router(&self) -> Router {
805        self.inner.router.clone()
806    }
807
808    /// The governed executor every binding shares.
809    pub fn executor(&self) -> &GovernedExecutor {
810        &self.inner.executor
811    }
812
813    /// The trust rules published at `GET /awp/v2/trust`.
814    pub fn published_trust_rules(&self) -> &TrustRules {
815        self.inner.tiers.published_rules()
816    }
817
818    /// The edge's mode.
819    pub fn mode(&self) -> EdgeMode {
820        self.inner.control.mode()
821    }
822
823    /// Switches the mode and publishes the signed status it implies (spec 3.5 §7.9, A-I11).
824    ///
825    /// # Errors
826    ///
827    /// [`StatusError`] when the status cannot be signed or stored; the mode still changes.
828    pub async fn set_mode(&self, mode: EdgeMode) -> Result<Option<SiteStatus>, StatusError> {
829        self.inner.control.set_mode(mode).await
830    }
831
832    /// Records the release being served, named in the status the edge signs.
833    pub fn set_release_seq(&self, seq: u64) {
834        self.inner.control.set_release_seq(seq);
835    }
836
837    /// Attaches the owner's kill switch unless one is attached; returns whether it was.
838    pub fn attach_governance(&self, control: GovernanceControl) -> bool {
839        self.inner.control.attach_governance(control)
840    }
841
842    /// The event publisher: releases, catalogue changes and order updates (spec 3.5 §7.5).
843    pub fn events(&self) -> &EdgeEvents {
844        &self.inner.events
845    }
846
847    /// The beacon's daily counts, for the KPI tracker's `beacon` source (spec 3.5 §7.12).
848    pub fn beacon(&self) -> BeaconCounts {
849        BeaconCounts::new(Arc::clone(&self.inner.beacon))
850    }
851
852    /// Resumes, every `interval` until the edge is dropped, the event deliveries a stopped
853    /// process left in a durable [`EventLog`], so retries survive a restart (spec 3.5 §7.5);
854    /// see [`EdgeEvents::resume_deliveries`]. With a log that keeps no deliveries it finds
855    /// nothing.
856    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    /// A handle that switches the edge to read-only and back, for the back office's incident
871    /// path (spec 3.5 A-I11).
872    pub fn status_control(&self) -> EdgeStatusControl {
873        EdgeStatusControl { control: Arc::clone(&self.inner.control) }
874    }
875
876    /// Resolves held call `id` if the owner decided it; see [`GovernedExecutor::resolve`].
877    ///
878    /// # Errors
879    ///
880    /// [`StoreError`] when the held-call store fails.
881    pub async fn resolve_held(&self, id: &str) -> Result<Option<HeldCall>, StoreError> {
882        self.inner.executor.resolve(id).await
883    }
884
885    /// Resolves pending held calls every `interval` until the edge is dropped, so decisions
886    /// take effect without a requester polling (spec 3.5 §7.4).
887    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/// Switches an edge to read-only and back (spec 3.5 §7.9, A-I11).
903///
904/// Switching the edge to read-only is one of the two incident acts an owner may
905/// pre-authorise; a back-office tool holds this handle, never the edge itself. Each switch
906/// publishes the signed status it implies.
907///
908/// # Example
909///
910/// ```rust,ignore
911/// let control = edge.status_control();
912/// control.read_only("drift_detected").await?;
913/// // ... rollback to the last signed release ...
914/// control.resume().await?;
915/// ```
916#[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    /// Puts the edge in read-only mode for `reason`, a snake_case code such as
929    /// `drift_detected`, and publishes a `read_only` status.
930    ///
931    /// # Errors
932    ///
933    /// [`StatusError`] when the status cannot be signed or stored; the mode still changes.
934    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    /// Returns the edge to serving and publishes an `operational` status.
939    ///
940    /// # Errors
941    ///
942    /// [`StatusError`] when the status cannot be signed or stored; the mode still changes.
943    pub async fn resume(&self) -> Result<Option<SiteStatus>, StatusError> {
944        self.control.set_mode(EdgeMode::Serving).await
945    }
946
947    /// The edge's mode; the kill switch is reported by [`is_read_only`](Self::is_read_only).
948    pub fn mode(&self) -> EdgeMode {
949        self.control.mode()
950    }
951
952    /// Whether non-read-only capabilities are refused: read-only mode or the kill switch.
953    pub fn is_read_only(&self) -> bool {
954        self.control.is_read_only()
955    }
956
957    /// The current signed status, if one was published.
958    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
971/// The application name of the public partition's sessions.
972const PUBLIC_APP: &str = "awp-public";
973
974/// The edge's guard: mode, caller, rate limit, and the HTTP binding's read-only answer.
975async 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    // A public caller converses as the visitor its token names, else as a new random one
1008    // whose token the response hands back; nothing is derived from the request.
1009    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    // A frozen static site's forms post form-encoded; the HTTP binding reads JSON.
1043    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
1118/// The discovery surface a path serves, for `awp.request.verified` (spec 3.5 §7.12).
1119fn 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
1136/// The JSON input of a form-encoded call: each field a string, or the type its input schema
1137/// declares (`integer`, `number`, `boolean`, `array`); a repeated field is an array (spec 3.5
1138/// §7.8 freeze, §7.9).
1139pub(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
1199/// The rate-limit fields of draft-ietf-httpapi-ratelimit-headers (AWP 2.0 §6.6).
1200fn 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}