1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum Shape {
68 Local,
70 Container,
72 Managed,
74 Agency,
76}
77
78impl Shape {
79 pub const ALL: [Shape; 4] = [Shape::Local, Shape::Container, Shape::Managed, Shape::Agency];
81
82 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct DeploymentPlan {
149 pub shape: Shape,
151 pub files: BTreeMap<String, String>,
153 pub commands: Vec<String>,
155 pub estimate: RunningCostEstimate,
157}
158
159fn 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#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct ProjectRef {
191 pub name: String,
193 pub domain: String,
195 pub sites: Vec<String>,
197}
198
199pub 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
283pub 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}