Skip to main content

adk_website/deploy/
mod.rs

1//! Deployment shapes (spec 3.5 §7.22, §7.17).
2//!
3//! | Shape | Content | Edge and kernel | Fits |
4//! |---|---|---|---|
5//! | [`Shape::Local`] | `DirectoryHost`, or any host driver | `adk-rust up --install` on the owner's machine | Trials, developers |
6//! | [`Shape::Container`] | Any static host | One container: one process serving the edge and the kernel on two listeners | Most small sites |
7//! | [`Shape::Managed`] | Any static host | The managed agent runtime or another agent platform through `adk-deploy` | Owners who want no servers |
8//! | [`Shape::Agency`] | Per-site hosts | One harness for many sites, each isolated (A-I22) | Developers running sites for clients |
9//!
10//! [`plan`] writes what a shape needs into the site project and estimates its monthly
11//! running cost before deployment; [`serve`](fn@serve) is what the `adk-website` binary runs: the
12//! kernel's control plane and the agent edge for one site, or many in [`agency`] mode.
13//!
14//! | Module | Contents |
15//! |---|---|
16//! | [`project`] | The project layout `adk-rust site` uses, delegated key files, released documents, the owner's feeds, slots and payment links |
17//! | [`config`] | The site's email, upkeep sources, wallet and Guardian's probe from the project's configuration files |
18//! | [`kernel`] | The kernel's durable SQLite stores in `data/kernel.db` |
19//! | [`site`] | [`RunningSite`]: one site's runtime, edge, updates, experiments, measurement, review, alarms, leads and upkeep |
20//! | [`back_office`] | The back-office agents the served kernel hosts, led by the Steward as one team |
21//! | [`updates`] | The update engine's driver, journal, decision cards and alarms |
22//! | [`checks`] | The release-delegation gate check, payment links, the log recorder |
23//! | [`serve`](mod@serve) | The kernel and the edge's listener for one site or an agency |
24
25pub mod agency;
26pub mod back_office;
27pub mod chat;
28pub mod checks;
29pub mod config;
30pub mod kernel;
31pub mod project;
32pub mod serve;
33pub mod site;
34pub mod updates;
35
36use std::collections::BTreeMap;
37use std::fmt;
38use std::path::Path;
39use std::str::FromStr;
40
41use adk_core::{AdkError, Result};
42use adk_deploy::{AgentConfig, DeploymentManifest};
43use serde::{Deserialize, Serialize};
44
45use crate::onboarding::cost::{CostInputs, RunningCostEstimate, estimate};
46use crate::team::SiteTeam;
47
48pub use agency::{Agency, AgencyRouter};
49pub use kernel::SiteStores;
50pub use project::ProjectPaths;
51pub use serve::{AgencyFile, AgencySite, ServeOptions, Served, serve, serve_agency};
52pub use site::{EmailOptions, ProbeOptions, RunningSite, ServedWorkflows, SiteOptions};
53pub use updates::{UpdateCards, UpdateDriver, UpdateJournal};
54
55/// A deployment shape (spec 3.5 §7.22).
56///
57/// # Example
58///
59/// ```rust
60/// use adk_website::deploy::Shape;
61///
62/// assert_eq!("container".parse::<Shape>().unwrap(), Shape::Container);
63/// assert!(Shape::Agency.fits().contains("clients"));
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum Shape {
68    /// On the owner's machine.
69    Local,
70    /// One server or container.
71    Container,
72    /// A managed agent runtime.
73    Managed,
74    /// Many sites in one harness.
75    Agency,
76}
77
78impl Shape {
79    /// Every shape.
80    pub const ALL: [Shape; 4] = [Shape::Local, Shape::Container, Shape::Managed, Shape::Agency];
81
82    /// The shape's name.
83    pub fn as_str(self) -> &'static str {
84        match self {
85            Self::Local => "local",
86            Self::Container => "container",
87            Self::Managed => "managed",
88            Self::Agency => "agency",
89        }
90    }
91
92    /// Where the content is served from.
93    pub fn content(self) -> &'static str {
94        match self {
95            Self::Local => "DirectoryHost, or any host driver",
96            Self::Container | Self::Managed => "Any static host",
97            Self::Agency => "Per-site hosts",
98        }
99    }
100
101    /// Where the edge and the kernel run.
102    pub fn runtime(self) -> &'static str {
103        match self {
104            Self::Local => "adk-rust up --install on the owner's machine",
105            Self::Container => {
106                "One container: one process serving the edge and the kernel on two listeners"
107            }
108            Self::Managed => {
109                "The managed agent runtime or another agent platform through adk-deploy"
110            }
111            Self::Agency => "One harness for many sites",
112        }
113    }
114
115    /// Whom it fits.
116    pub fn fits(self) -> &'static str {
117        match self {
118            Self::Local => "Trials, developers",
119            Self::Container => "Most small sites: personal, business, nonprofit, community",
120            Self::Managed => "Owners who want no servers",
121            Self::Agency => "Developers running sites for clients",
122        }
123    }
124}
125
126impl fmt::Display for Shape {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.write_str(self.as_str())
129    }
130}
131
132impl FromStr for Shape {
133    type Err = AdkError;
134
135    fn from_str(text: &str) -> Result<Self> {
136        Self::ALL.into_iter().find(|shape| shape.as_str() == text.trim()).ok_or_else(|| {
137            AdkError::config(format!(
138                "unknown shape `{text}`; use local, container, managed or agency"
139            ))
140        })
141    }
142}
143
144/// A site's deployment in one shape: the files to write into the project, the commands that
145/// start it, and its monthly running cost (spec 3.5 §7.22).
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct DeploymentPlan {
149    /// The shape.
150    pub shape: Shape,
151    /// Files by path relative to the project.
152    pub files: BTreeMap<String, String>,
153    /// What starts it, in order.
154    pub commands: Vec<String>,
155    /// The monthly running cost before deployment.
156    pub estimate: RunningCostEstimate,
157}
158
159/// The container's image: `adk-website` from crates.io, and the project, keys excluded.
160fn dockerfile() -> String {
161    let version = env!("CARGO_PKG_VERSION");
162    format!(
163        r#"# The site's edge and kernel in one container (spec 3.5 §7.22): one process serving the
164# agent edge publicly and the kernel's control plane on loopback, each on its own listener.
165# The content can be served by any static host as well.
166FROM rust:1.95-slim AS build
167RUN apt-get update && apt-get install -y --no-install-recommends build-essential cmake pkg-config && rm -rf /var/lib/apt/lists/*
168RUN cargo install adk-website --version {version} --locked
169
170FROM debian:bookworm-slim
171RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
172COPY --from=build /usr/local/cargo/bin/adk-website /usr/local/bin/adk-website
173COPY . /site/
174# Keys, stores and releases live on the volume, never in the image.
175VOLUME ["/site/data", "/site/host"]
176EXPOSE 8080
177CMD ["adk-website", "start", "/site", "--edge", "0.0.0.0:8080", "--kernel", "127.0.0.1:7340"]
178"#
179    )
180}
181
182fn build_script(image: &str) -> String {
183    format!(
184        "#!/bin/sh\n# Builds the site's image from this project.\nset -eu\ndocker build -t {image} .\n"
185    )
186}
187
188/// What a plan needs to know about the project.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct ProjectRef {
191    /// The site's name.
192    pub name: String,
193    /// Its domain.
194    pub domain: String,
195    /// The sites an agency runs, by domain; the project's own for the other shapes.
196    pub sites: Vec<String>,
197}
198
199/// The deployment of `project` in `shape`, with the running cost of `team` under `costs`
200/// (spec 3.5 §7.22).
201///
202/// # Errors
203///
204/// An invalid managed-runtime manifest.
205///
206/// # Example
207///
208/// ```rust
209/// use adk_harness::website::SiteRef;
210/// use adk_website::deploy::{ProjectRef, Shape, plan};
211/// use adk_website::kinds::template;
212/// use adk_website::onboarding::cost::{CostInputs, ModelPrice};
213/// use adk_website::team::SiteTeam;
214/// use awp_types::SiteKind;
215///
216/// let team = SiteTeam::new(SiteRef::new(uuid::Uuid::nil(), "notes", "https://notes.example"), &template(SiteKind::Personal));
217/// let project = ProjectRef { name: "Notes".into(), domain: "notes.example".into(), sites: vec![] };
218/// let costs = CostInputs::small(500, 1_200, ModelPrice { input_per_mtok: 30, output_per_mtok: 250 });
219/// let container = plan(Shape::Container, &project, &team, &costs).unwrap();
220/// assert!(container.files.contains_key("Dockerfile"));
221/// assert!(container.estimate.total > 0);
222/// ```
223pub fn plan(
224    shape: Shape,
225    project: &ProjectRef,
226    team: &SiteTeam,
227    costs: &CostInputs,
228) -> Result<DeploymentPlan> {
229    let image = project.domain.replace('.', "-");
230    let mut files = BTreeMap::new();
231    let commands = match shape {
232        Shape::Local => vec!["adk-rust up --install".into(), "adk-website start .".into()],
233        Shape::Container => {
234            files.insert("Dockerfile".into(), dockerfile());
235            files.insert(".dockerignore".into(), "data\nhost\n".into());
236            files.insert("scripts/build-image.sh".into(), build_script(&image));
237            vec![
238                "sh scripts/build-image.sh".into(),
239                format!(
240                    "docker run -p 8080:8080 -v \"$PWD/data:/site/data\" -v \"$PWD/host:/site/host\" {image}"
241                ),
242            ]
243        }
244        Shape::Managed => {
245            let mut manifest = DeploymentManifest {
246                agent: AgentConfig::new(image.clone(), "adk-website"),
247                ..DeploymentManifest::default()
248            };
249            manifest.agent.description = Some(format!("The AWP website {}", project.name));
250            manifest.build.assets = [
251                "site.toml",
252                "theme",
253                "content",
254                "capabilities.json",
255                "public-terms.json",
256                "charter.draft.json",
257                "packs",
258            ]
259            .into_iter()
260            .map(str::to_string)
261            .collect();
262            let toml = manifest.to_toml_string().map_err(|e| AdkError::config(e.to_string()))?;
263            files.insert("adk-deploy.toml".into(), toml);
264            vec!["Bundle and push with adk-deploy's BundleBuilder and DeployClient".into()]
265        }
266        Shape::Agency => {
267            let sites = if project.sites.is_empty() {
268                vec![project.domain.clone()]
269            } else {
270                project.sites.clone()
271            };
272            let listed: String = sites
273                .iter()
274                .map(|site| format!("[[site]]\ndomain = \"{site}\"\ndir = \"sites/{site}\"\n\n"))
275                .collect();
276            files.insert("agency.toml".into(), listed);
277            vec!["adk-website agency agency.toml".into()]
278        }
279    };
280    Ok(DeploymentPlan { shape, files, commands, estimate: estimate(team, costs) })
281}
282
283/// Writes `plan`'s files into the project at `dir`, leaving existing files as they are;
284/// returns the files written.
285///
286/// # Errors
287///
288/// The file system's error.
289pub async fn write_plan(plan: &DeploymentPlan, dir: &Path) -> Result<Vec<String>> {
290    let mut written = Vec::new();
291    for (path, contents) in &plan.files {
292        let target = dir.join(path);
293        if tokio::fs::try_exists(&target).await.unwrap_or(false) {
294            continue;
295        }
296        if let Some(parent) = target.parent() {
297            tokio::fs::create_dir_all(parent).await.map_err(|e| {
298                AdkError::config(format!("cannot create {}: {e}", parent.display()))
299            })?;
300        }
301        tokio::fs::write(&target, contents)
302            .await
303            .map_err(|e| AdkError::config(format!("cannot write {}: {e}", target.display())))?;
304        written.push(path.clone());
305    }
306    Ok(written)
307}