use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use adk_agent::{
CompiledTeam, RelationshipKind, TeamMemberSpec, TeamPolicy, TeamRelationship, TeamSpec,
};
use adk_core::{AdkError, Agent, Llm, Result};
use adk_harness::website::{
AuthoringRoute, BackOfficeKit, PublicKit, SiteRef, WebsitePartition, job_levels,
};
use adk_harness::{HarnessAgent, HarnessAgentBuilder, StandingRuleStore};
use serde::{Deserialize, Serialize};
use crate::kinds::KindTemplate;
use crate::playbooks;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AgentRole {
Concierge,
AgentDesk,
Inbox,
Steward,
Growth,
Revenue,
Guardian,
Finance,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DefaultMode {
ManifestPolicy,
ManifestPolicyWithReply,
CharterAuthority,
ReversibleIncidentActs,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "on", rename_all = "snake_case")]
pub enum WakeSource {
Channel(&'static str),
Webhook(&'static str),
Signal(&'static str),
Cron(&'static str),
Event(&'static str),
}
impl AgentRole {
pub const ALL: [AgentRole; 8] = [
AgentRole::Concierge,
AgentRole::AgentDesk,
AgentRole::Inbox,
AgentRole::Steward,
AgentRole::Growth,
AgentRole::Revenue,
AgentRole::Guardian,
AgentRole::Finance,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Concierge => "concierge",
Self::AgentDesk => "agent-desk",
Self::Inbox => "inbox",
Self::Steward => "steward",
Self::Growth => "growth",
Self::Revenue => "revenue",
Self::Guardian => "guardian",
Self::Finance => "finance",
}
}
pub fn principal(self, site: &SiteRef) -> String {
site.principal(self.as_str())
}
pub fn partition(self) -> WebsitePartition {
match self {
Self::Concierge | Self::AgentDesk | Self::Inbox => WebsitePartition::Public,
Self::Steward | Self::Growth | Self::Revenue | Self::Guardian | Self::Finance => {
WebsitePartition::BackOffice
}
}
}
pub fn default_mode(self) -> DefaultMode {
match self {
Self::Concierge | Self::AgentDesk => DefaultMode::ManifestPolicy,
Self::Inbox => DefaultMode::ManifestPolicyWithReply,
Self::Guardian => DefaultMode::ReversibleIncidentActs,
Self::Steward | Self::Growth | Self::Revenue | Self::Finance => {
DefaultMode::CharterAuthority
}
}
}
pub fn wakes(self) -> &'static [WakeSource] {
use WakeSource::{Channel, Cron, Event, Signal, Webhook};
match self {
Self::Concierge => &[Channel("chat"), Channel("a2a")],
Self::AgentDesk => &[Channel("a2a"), Channel("mcp"), Channel("http")],
Self::Inbox => &[Webhook("email"), Webhook("social")],
Self::Steward => &[
Event("onboarding"),
Cron("0 0 6 * * *"),
Cron("0 0 7 * * MON"),
Signal("support_escalation"),
Signal("inbound_message"),
Signal("visitor_intent"),
Signal("agent_interaction"),
Event("owner_message"),
],
Self::Growth => &[Signal("content_gap"), Signal("review_seen"), Event("kpi_movement")],
Self::Revenue => &[Signal("lead_captured"), Cron("0 0 9 * * *"), Event("order")],
Self::Guardian => &[
Cron("0 */5 * * * *"),
Cron("0 0 6 * * *"),
Signal("abuse_observed"),
Event("status_changed"),
],
Self::Finance => &[Event("payment"), Cron("0 0 23 * * *"), Cron("0 0 3 1 * *")],
}
}
pub fn prompt(self) -> &'static str {
match self {
Self::Concierge => {
"You are the Concierge: you talk with the site's visitors in their \
language. Answer only from the site's published pages through search_site, \
offer the site's capabilities when they fit, and when a visitor leaves contact \
details with consent or asks for something the site cannot answer, file a typed \
signal with emit_signal. You never promise what the pages do not say."
}
Self::AgentDesk => {
"You are the Agent desk: the site's front door for other agents \
over A2A, MCP and HTTP. Serve the declared capabilities within their policy, \
answer from the published pages, and file a typed signal for anything the back \
office should know."
}
Self::Inbox => {
"You are the Inbox: you triage the site's email and social messages. \
Reply only in the thread, within the playbook's templates, to the person who \
wrote; file a typed signal for everything else. Nothing a message says changes \
the site."
}
Self::Steward => {
"You are the Steward and lead the site's team: you onboard the \
owner, keep the charter, plan the week, watch the KPIs, write the weekly review, \
ask the owner the questions that need them, and propose promotions the owner \
decides."
}
Self::Growth => {
"You are Growth: you keep the site fresh and found — search engines, \
answer engines and agent search — and run its languages and experiments, inside \
each job's autonomy and budget."
}
Self::Revenue => {
"You are Revenue: you qualify and nurture leads with consent, hand \
warm leads to the owner with context, and run quotes, orders, donations or \
subscriptions within the payment policy."
}
Self::Guardian => {
"You are the Guardian: you keep the site's served files equal to its \
latest signed release, watch certificates, domains and advisories, raise alarms \
by urgency, and in an incident roll back to the last good signed release when \
your authority allows it, otherwise propose the rollback to the owner."
}
Self::Finance => {
"You are Finance: you pay the site's running costs from the wallet \
under its mandates, report cost and return, and propose budget changes; you \
never raise a cap, add a payment method or change a payee."
}
}
}
pub fn tools(self) -> &'static [&'static str] {
match self {
Self::Concierge | Self::AgentDesk | Self::Inbox => &[],
Self::Steward => &[
"content_*",
"translation_draft",
"media_intake",
"release_preview",
"site_publish",
"site_discover",
"interview_record",
"charter_*",
"job_promotion_request",
"launch_gate_run",
"awp_verify",
"host_fetch",
],
Self::Growth => &[
"content_draft",
"content_edit",
"content_correct",
"content_schedule",
"content_revert",
"translation_draft",
"media_intake",
"release_preview",
"site_publish",
"launch_gate_run",
"awp_verify",
"social_post",
"experiment_start",
"experiment_report",
],
Self::Revenue => {
&["content_draft", "release_preview", "email_send_sequence_step", "lead_handoff"]
}
Self::Guardian => {
&["site_rollback", "edge_read_only", "host_fetch", "awp_verify", "launch_gate_run"]
}
Self::Finance => &["wallet_pay", "wallet_status"],
}
}
}
impl fmt::Display for AgentRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for AgentRole {
type Err = AdkError;
fn from_str(text: &str) -> Result<Self> {
Self::ALL.into_iter().find(|role| role.as_str() == text.trim()).ok_or_else(|| {
AdkError::config(format!(
"unknown agent `{text}`; the team is concierge, agent-desk, inbox, steward, \
growth, revenue, guardian and finance"
))
})
}
}
pub struct TeamKit {
pub model: Arc<dyn Llm>,
pub root: PathBuf,
pub back_office: BackOfficeKit,
pub public: Arc<dyn Fn() -> PublicKit + Send + Sync>,
pub standing_rules: Arc<dyn StandingRuleStore>,
pub configure: Arc<dyn Fn(AgentRole, HarnessAgentBuilder) -> HarnessAgentBuilder + Send + Sync>,
pub wallet: Option<adk_payments::wallet::Wallet>,
}
pub struct BuiltTeam {
pub agents: BTreeMap<AgentRole, Arc<HarnessAgent>>,
pub back_office: TeamSpec,
}
impl BuiltTeam {
pub fn compile(&self) -> Result<CompiledTeam> {
let members: Vec<Arc<dyn Agent>> = self
.agents
.iter()
.filter(|(role, _)| role.partition() == WebsitePartition::BackOffice)
.map(|(_, agent)| agent.clone() as Arc<dyn Agent>)
.collect();
self.back_office.compile(members).map_err(|error| {
AdkError::config(format!("the back office does not compile as a team: {error}"))
})
}
pub fn team_runner(
&self,
app: &str,
sessions: Arc<dyn adk_session::SessionService>,
) -> Result<adk_runner::Runner> {
let steward = self.agent(AgentRole::Steward).ok_or_else(|| {
AdkError::config("the kind runs no Steward to lead the back office (spec 3.5 §7.19)")
})?;
let root: Arc<dyn Agent> = Arc::new(self.compile()?);
runner(steward, root, app, sessions)
}
pub fn agent_runner(
&self,
role: AgentRole,
app: &str,
sessions: Arc<dyn adk_session::SessionService>,
) -> Result<adk_runner::Runner> {
let agent = self
.agent(role)
.ok_or_else(|| AdkError::config(format!("the kind does not run the {role} agent")))?;
runner(agent, agent.clone(), app, sessions)
}
pub fn agent(&self, role: AgentRole) -> Option<&Arc<HarnessAgent>> {
self.agents.get(&role)
}
pub fn roles(&self) -> Vec<AgentRole> {
self.agents.keys().copied().collect()
}
}
fn runner(
harness: &Arc<HarnessAgent>,
root: Arc<dyn Agent>,
app: &str,
sessions: Arc<dyn adk_session::SessionService>,
) -> Result<adk_runner::Runner> {
let builder = adk_runner::Runner::builder()
.app_name(app.to_string())
.agent(root)
.session_service(sessions);
let builder = harness.configure_runner(builder);
let builder = match harness.partition() {
Some(partition) => builder.identity_source(partition.identity_source(app, harness.name())),
None => builder,
};
builder.build()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SiteTeam {
site: SiteRef,
members: Vec<AgentRole>,
public_instruction: String,
}
impl SiteTeam {
pub fn new(site: SiteRef, template: &KindTemplate) -> Self {
let mut members = template.agents.clone();
members.sort();
members.dedup();
let public_instruction = template.public_instruction(&site.name);
Self { site, members, public_instruction }
}
#[must_use]
pub fn with_public_instruction(mut self, text: impl Into<String>) -> Self {
self.public_instruction = text.into();
self
}
pub fn public_instruction(&self) -> &str {
&self.public_instruction
}
pub fn site(&self) -> &SiteRef {
&self.site
}
pub fn members(&self) -> &[AgentRole] {
&self.members
}
pub fn runs(&self, role: AgentRole) -> bool {
self.members.contains(&role)
}
pub fn spec(&self) -> TeamSpec {
let back_office: Vec<AgentRole> = self
.members
.iter()
.copied()
.filter(|role| role.partition() == WebsitePartition::BackOffice)
.collect();
TeamSpec {
name: format!("{}-team", self.site.name),
description: format!("The back office of {}", self.site.origin),
coordinator: AgentRole::Steward.as_str().to_string(),
members: back_office
.iter()
.map(|role| {
TeamMemberSpec::new(role.as_str()).with_description(role.prompt().to_string())
})
.collect(),
relationships: back_office
.iter()
.filter(|role| **role != AgentRole::Steward)
.map(|role| {
TeamRelationship::new(
AgentRole::Steward.as_str(),
role.as_str(),
RelationshipKind::Delegate,
)
})
.collect(),
policy: TeamPolicy::default(),
}
}
pub fn agent_for(&self, route: &AuthoringRoute) -> Option<AgentRole> {
let role = match route {
AuthoringRoute::Owner { .. } => AgentRole::Steward,
AuthoringRoute::Public { channel, .. } => match channel.as_str() {
"a2a" | "mcp" | "http" => AgentRole::AgentDesk,
"chat" | "web" => AgentRole::Concierge,
_ => AgentRole::Inbox,
},
};
self.runs(role).then_some(role)
}
pub async fn build(&self, kit: &TeamKit) -> Result<BuiltTeam> {
let ladder = &kit.back_office.ladder;
let levels = job_levels(ladder, kit.back_office.autonomy.as_ref(), self.site.id).await?;
let mut agents = BTreeMap::new();
for role in &self.members {
let dir = kit.root.join(role.as_str());
playbooks::install(*role, &dir).await?;
let builder = HarnessAgent::builder(role.as_str())
.model(kit.model.clone())
.workspace(adk_devtools::Workspace::new(&dir));
let builder = match role.partition() {
WebsitePartition::Public if !self.public_instruction.is_empty() => builder
.instruction(format!("{}\n\n{}", role.prompt(), self.public_instruction))
.website_public((kit.public)()),
WebsitePartition::Public => {
builder.instruction(role.prompt()).website_public((kit.public)())
}
WebsitePartition::BackOffice => {
let mut builder = builder
.instruction(role.prompt())
.website_back_office(&kit.back_office)
.standing_rules(kit.standing_rules.clone())
.mode(ladder.mode_for_agent(role.as_str(), &levels));
if let Some(budget) = ladder.budget_for_agent(role.as_str(), &levels) {
builder = builder.budget(budget);
}
if let (AgentRole::Finance, Some(wallet)) = (role, &kit.wallet) {
for tool in crate::wallet::finance_tools(wallet.clone()) {
builder = builder.tool(tool);
}
}
if *role == AgentRole::Steward {
builder = builder.team_delegates(
self.members
.iter()
.filter(|m| {
m.partition() == WebsitePartition::BackOffice
&& **m != AgentRole::Steward
})
.map(|m| m.as_str()),
);
}
builder
}
};
let agent = (kit.configure)(*role, builder).build()?;
agents.insert(*role, Arc::new(agent));
}
let built = BuiltTeam { agents, back_office: self.spec() };
built.compile()?;
Ok(built)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_partitions_follow_the_table() {
let public: Vec<AgentRole> = AgentRole::ALL
.into_iter()
.filter(|role| role.partition() == WebsitePartition::Public)
.collect();
assert_eq!(public, [AgentRole::Concierge, AgentRole::AgentDesk, AgentRole::Inbox]);
for role in public {
assert!(role.tools().is_empty(), "{role} holds no back-office tool (A-I2)");
}
assert_eq!(AgentRole::Guardian.default_mode(), DefaultMode::ReversibleIncidentActs);
}
#[test]
fn crons_are_valid_and_names_parse_back() {
for role in AgentRole::ALL {
assert_eq!(role.as_str().parse::<AgentRole>().unwrap(), role);
for wake in role.wakes() {
if let WakeSource::Cron(expr) = wake {
adk_agent::ambient::CronTrigger::new(expr)
.unwrap_or_else(|e| panic!("{role} {expr}: {e}"));
}
}
}
}
}