Skip to main content

adk_website/deploy/
back_office.rs

1//! The back office the served kernel runs (spec 3.5 §7.19, §7.20, §7.11, §7.22, A-I13).
2//!
3//! With a model, [`serve`](fn@super::serve) builds the site's back-office agents — each a
4//! `HarnessAgent` in the back-office partition with its jobs' tools — and hosts them on the
5//! kernel: the Steward's target runs the whole back office as one team, delegating to the
6//! others; every other agent also runs alone for its jobs' processes (`site.content`,
7//! `site.reviews`, `site.outreach`, `site.support`).
8//!
9//! | Each agent gets | From |
10//! |---|---|
11//! | The ladder's mode and budget for its jobs | The kernel's autonomy store, read at every call |
12//! | The owner's standing rules | `data/kernel.db`, where `adk-rust website jobs promote` grants them, so a promotion takes effect while the site serves |
13//! | Held calls | The owner's approval inbox, the kernel's approval service |
14//! | The publish delay | [`PublishDelay`](crate::publish_delay::PublishDelay) on the content-gap jobs |
15//! | Revenue: nurture sends, the lead handoff | The site's email outbox through [`nurture_tools`](crate::leads::nurture_tools), [`handoff_tool_for`](crate::alarms::handoff_tool_for) |
16//! | Growth: experiments | [`experiment_tools`](crate::experiments::experiment_tools) |
17//! | Guardian: the edge's read-only switch | [`SiteEdge::read_only_tool`](crate::edge::SiteEdge::read_only_tool) |
18//! | Finance: `wallet_pay`, `wallet_status` | The owner's wallet, [`SiteOptions::wallet`](super::SiteOptions::wallet) |
19
20use std::sync::Arc;
21
22use adk_core::{Llm, Result, Tool};
23use adk_drivers::Side;
24use adk_drivers::email::email_tools;
25use adk_harness::InstructionsConfig;
26use adk_harness::website::{BackOfficeKit, LadderCompiler, PublicKit, SiteSearch};
27use adk_kernel::{KernelBuilder, PartitionId};
28
29use super::kernel::SiteStores;
30use super::site::RunningSite;
31use crate::team::{AgentRole, BuiltTeam, SiteTeam, TeamKit};
32
33impl RunningSite {
34    /// The ladder compiler of the site's jobs: under the charter in force when there is one,
35    /// with the email tools' origins pinned for standing rules.
36    async fn compiler(&self, stores: &SiteStores) -> Result<LadderCompiler> {
37        let team = SiteTeam::new(self.site.clone(), &self.template);
38        let bindings = crate::jobs::bindings(&team, &self.template.jobs());
39        let current = stores
40            .kernel
41            .charter
42            .charters
43            .current(self.site.id)
44            .await
45            .map_err(|e| adk_core::AdkError::config(e.to_string()))?;
46        let mut compiler = match current {
47            Some(current) => {
48                LadderCompiler::new(self.site.clone()).with_charter(&current.charter, bindings)
49            }
50            None => bindings
51                .into_iter()
52                .fold(LadderCompiler::new(self.site.clone()), LadderCompiler::job),
53        };
54        if let Some(outbox) = &self.outbox {
55            compiler = compiler.with_tool_origins(&email_tools(outbox.clone(), Side::BackOffice));
56        }
57        Ok(compiler)
58    }
59
60    /// The site's back office over `model` (spec 3.5 §7.19): every back-office agent the
61    /// kind runs, each with its jobs' tools, the owner's standing rules, the owner's approval
62    /// inbox for held calls and the publish delay, compiled as one team led by the Steward.
63    ///
64    /// # Errors
65    ///
66    /// A store's error, or a team that does not build.
67    pub async fn back_office(&self, stores: &SiteStores, model: Arc<dyn Llm>) -> Result<BuiltTeam> {
68        let compiler = self.compiler(stores).await?;
69        let mut kit = BackOfficeKit::new(
70            self.partitions.clone(),
71            stores.partitions.clone(),
72            self.runtime.clone(),
73            compiler.clone(),
74            stores.kernel.charter.autonomy.clone(),
75        );
76        // The KPI tracker's guardrails pause jobs through the same pauses (A-I15).
77        kit.pauses = self.pauses.clone();
78        let public = {
79            let partitions = self.partitions.clone();
80            let table = stores.partitions.clone();
81            let signals = partitions
82                .signal_sink(stores.kernel.charter.signals.clone(), stores.kernel.agenda.clone());
83            move || PublicKit {
84                partitions: partitions.clone(),
85                table: table.clone(),
86                search: Arc::new(SiteSearch::new()),
87                signals: signals.clone(),
88                reply: None,
89                capabilities: Vec::new(),
90            }
91        };
92        let revenue: Vec<Arc<dyn Tool>> = {
93            let mut tools =
94                vec![crate::alarms::handoff_tool_for(self.alarms.clone(), self.leads.clone())];
95            if let Some(outbox) = &self.outbox {
96                tools.extend(crate::leads::nurture_tools(
97                    email_tools(outbox.clone(), Side::BackOffice),
98                    self.leads.clone(),
99                    crate::alarms::quiet_hours(&self.reporting),
100                    Arc::new(adk_core::SystemClock),
101                ));
102            }
103            tools
104        };
105        let growth = crate::experiments::experiment_tools(self.experiments.clone());
106        let guardian = vec![self.edge.read_only_tool()];
107        let delay = crate::publish_delay::PublishDelay::new(self.publish_delay, compiler)
108            .with_charters(stores.kernel.charter.charters.clone());
109        let delay: Arc<dyn adk_core::ToolPolicy> = Arc::new(delay);
110        let approvals = stores.approvals.clone();
111        let configure = move |role: AgentRole, builder: adk_harness::HarnessAgentBuilder| {
112            let extra: &[Arc<dyn Tool>] = match role {
113                AgentRole::Revenue => &revenue,
114                AgentRole::Growth => &growth,
115                AgentRole::Guardian => &guardian,
116                _ => &[],
117            };
118            extra
119                .iter()
120                .cloned()
121                .fold(builder, adk_harness::HarnessAgentBuilder::tool)
122                // A served site reads no instruction file from the host's home directory.
123                .project_instructions(InstructionsConfig {
124                    user_file: None,
125                    require_trust: false,
126                    ..InstructionsConfig::default()
127                })
128                .approval_service(approvals.clone())
129                .add_operator_policy(delay.clone())
130        };
131        // The packs' playbooks join each agent's own (spec 3.5 §7.23).
132        self.packs.install_playbooks(&self.paths.data().join("agents")).await?;
133        let kit = TeamKit {
134            model,
135            root: self.paths.data().join("agents"),
136            back_office: kit,
137            public: Arc::new(public),
138            standing_rules: stores.rules.clone(),
139            configure: Arc::new(configure),
140            // The Finance agent pays running costs from the owner's wallet (spec 3.5 §7.14).
141            wallet: self.wallet.clone(),
142        };
143        SiteTeam::new(self.site.clone(), &self.template).build(&kit).await
144    }
145}
146
147/// Hosts `team` on `kernel` in the back-office `partition` of app `app` (spec 3.5 §7.19,
148/// §7.20): the Steward's target runs the whole team; every other back-office agent runs alone
149/// for its jobs' processes. Returns the agents hosted.
150///
151/// # Errors
152///
153/// A runner that refuses its configuration.
154pub fn host(
155    mut kernel: KernelBuilder,
156    team: &BuiltTeam,
157    partition: &PartitionId,
158    app: &str,
159    sessions: Arc<dyn adk_session::SessionService>,
160) -> Result<(KernelBuilder, Vec<AgentRole>)> {
161    let mut hosted = Vec::new();
162    for role in team.roles() {
163        if role.partition() != adk_harness::website::WebsitePartition::BackOffice {
164            continue;
165        }
166        let runner = match role {
167            AgentRole::Steward => team.team_runner(app, sessions.clone())?,
168            _ => team.agent_runner(role, app, sessions.clone())?,
169        };
170        kernel = kernel.partition_agent(partition.clone(), role.as_str(), Arc::new(runner));
171        hosted.push(role);
172    }
173    Ok((kernel, hosted))
174}