Skip to main content

adk_website/edge/
mod.rs

1//! The site on the agent edge (spec 3.5 §7.9, §7.10, §7.16 `packs`, §7.20, A-I11).
2//!
3//! `adk-server`'s `AwpEdge` serves the site's capabilities over A2A, MCP and HTTP from one
4//! declaration under one governed path. [`SiteEdge::build`] gives it the kind's capability
5//! declarations with the packs' [`handlers`], the [`adapters`] to the back office, and returns
6//! the handles the rest of the product uses:
7//!
8//! | Handle | Use |
9//! |---|---|
10//! | [`SiteEdge::status`] | The incident path's [`EdgeStatus`]: drift puts the edge in read-only mode, a person's close resumes it (A-I11) |
11//! | [`SiteEdge::read_only_tool`] | The Guardian's `edge_read_only` tool, the second reversible incident act |
12//! | [`SiteEdge::announcer`] | The pipeline's announcer: releases and catalog changes on the edge's events |
13//! | [`stream_router`] | The stream lane's feed a live page polls |
14//! | [`site_router`] | The edge's routes with the release the host serves behind them |
15//! | [`consent_config`] | The consent scopes the kind's capabilities ask for |
16//!
17//! Payments go through the owner's [`handlers::PaymentDesk`]: [`ap2::Ap2Desk`] for AP2
18//! mandates, [`token::TokenDesk`] for token rails, [`token::PaymentRails`] for both.
19//! Bookings go through a [`handlers::Calendar`]: [`caldav::CalDavCalendar`] over the owner's
20//! CalDAV calendar, or [`commerce::StoredCalendar`] (in memory, [`handlers::InMemoryCalendar`])
21//! from `calendar.json`. Quotes, orders and the bookings of `calendar.json`'s slots live in a
22//! [`commerce::CommerceStore`]: [`SiteEdge::build_with_commerce`] takes a durable one,
23//! [`SiteEdge::build`] keeps them in memory.
24//!
25//! The declarations and their handlers come from the site's capability packs (spec 3.5
26//! §7.23): [`SiteEdge::build_with_packs`] serves the kind's capabilities and every capability
27//! of the packs a site installed ([`PackSet`]), each with the built-in handler its pack's
28//! configuration names; the other constructors serve the built-in packs.
29
30pub mod adapters;
31pub mod ap2;
32pub mod caldav;
33pub mod commerce;
34pub mod handlers;
35pub mod token;
36
37use std::collections::BTreeMap;
38use std::sync::Arc;
39
40use adk_awp::v2::capability::{CapabilityHandler, CapabilityRegistry};
41use adk_core::audit_log::AuditTrail;
42use adk_core::{
43    ActionLedger, AdkError, Agent, ApprovalService, Llm, Result, Tool, ToolContext, ToolEffect, Url,
44};
45use adk_harness::website::SitePartitions;
46use adk_harness::website::SiteRuntime;
47use adk_kernel::Partitions;
48use adk_server::awp::{
49    AwpEdge, BeaconStore, ConsentConfig, ConsentPolicy, EdgeKeys, EdgeLimits, EdgeStatusControl,
50    EdgeStores, EdgeTiers, PublicTools, SignalEmitter, SiteSearch, ThreadSink,
51};
52use adk_site::host::SiteHost;
53use async_trait::async_trait;
54use awp_types::{CapabilityV2, ConsentScope, SiteState};
55use chrono::Duration;
56use serde_json::{Value, json};
57
58use self::adapters::{EdgeAnnouncer, EdgeLiveStore, SiteSubjectData};
59use self::handlers::{
60    BookingHandler, Calendar, ContactBook, FormHandler, InMemoryCalendar, ListingHandler,
61    OrderBook, OrderHandler, PaymentDesk, PaymentHandler, PublishedContent, QuoteBook,
62    QuoteHandler, SearchHandler, StatusHandler,
63};
64use crate::incident::{InMemoryStatusBoard, StatusRecord, StatusSink};
65use crate::kinds::KindTemplate;
66use crate::packs::bundle::HandlerConfig;
67use crate::packs::installed::{Dispatched, PackSet};
68use crate::team::{AgentRole, SiteTeam};
69
70/// What a site's edge is built from (spec 3.5 §7.9).
71pub struct SiteEdgeParts {
72    /// The site's kind, whose capabilities the edge declares.
73    pub template: KindTemplate,
74    /// The site runtime: published content and the release.
75    pub runtime: Arc<SiteRuntime>,
76    /// The edge's delegated `card` and `receipt` keys.
77    pub keys: EdgeKeys,
78    /// The edge's public URL, such as `https://agent.example.com`.
79    pub edge_url: Url,
80    /// The edge's stores.
81    pub stores: EdgeStores,
82    /// Signals into the back office ([`adapters::KernelSignals`]).
83    pub signals: Arc<dyn SignalEmitter>,
84    /// The release's index ([`adapters::ReleaseSearch`]).
85    pub search: Arc<dyn SiteSearch>,
86    /// The site's contact book.
87    pub contacts: Arc<dyn ContactBook>,
88    /// The bookable slots; none open without one.
89    pub calendar: Option<Arc<dyn Calendar>>,
90    /// The owner's payment rail, such as an [`ap2::Ap2Desk`]; payments are refused without
91    /// one.
92    pub payments: Option<Arc<dyn PaymentDesk>>,
93    /// The owner's amount thresholds: orders, bookings and payments above them wait for the
94    /// owner's decision (spec 3.5 §7.4, S9).
95    pub thresholds: crate::packs::ApprovalThresholds,
96    /// The kernel's approval service, where held calls wait for the owner.
97    pub approvals: Option<Arc<dyn ApprovalService>>,
98    /// Trust tiers; every caller is `public` without them.
99    pub tiers: Option<EdgeTiers>,
100    /// Consent scopes and policies.
101    pub consent: Option<ConsentConfig>,
102    /// In-thread replies ([`adapters::InboxThreads`]).
103    pub threads: Option<Arc<dyn ThreadSink>>,
104    /// How long a quote keeps its price (A-I25).
105    pub quote_validity: Duration,
106    /// The action ledger non-idempotent calls run exactly once through (A-I7), such as
107    /// `measurement::MeteredActionLedger`.
108    pub action_ledger: Option<Arc<dyn ActionLedger>>,
109    /// Where the edge's audit records go, such as through `measurement::EdgeMeter`.
110    pub audit: Option<AuditTrail>,
111    /// Where the beacon counts; in memory without one.
112    pub beacon: Option<Arc<dyn BeaconStore>>,
113    /// The edge's rate limits; the edge's defaults without them.
114    pub limits: Option<EdgeLimits>,
115    /// The public agent the chat and A2A conversation run, such as [`concierge`]; none
116    /// without one.
117    pub public_agent: Option<PublicAgentFactory>,
118}
119
120/// Builds the public agent over the edge's own tools.
121pub type PublicAgentFactory = Box<dyn FnOnce(&PublicTools) -> Arc<dyn Agent> + Send>;
122
123/// The Concierge over the edge's public tools (spec 3.5 §7.10, §7.19, A-I2, A-I3): the
124/// website preset in the site's public partition with the kind's instruction, and exactly the
125/// tools the edge's public policy admits — the declared capabilities, `reply_in_thread` and
126/// the edge's `emit_signal`, which files signals through the kernel's sink. A declared
127/// `search_site` capability is the site's search; the edge's own one is left out so no two
128/// tools share the name.
129///
130/// The agent is built with `adk-harness`' `website_public_served` over the edge's tools, not
131/// with the kit's own `search_site` and `emit_signal`, which the edge's public policy would
132/// refuse: the manifest decides each tool, the harness's `PublicPolicy` admits only the
133/// public tools, the agent is offered nothing else, and the edge's governed path holds the
134/// calls its manifest holds.
135pub fn concierge(
136    team: &SiteTeam,
137    partitions: &SitePartitions,
138    table: Partitions,
139    model: Arc<dyn Llm>,
140    workspace: impl Into<std::path::PathBuf>,
141) -> PublicAgentFactory {
142    let instruction = match team.public_instruction() {
143        "" => AgentRole::Concierge.prompt().to_string(),
144        kind => format!("{}\n\n{kind}", AgentRole::Concierge.prompt()),
145    };
146    let partitions = partitions.clone();
147    let workspace = workspace.into();
148    Box::new(move |tools: &PublicTools| {
149        // The manifest decides (spec 3.5 §7.19 "Manifest policy"): the public policy admits
150        // only these tools, and the edge's governed path holds what the manifest holds.
151        let served = adk_harness::website::ServedPublicTools {
152            partitions: partitions.clone(),
153            table,
154            search_site: tools.search_site.clone(),
155            reply_in_thread: Some(tools.reply_in_thread.clone()),
156            emit_signal: tools.emit_signal.clone(),
157            capabilities: tools.capabilities.iter().map(|tool| (tool.clone(), false)).collect(),
158        };
159        let builder = adk_harness::HarnessAgent::builder(AgentRole::Concierge.as_str())
160            .model(model.clone())
161            .workspace(adk_devtools::Workspace::new(&workspace))
162            .website_public_served(served)
163            .instruction(instruction.clone());
164        match builder.build() {
165            Ok(agent) => Arc::new(agent) as Arc<dyn Agent>,
166            Err(error) => {
167                tracing::error!(error = %error, "the Concierge did not build; a plain agent answers");
168                let declared_search =
169                    tools.capabilities.iter().any(|tool| tool.name() == "search_site");
170                let mut fallback = adk_agent::LlmAgentBuilder::new(AgentRole::Concierge.as_str())
171                    .model(model)
172                    .instruction(instruction);
173                for tool in tools.capabilities.iter().cloned().chain(
174                    [
175                        (!declared_search).then(|| tools.search_site.clone()),
176                        Some(tools.reply_in_thread.clone()),
177                        Some(tools.emit_signal.clone()),
178                    ]
179                    .into_iter()
180                    .flatten(),
181                ) {
182                    fallback = fallback.tool(tool);
183                }
184                Arc::new(fallback.build().expect("an LlmAgent with a model builds"))
185            }
186        }
187    })
188}
189
190/// A site's edge and its handles (spec 3.5 §7.9).
191pub struct SiteEdge {
192    /// The edge; mount it with `ServerBuilder::awp`.
193    pub edge: AwpEdge,
194    /// The quotes it issued.
195    pub quotes: Arc<QuoteBook>,
196    /// The orders placed.
197    pub orders: Arc<OrderBook>,
198    /// The live lane's values.
199    pub live: Arc<EdgeLiveStore>,
200}
201
202impl SiteEdge {
203    /// The kind's capability declarations with the packs' handlers (spec 3.5 §7.16 `packs`),
204    /// each under the owner's amount threshold (§7.4), from the built-in packs.
205    ///
206    /// # Errors
207    ///
208    /// A threshold on a capability whose calls carry no amount, or a declaration the
209    /// registry refuses.
210    pub fn registry(
211        parts: &SiteEdgeParts,
212        quotes: &Arc<QuoteBook>,
213        orders: &Arc<OrderBook>,
214    ) -> Result<CapabilityRegistry> {
215        Self::registry_with_packs(parts, quotes, orders, &PackSet::builtin()?)
216    }
217
218    /// The capabilities `packs` serve for the kind ([`PackSet::served`]), each with the
219    /// built-in handler its pack's configuration names and under the owner's amount threshold
220    /// (spec 3.5 §7.4, §7.23).
221    ///
222    /// # Errors
223    ///
224    /// A threshold on a capability whose calls carry no amount, or a declaration the
225    /// registry refuses.
226    pub fn registry_with_packs(
227        parts: &SiteEdgeParts,
228        quotes: &Arc<QuoteBook>,
229        orders: &Arc<OrderBook>,
230        packs: &PackSet,
231    ) -> Result<CapabilityRegistry> {
232        Self::registry_of(parts, quotes, orders, packs.served(&parts.template))
233    }
234
235    fn registry_of(
236        parts: &SiteEdgeParts,
237        quotes: &Arc<QuoteBook>,
238        orders: &Arc<OrderBook>,
239        served: Vec<(CapabilityV2, HandlerConfig)>,
240    ) -> Result<CapabilityRegistry> {
241        let site = parts.runtime.site();
242        let domain = Url::parse(&site.origin)
243            .ok()
244            .and_then(|url| url.host_str().map(str::to_string))
245            .unwrap_or_else(|| site.name.clone());
246        let content = PublishedContent::new(parts.runtime.clone());
247        let forms = Arc::new(FormHandler::new(
248            parts.stores.leads.clone(),
249            parts.contacts.clone(),
250            parts.signals.clone(),
251            AgentRole::AgentDesk.principal(site),
252        ));
253        let calendar = parts
254            .calendar
255            .clone()
256            .unwrap_or_else(|| Arc::new(InMemoryCalendar::default()) as Arc<dyn Calendar>);
257        let booking: Arc<dyn CapabilityHandler> =
258            Arc::new(BookingHandler::new(calendar, forms.clone()));
259        parts.thresholds.validate()?;
260        let mut order = OrderHandler::new(quotes.clone(), orders.clone());
261        if let Some(desk) = &parts.payments {
262            order = order.with_payments(desk.clone());
263        }
264        let order: Arc<dyn CapabilityHandler> = Arc::new(order);
265        let mut payment = PaymentHandler::new(parts.payments.clone()).with_orders(orders.clone());
266        if let Some(audit) = &parts.audit {
267            payment = payment.with_audit(audit.clone());
268        }
269        let payment: Arc<dyn CapabilityHandler> = Arc::new(payment);
270        let mut registry = CapabilityRegistry::new(domain);
271        for (declaration, config) in served {
272            let declaration = parts.thresholds.apply(declaration);
273            let handler: Arc<dyn CapabilityHandler> = match config {
274                HandlerConfig::Form => forms.clone(),
275                HandlerConfig::Quote => Arc::new(QuoteHandler::new(
276                    content.clone(),
277                    quotes.clone(),
278                    parts.quote_validity,
279                )),
280                HandlerConfig::Order { .. } => order.clone(),
281                HandlerConfig::Payment => payment.clone(),
282                HandlerConfig::Booking { .. } => booking.clone(),
283                HandlerConfig::Search => Arc::new(SearchHandler::new(parts.search.clone())),
284                HandlerConfig::Listing { content: kind } => {
285                    Arc::new(ListingHandler::new(content.clone(), kind))
286                }
287                HandlerConfig::Status => Arc::new(StatusHandler::new(parts.stores.leads.clone())),
288            };
289            // A pack's capability reaches a handler that dispatches on a built-in name as
290            // that name (spec 3.5 §7.23).
291            let handler = match config.dispatches_as() {
292                Some(builtin) if builtin != declaration.name => {
293                    Arc::new(Dispatched::new(builtin, handler)) as Arc<dyn CapabilityHandler>
294                }
295                _ => handler,
296            };
297            registry
298                .declare(declaration, handler)
299                .map_err(|error| AdkError::config(error.to_string()))?;
300        }
301        Ok(registry)
302    }
303
304    /// Builds the site's edge (spec 3.5 §7.9).
305    ///
306    /// # Errors
307    ///
308    /// A refused declaration, or the edge builder's error.
309    pub fn build(parts: SiteEdgeParts) -> Result<Self> {
310        Self::build_with_commerce(parts, Arc::new(commerce::InMemoryCommerceStore::default()))
311    }
312
313    /// Builds the site's edge with its quotes and orders in `commerce`, such as a served
314    /// site's [`commerce::SqliteCommerceStore`] in `data/edge.db`, so they survive a restart
315    /// (spec 3.5 §7.5, §7.9).
316    ///
317    /// # Errors
318    ///
319    /// A refused declaration, or the edge builder's error.
320    pub fn build_with_commerce(
321        parts: SiteEdgeParts,
322        commerce: Arc<dyn commerce::CommerceStore>,
323    ) -> Result<Self> {
324        Self::build_with_packs(parts, commerce, &PackSet::builtin()?)
325    }
326
327    /// Builds the site's edge over `packs`, such as a served site's [`PackDir::load`]
328    /// (spec 3.5 §7.9, §7.23): the kind's capabilities and those of the installed packs, each
329    /// with the handler its pack configures, quotes and orders in `commerce`. The consent
330    /// scopes the served capabilities ask for join `parts.consent`'s.
331    ///
332    /// [`PackDir::load`]: crate::packs::installed::PackDir::load
333    ///
334    /// # Errors
335    ///
336    /// A refused declaration, or the edge builder's error.
337    ///
338    /// # Example
339    ///
340    /// ```rust,no_run
341    /// use std::sync::Arc;
342    ///
343    /// use adk_website::edge::commerce::InMemoryCommerceStore;
344    /// use adk_website::edge::{SiteEdge, SiteEdgeParts};
345    /// use adk_website::packs::installed::PackDir;
346    ///
347    /// fn edge(parts: SiteEdgeParts, project: &std::path::Path) -> adk_core::Result<SiteEdge> {
348    ///     let packs = PackDir::new(project).load()?;
349    ///     SiteEdge::build_with_packs(parts, Arc::new(InMemoryCommerceStore::default()), &packs)
350    /// }
351    /// ```
352    pub fn build_with_packs(
353        mut parts: SiteEdgeParts,
354        commerce: Arc<dyn commerce::CommerceStore>,
355        packs: &PackSet,
356    ) -> Result<Self> {
357        let quotes = Arc::new(QuoteBook::new(commerce.clone()));
358        let orders = Arc::new(OrderBook::new(commerce));
359        let served = packs.served(&parts.template);
360        if let Some(consent) = parts.consent.as_mut() {
361            for (declaration, _) in &served {
362                if let Some(required) = &declaration.consent
363                    && !consent.scopes.contains(&required.scope)
364                {
365                    consent.scopes.push(required.scope.clone());
366                }
367            }
368        }
369        let registry = Self::registry_of(&parts, &quotes, &orders, served)?;
370        let mut builder = AwpEdge::builder(registry, parts.keys, parts.edge_url)
371            .stores(parts.stores.clone())
372            .signals(parts.signals.clone())
373            .site_search(parts.search.clone())
374            .subject_data(Arc::new(SiteSubjectData::new(
375                parts.stores.leads.clone(),
376                parts.contacts.clone(),
377            )))
378            .principal(
379                adk_harness::website::SitePartitions::new(parts.runtime.site())
380                    .public()
381                    .principal(&parts.runtime.site().name, AgentRole::AgentDesk.as_str()),
382            );
383        if let Some(tiers) = parts.tiers {
384            builder = builder.tiers(tiers);
385        }
386        if let Some(approvals) = parts.approvals {
387            builder = builder.approval_service(approvals);
388        }
389        if let Some(consent) = parts.consent {
390            builder = builder.consent(consent);
391        }
392        if let Some(threads) = parts.threads {
393            builder = builder.threads(threads);
394        }
395        if let Some(ledger) = parts.action_ledger {
396            builder = builder.action_ledger(ledger);
397        }
398        if let Some(audit) = parts.audit {
399            builder = builder.audit(audit);
400        }
401        if let Some(beacon) = parts.beacon {
402            builder = builder.beacon_store(beacon);
403        }
404        if let Some(limits) = parts.limits {
405            builder = builder.limits(limits);
406        }
407        if let Some(agent) = parts.public_agent {
408            builder = builder.public_agent(agent);
409        }
410        Ok(Self {
411            edge: builder.build()?,
412            quotes,
413            orders,
414            live: Arc::new(EdgeLiveStore::default()),
415        })
416    }
417
418    /// The incident path's status: the edge's signed status and read-only mode (A-I11).
419    pub fn status(&self) -> EdgeStatus {
420        EdgeStatus::new(self.edge.status_control())
421    }
422
423    /// The Guardian's `edge_read_only` tool (spec 3.5 A-I11).
424    pub fn read_only_tool(&self) -> Arc<dyn Tool> {
425        Arc::new(EdgeReadOnlyTool { control: self.edge.status_control() })
426    }
427
428    /// The pipeline's announcer over the edge's events (spec 3.5 §7.8.2 step 7).
429    pub fn announcer(&self) -> Arc<EdgeAnnouncer> {
430        Arc::new(EdgeAnnouncer::new(self.edge.events().clone()))
431    }
432}
433
434/// The consent the kind asks for (spec 3.5 §7.5, A-I8): every scope a declaration names, and
435/// `nurture` when the kind nurtures its leads ([`crate::leads::consent_scopes`]), under the packs' [`POLICY_VERSION`](crate::packs::POLICY_VERSION) with
436/// `policy` as its text, and subject sessions keyed by `subject_key` (at least 32 bytes).
437///
438/// # Example
439///
440/// ```rust
441/// use adk_server::awp::ConsentPolicy;
442/// use adk_website::edge::consent_config;
443/// use adk_website::kinds::template;
444/// use awp_types::{ConsentScope, Digest, SiteKind};
445///
446/// let policy = ConsentPolicy { digest: Digest::from_sha256_bytes([1; 32]), ttl: None };
447/// let consent = consent_config(&template(SiteKind::Business), policy, vec![7u8; 32]);
448/// assert!(consent.scopes.contains(&ConsentScope::from("contact")));
449/// assert!(consent.scopes.contains(&ConsentScope::from("nurture")), "a business nurtures its leads");
450/// ```
451pub fn consent_config(
452    template: &KindTemplate,
453    policy: ConsentPolicy,
454    subject_key: impl Into<Arc<[u8]>>,
455) -> ConsentConfig {
456    let scopes: Vec<ConsentScope> = crate::leads::consent_scopes(template);
457    let policies = BTreeMap::from([(crate::packs::POLICY_VERSION.to_string(), policy)]);
458    ConsentConfig::new(scopes, policies, subject_key)
459}
460
461/// The site's public router (spec 3.5 §7.9, §7.22): the edge's routes, and behind them the
462/// files of the release `host` serves, each with its release media type, HSTS, and a CSP on
463/// pages; before the launch `/` answers the holding page of the site `name`.
464pub fn site_router(edge: &AwpEdge, host: Arc<dyn SiteHost>, name: &str) -> axum::Router {
465    use axum::http::{HeaderValue, StatusCode, Uri, header};
466    use axum::response::{IntoResponse, Response};
467
468    async fn content(host: &dyn SiteHost, name: &str, path: &str) -> Response {
469        let path = if path.ends_with('/') { format!("{path}index.html") } else { path.to_string() };
470        let (kind, body) = match host.fetch(&path).await {
471            Ok(Some(bytes)) => (adk_site::release::content_type(&path), bytes.to_vec()),
472            Ok(None) if path == "/index.html" => {
473                ("text/html; charset=utf-8", crate::onboarding::holding_page(name).into_bytes())
474            }
475            Ok(None) => return StatusCode::NOT_FOUND.into_response(),
476            Err(error) => {
477                tracing::error!(error = %error, path, "the host could not serve a file");
478                return StatusCode::SERVICE_UNAVAILABLE.into_response();
479            }
480        };
481        let mut response = (StatusCode::OK, body).into_response();
482        let headers = response.headers_mut();
483        headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(kind));
484        headers.insert(
485            header::STRICT_TRANSPORT_SECURITY,
486            HeaderValue::from_static("max-age=31536000"),
487        );
488        if kind.starts_with("text/html") {
489            headers.insert(
490                header::CONTENT_SECURITY_POLICY,
491                HeaderValue::from_static("default-src 'self'; script-src 'self'"),
492            );
493        }
494        response
495    }
496
497    let name = name.to_string();
498    edge.router().fallback(move |uri: Uri| {
499        let (host, name) = (host.clone(), name.clone());
500        async move { content(host.as_ref(), &name, uri.path()).await }
501    })
502}
503
504/// The site's status on the edge (spec 3.5 §7.5, §7.20, A-I11): an incident or a read-only
505/// state puts the edge in read-only mode with the reason, so every non-read capability
506/// answers `503 read_only` with the signed status; `operational` resumes it.
507pub struct EdgeStatus {
508    control: EdgeStatusControl,
509    board: InMemoryStatusBoard,
510}
511
512impl EdgeStatus {
513    /// The status over `control`, the edge's.
514    pub fn new(control: EdgeStatusControl) -> Self {
515        Self { control, board: InMemoryStatusBoard::new() }
516    }
517}
518
519#[async_trait]
520impl StatusSink for EdgeStatus {
521    async fn set(&self, site: uuid::Uuid, status: StatusRecord) -> Result<()> {
522        let switched = match status.state {
523            SiteState::Operational => self.control.resume().await,
524            _ => self.control.read_only(&status.reason).await,
525        };
526        if let Err(error) = switched {
527            tracing::warn!(error = %error, "the edge's status was not signed; its mode changed");
528        }
529        self.board.set(site, status).await
530    }
531
532    async fn get(&self, site: uuid::Uuid) -> Result<Option<StatusRecord>> {
533        self.board.get(site).await
534    }
535}
536
537/// `edge_read_only`: switches the edge to read-only for a reason, or back (spec 3.5 A-I11).
538/// It implements `adk-harness`' catalogue entry, under the back office's origin, so the
539/// catalogue classes it as a reversible incident act an owner may pre-authorise.
540struct EdgeReadOnlyTool {
541    control: EdgeStatusControl,
542}
543
544#[async_trait]
545impl Tool for EdgeReadOnlyTool {
546    fn name(&self) -> &str {
547        adk_harness::website::EDGE_READ_ONLY
548    }
549
550    fn origin(&self) -> &str {
551        adk_harness::website::BACK_OFFICE_ORIGIN
552    }
553
554    fn description(&self) -> &str {
555        "Switches the agent edge to read-only for a reason, such as drift_detected, or back to \
556         serving with resume: true. Read-only capabilities and static pages keep working."
557    }
558
559    fn parameters_schema(&self) -> Option<Value> {
560        Some(json!({
561            "type": "object",
562            "properties": {
563                "reason": { "type": "string", "pattern": "^[a-z][a-z0-9_]{0,63}$" },
564                "resume": { "type": "boolean" }
565            },
566            "additionalProperties": false
567        }))
568    }
569
570    fn effect(&self) -> ToolEffect {
571        ToolEffect::Idempotent
572    }
573
574    async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
575        let resume = args["resume"].as_bool().unwrap_or(false);
576        let result = if resume {
577            self.control.resume().await
578        } else {
579            self.control.read_only(args["reason"].as_str().unwrap_or("incident")).await
580        };
581        let status = result.map_err(|error| AdkError::tool(error.to_string()))?;
582        Ok(json!({ "readOnly": self.control.is_read_only(), "status": status }))
583    }
584}
585
586/// The stream lane's feed (spec 3.5 §7.8.3 "Stream"): `GET /awp/v2/stream?item={id}&after={n}`
587/// answers the entries after `n`, each signed by the edge's receipt key.
588pub fn stream_router(engine: Arc<adk_site::updates::UpdateEngine>) -> axum::Router {
589    use axum::extract::{Query, State};
590    use axum::http::StatusCode;
591    use axum::response::IntoResponse;
592
593    #[derive(serde::Deserialize)]
594    struct Params {
595        item: String,
596        #[serde(default)]
597        after: u64,
598    }
599
600    async fn feed(
601        State(engine): State<Arc<adk_site::updates::UpdateEngine>>,
602        Query(params): Query<Params>,
603    ) -> axum::response::Response {
604        match engine.stream_since(&awp_types::ContentId(params.item), params.after).await {
605            Ok(entries) => axum::Json(json!({ "entries": entries })).into_response(),
606            Err(error) => {
607                (StatusCode::NOT_FOUND, axum::Json(json!({ "error": error.to_string() })))
608                    .into_response()
609            }
610        }
611    }
612
613    axum::Router::new().route("/awp/v2/stream", axum::routing::get(feed)).with_state(engine)
614}