Skip to main content

adk_website/deploy/
serve.rs

1//! Serving sites: the kernel's control plane and the agent edge (spec 3.5 §7.17, §7.22,
2//! A-I20, A-I22): what `adk-website start`, `adk-website agency` and the container run.
3//!
4//! | Listener | Serves |
5//! |---|---|
6//! | Kernel (loopback by default) | The control plane, with device pairing: the setup code is claimed at `POST /api/kernel/pairing/claim` |
7//! | Edge | The agent edge's routes, the stream feed and the content: the signed release on the site's `DirectoryHost`, or the holding page until the launch; in agency mode, each site's by its host (A-I22) |
8//!
9//! Each site is a [`RunningSite`] over its project ([`ProjectPaths`]); the kernel's stores are
10//! durable in `data/kernel.db` ([`SiteStores`]). The setup code is issued while no device
11//! is paired, so a restarted site does not offer a second one.
12//!
13//! The kernel runs each site's processes (spec 3.5 §7.20): the Guardian's probe when the site
14//! has a domain claim ([`ProbeOptions`](super::ProbeOptions)), the weekly digest when the owner
15//! has a channel, the hosting job's upkeep check when the site has an advisory or certificate
16//! source, and — with a model — the back office ([`super::back_office`]): the Steward leading
17//! the team, and each agent's jobs on their signals and schedules, under the owner's
18//! standing rules in `data/kernel.db`. Agent sessions are kept in `data/kernel/sessions.db`.
19//! Each site's jobs are bound through a `CharterKit`, which also runs the KPI tracker as the
20//! kernel's `kernel.kpi` process, hourly. A job whose process is not scheduled is a warning in
21//! the kernel's inventory, logged at start and at `GET /api/kernel/inventory`, with the
22//! reason: no channel, no probe options or domain claim, no advisory or certificate source,
23//! or no model.
24//!
25//! Every store of the kernel is in `data/kernel.db` beside the runs ([`SiteStores`]) — the
26//! process table, schedules, spend ledger, the kill switch and the control plane's settings
27//! among them — and the kernel refuses to start with one in memory
28//! (`KernelBuilder::require_durable`). It records into the site's audit trail,
29//! `data/audit.jsonl`; an agency's kernel records into the agency's own `data/audit.jsonl`.
30
31use std::net::SocketAddr;
32use std::path::{Path, PathBuf};
33use std::sync::Arc;
34use std::time::Duration;
35
36use adk_core::audit_log::AuditTrail;
37use adk_core::{AdkError, Result};
38use adk_kernel::control::ControlPlaneConfig;
39use adk_kernel::pairing::{IssuedCode, Pairing};
40use adk_kernel::{Kernel, KernelConfig};
41use serde::Deserialize;
42use tokio::task::JoinHandle;
43
44use super::agency::{Agency, AgencyRouter};
45use super::kernel::SiteStores;
46use super::project::ProjectPaths;
47use super::site::{RunningSite, ServedWorkflows, SiteOptions};
48use crate::onboarding::SetupGate;
49use crate::team::SiteTeam;
50use crate::workflows::SiteWorkflows;
51
52fn config(error: impl std::fmt::Display) -> AdkError {
53    AdkError::config(error.to_string())
54}
55
56/// How to serve a site.
57#[derive(Debug, Clone)]
58pub struct ServeOptions {
59    /// The site project.
60    pub dir: PathBuf,
61    /// Where the edge listens.
62    pub edge: SocketAddr,
63    /// Where the kernel's control plane listens; loopback unless a token or SSO guards it.
64    pub kernel: SocketAddr,
65    /// The owner, the edge's URL, the channels, drivers and schedules.
66    pub site: SiteOptions,
67}
68
69impl ServeOptions {
70    /// The site at `dir` for `owner`, the edge on `127.0.0.1:8080` and the kernel on
71    /// `127.0.0.1:7340`.
72    ///
73    /// # Example
74    ///
75    /// ```rust
76    /// use adk_website::deploy::ServeOptions;
77    ///
78    /// let options = ServeOptions::new("bakery", "amina");
79    /// assert_eq!(options.edge.port(), 8080);
80    /// assert_eq!(options.site.owner, "amina");
81    /// ```
82    pub fn new(dir: impl Into<PathBuf>, owner: impl Into<String>) -> Self {
83        Self {
84            dir: dir.into(),
85            edge: SocketAddr::from(([127, 0, 0, 1], 8080)),
86            kernel: SocketAddr::from(([127, 0, 0, 1], 7340)),
87            site: SiteOptions { owner: owner.into(), ..SiteOptions::default() },
88        }
89    }
90}
91
92/// Served sites; dropping it stops the edge's listener and the sites' background work.
93pub struct Served {
94    /// Where the edge listens.
95    pub edge_addr: SocketAddr,
96    /// Where the kernel's control plane listens.
97    pub kernel_addr: SocketAddr,
98    /// The setup code, also in the logs, while no device is paired (A-I20).
99    pub setup_code: Option<IssuedCode>,
100    /// The sites served.
101    pub sites: Vec<RunningSite>,
102    /// The kernel's durable stores.
103    pub stores: SiteStores,
104    kernel: Kernel,
105    edge_task: JoinHandle<()>,
106    chat: Option<adk_kernel::channels::ChannelGateway>,
107}
108
109impl std::fmt::Debug for Served {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.debug_struct("Served")
112            .field("edge_addr", &self.edge_addr)
113            .field("kernel_addr", &self.kernel_addr)
114            .field("sites", &self.sites)
115            .finish_non_exhaustive()
116    }
117}
118
119impl Served {
120    /// The kernel serving the sites.
121    pub fn kernel(&self) -> &Kernel {
122        &self.kernel
123    }
124
125    /// The site's chat gateway, when [`SiteOptions::chat`](super::SiteOptions::chat) is set
126    /// (spec 3.5 §10 X12): every chat platform's messages pass through it.
127    pub fn chat(&self) -> Option<&adk_kernel::channels::ChannelGateway> {
128        self.chat.as_ref()
129    }
130
131    /// Stops the edge, the sites' background work and the kernel with its control plane.
132    ///
133    /// # Errors
134    ///
135    /// The kernel's error on shutdown.
136    pub async fn shutdown(mut self) -> Result<()> {
137        self.edge_task.abort();
138        if let Some(chat) = &self.chat {
139            chat.stop();
140        }
141        drop(std::mem::take(&mut self.sites));
142        self.kernel.stop().await.map_err(config)
143    }
144}
145
146impl Drop for Served {
147    fn drop(&mut self) {
148        self.edge_task.abort();
149    }
150}
151
152/// Starts the kernel over `stores` with `sites`' workflows and triggers and device pairing on
153/// its control plane, recording into `audit`, then the edge's listener serving `app`.
154// `serve` and `serve_agency` differ in every argument; a struct for one private call adds
155// nothing.
156#[allow(clippy::too_many_arguments)]
157async fn start(
158    name: &str,
159    home: PathBuf,
160    stores: SiteStores,
161    audit: AuditTrail,
162    mut sites: Vec<RunningSite>,
163    options: &ServeOptions,
164    app: axum::Router,
165    doorbell: Option<Arc<adk_kernel::channels::ChannelDoorbell>>,
166) -> Result<Served> {
167    let pairing = Pairing::new(stores.kernel.devices.clone());
168    // `adk-rust pair accept` pairs a chat account that asked with `/pair` (spec 3.5 §10 X12).
169    let pairing = match &options.site.channel_bindings {
170        Some(bindings) => pairing.with_channel_bindings(bindings.clone()),
171        None => pairing,
172    };
173    let paired = !pairing.devices().await.map_err(config)?.is_empty();
174    let setup_code = if paired {
175        None
176    } else {
177        Some(SetupGate::new(pairing.clone(), options.site.owner.clone()).issue().await?)
178    };
179    let control = ControlPlaneConfig::default()
180        .without_socket()
181        .with_http(options.kernel)
182        .with_pairing(pairing);
183    let mut site_workflows = SiteWorkflows::new();
184    let mut triggers = Vec::new();
185    let sessions: Option<Arc<dyn adk_session::SessionService>> = match &options.site.model {
186        Some(_) => {
187            std::fs::create_dir_all(&home).map_err(config)?;
188            let url = format!("sqlite://{}?mode=rwc", home.join("sessions.db").display());
189            let sessions = adk_session::SqliteSessionService::new(&url).await?;
190            sessions.migrate().await?;
191            Some(Arc::new(sessions))
192        }
193        None => None,
194    };
195    let mut kernel_config = KernelConfig::default()
196        .with_app_name(name)
197        .with_home(home.clone())
198        .with_control(control)
199        .with_governance(stores.governance.clone());
200    // The site's proactive runs wait out the owner's quiet hours (spec 3.5 §7.21, §5 S10); an
201    // agency's sites may keep different hours, and the kernel holds one set.
202    if let [site] = sites.as_slice()
203        && let Some(quiet) = crate::alarms::quiet_hours(&site.reporting)
204    {
205        kernel_config = kernel_config.with_quiet_hours(quiet);
206    }
207    // Every stateful store is durable in `data/kernel.db`: the process table, which the wake
208    // router finds sleepers through, so a restart keeps every wake set, admission deferral
209    // and daily total; the kill switch, mirrored; the control plane's settings. A store
210    // that would be kept in memory refuses the start.
211    let mut builder = Kernel::builder()
212        .config(kernel_config)
213        .stores(&stores.kernel)
214        .require_durable()
215        .audit(audit)
216        .approval_service(stores.approvals.clone())
217        .partitions(stores.partitions.clone());
218    for site in &sites {
219        use adk_kernel::charter::{CharterKit, SiteProcessKind};
220        triggers.extend(site.triggers().iter().cloned());
221        let team = SiteTeam::new(site.site.clone(), &site.template);
222        let partition = site.partitions.back_office().id.clone();
223        // The runs of a site's processes are its own app's, so its agents act as
224        // `urn:adk:agent:{site}/{agent}`, an agency's sites included.
225        let app = site.site.name.as_str();
226        let mut runs: Vec<SiteProcessKind> = Vec::new();
227        // The kinds this site does not run, each with its reason, for the startup log.
228        let mut skipped: Vec<(SiteProcessKind, &str)> = Vec::new();
229        if let Some(target) = site.digest_target(&options.site) {
230            site_workflows = site_workflows.digest(site.site.id, target);
231            runs.push(SiteProcessKind::Digest);
232        } else {
233            skipped.push((SiteProcessKind::Digest, "the owner has no channel"));
234        }
235        // The Guardian's probe every five minutes, when the site has a domain claim (spec
236        // 3.5 §7.20, A-I9).
237        if let Some(probe) = &site.guardian {
238            site_workflows = site_workflows.probe(site.site.id, probe.clone());
239            runs.push(SiteProcessKind::Probe);
240        } else {
241            skipped.push((SiteProcessKind::Probe, "no probe options or no domain claim"));
242        }
243        // A push to the content repository is a run of the site's own (spec 3.5 §7.8.2).
244        if let Some(entry) = &site.repository {
245            site_workflows = site_workflows.repository(site.site.id, entry.clone());
246        }
247        // The weekly playbook learning, decided by the owner (spec 3.5 §7.15).
248        site_workflows = site_workflows.learning(site.site.id, site.learning.clone());
249        if let Some(check) = site.upkeep(&stores, &options.site) {
250            site_workflows = site_workflows.watch(site.site.id, check);
251            runs.push(SiteProcessKind::Watch);
252        } else {
253            skipped.push((SiteProcessKind::Watch, "no advisory or certificate source"));
254        }
255        if let (Some(model), Some(sessions)) = (&options.site.model, &sessions) {
256            let team = site.back_office(&stores, model.clone()).await?;
257            let hosted;
258            (builder, hosted) =
259                super::back_office::host(builder, &team, &partition, app, sessions.clone())?;
260            tracing::info!(site = app, agents = ?hosted, "the back office is hosted");
261            runs.extend([
262                SiteProcessKind::Content,
263                SiteProcessKind::Reviews,
264                SiteProcessKind::Outreach,
265                SiteProcessKind::Support,
266            ]);
267        } else {
268            skipped.extend(
269                [
270                    SiteProcessKind::Content,
271                    SiteProcessKind::Reviews,
272                    SiteProcessKind::Outreach,
273                    SiteProcessKind::Support,
274                ]
275                .map(|kind| (kind, "the site has no model")),
276            );
277        }
278        // The charter kit binds each job's process to its target, runs the KPI tracker as
279        // the kernel's `kernel.kpi` process and files the edge's signals in the back office;
280        // a kind the site does not run is named in the kernel's inventory with the reason.
281        let mut kit = CharterKit::new(
282            site.site.id,
283            app,
284            partition.clone(),
285            stores.kernel.charter.signals.clone(),
286        )
287        .with_user(format!("site:{}", site.site.name))
288        .tracker(site.tracker().clone());
289        for process in crate::jobs::processes(&team, &site.template.jobs()) {
290            kit = match skipped.iter().find(|(kind, _)| *kind == process.kind) {
291                Some((_, reason)) => kit.skip(process.kind, *reason),
292                None if runs.contains(&process.kind) => {
293                    kit.job(process.kind, process.target, process.input)
294                }
295                None => kit,
296            };
297        }
298        builder = kit.install(builder);
299    }
300    // The kernel fires each standing trigger's cron expression through one watermarked
301    // source of its own, its cursor in the project's store.
302    for trigger in triggers {
303        builder = builder.trigger(trigger);
304    }
305    let workflows =
306        ServedWorkflows::new(site_workflows, sites.iter().map(|site| site.experiments.clone()));
307    let kernel = builder.workflow(Arc::new(workflows)).build().map_err(config)?;
308    // The edge's signals wake the back office's processes (spec 3.5 §7.10, §7.20), filed in
309    // each site's trail.
310    for site in &sites {
311        let partition = site.partitions.back_office().id.clone();
312        let sink = kernel.signal_sink(partition).map_err(config)?;
313        site.signals.attach(sink.with_audit(site.audit.clone()));
314    }
315    // A guardrail breached before the restart pauses its jobs again before the kernel takes
316    // their work (A-I15).
317    for site in &sites {
318        let paused = site.tracker().restore_pauses().await.map_err(config)?;
319        if !paused.is_empty() {
320            tracing::info!(site = %site.site.name, jobs = ?paused, "jobs paused by a breached guardrail");
321        }
322    }
323    kernel.start().await.map_err(config)?;
324    let kernel_addr = kernel
325        .control_addr()
326        .await
327        .ok_or_else(|| config("the kernel's control plane is not listening"))?;
328    let idle = options.site.idle.unwrap_or(Duration::from_secs(60));
329    for site in &mut sites {
330        site.start(idle);
331    }
332    // The site's chat: its gateway on the kernel, and the adapters' routes on the edge.
333    let (mut app, mut chat) = (app, None);
334    if let (Some(adapters), [site]) = (&options.site.chat, sites.as_slice()) {
335        let bindings: Arc<dyn adk_kernel::channels::ChannelBindingStore> =
336            match &options.site.channel_bindings {
337                Some(bindings) => bindings.clone(),
338                None => stores.kernel.channel_bindings.clone(),
339            };
340        let (gateway, routes) =
341            super::chat::start(adapters, &kernel, site, bindings, doorbell, sessions.clone())
342                .await?;
343        app = app.merge(routes);
344        chat = Some(gateway);
345    }
346    let listener = tokio::net::TcpListener::bind(options.edge).await.map_err(config)?;
347    let edge_addr = listener.local_addr().map_err(config)?;
348    // The peer address keys anonymous callers' rate limits and conversations (spec 3.5 §7.3).
349    let service = app.into_make_service_with_connect_info::<SocketAddr>();
350    let edge_task = tokio::spawn(async move {
351        if let Err(error) = axum::serve(listener, service).await {
352            tracing::error!(error = %error, "the edge stopped");
353        }
354    });
355    tracing::info!(edge = %edge_addr, kernel = %kernel_addr, sites = sites.len(), "serving");
356    Ok(Served { edge_addr, kernel_addr, setup_code, sites, stores, kernel, edge_task, chat })
357}
358
359/// Serves the site at `options.dir` (spec 3.5 §7.17, §7.22): issues the setup code into the
360/// logs while no device is paired, starts the kernel over its durable stores with device
361/// pairing on its control plane, and serves the edge with the release behind it.
362///
363/// # Errors
364///
365/// A project that does not load, a store that does not open, or a listener that does not
366/// bind.
367pub async fn serve(mut options: ServeOptions) -> Result<Served> {
368    let paths = ProjectPaths::new(&options.dir);
369    std::fs::create_dir_all(paths.data()).map_err(config)?;
370    // The site's chat gateway hears each decision the approval service takes (spec 3.5 §10
371    // X12).
372    let doorbell =
373        options.site.chat.is_some().then(|| Arc::new(adk_kernel::channels::ChannelDoorbell::new()));
374    let notifiers = doorbell.iter().map(|bell| bell.clone() as Arc<dyn adk_core::ApprovalNotifier>);
375    let stores =
376        SiteStores::open_with(&paths.database("kernel"), &options.site.owner, notifiers.collect())
377            .await?;
378    if options.site.chat.is_some() && options.site.channel_bindings.is_none() {
379        options.site.channel_bindings = Some(stores.kernel.channel_bindings.clone());
380    }
381    let site = RunningSite::open(paths.clone(), &stores, &options.site).await?;
382    site.partitions.install(&stores.partitions, adk_core::audit_log::AuditActor::default()).await?;
383    let app = site.router.clone();
384    let name = site.site.name.clone();
385    let audit = site.audit.clone();
386    start(&name, paths.data().join("kernel"), stores, audit, vec![site], &options, app, doorbell)
387        .await
388}
389
390/// An agency's file: the sites it runs, each a project directory relative to the file
391/// (spec 3.5 §7.22).
392#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
393pub struct AgencyFile {
394    /// The sites.
395    #[serde(rename = "site")]
396    pub sites: Vec<AgencySite>,
397}
398
399/// One site of an agency.
400#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
401pub struct AgencySite {
402    /// The domain it is served at.
403    pub domain: String,
404    /// Its project directory, relative to the agency file.
405    pub dir: PathBuf,
406}
407
408/// Serves every site `file` lists from one harness (spec 3.5 §7.22, A-I22): one kernel whose
409/// durable table holds each site's isolated partitions, and one edge listener that sends a
410/// request only to the site its host names. `options.dir` is ignored.
411///
412/// # Errors
413///
414/// An unreadable file, a duplicate site, or [`serve`]'s errors.
415pub async fn serve_agency(file: &Path, options: ServeOptions) -> Result<Served> {
416    let text = tokio::fs::read_to_string(file).await.map_err(config)?;
417    let listed: AgencyFile = toml::from_str(&text).map_err(config)?;
418    let root = file.parent().unwrap_or(Path::new("."));
419    let agency_paths = ProjectPaths::new(root);
420    std::fs::create_dir_all(agency_paths.data()).map_err(config)?;
421    let stores = SiteStores::open(&agency_paths.database("kernel"), &options.site.owner).await?;
422    // The agency's kernel serves every site, so it records into the agency's own trail.
423    let audit = AuditTrail::new(Arc::new(
424        adk_core::audit_log::FileAuditRecorder::open(agency_paths.data().join("audit.jsonl"))?
425            .with_log_id("agency"),
426    ));
427    let mut agency = Agency::new(stores.partitions.clone());
428    let (mut edges, mut sites) = (std::collections::BTreeMap::new(), Vec::new());
429    for listed in &listed.sites {
430        let paths = ProjectPaths::new(root.join(&listed.dir));
431        let site = RunningSite::open(paths, &stores, &options.site).await?;
432        agency.add(site.site.clone()).await?;
433        if site.domain != listed.domain {
434            tracing::warn!(listed = %listed.domain, project = %site.domain, "the agency file and the project name different domains");
435        }
436        edges.insert(listed.domain.to_ascii_lowercase(), site.router.clone());
437        sites.push(site);
438    }
439    let app = AgencyRouter::new(edges).router();
440    if options.site.chat.is_some() {
441        tracing::warn!(
442            "an agency's sites run no chat gateway: serve each site on its own for chat"
443        );
444    }
445    start("agency", agency_paths.data().join("kernel"), stores, audit, sites, &options, app, None)
446        .await
447}