Skip to main content

adk_harness/website/
partitions.rs

1//! The two partitions of a site and the agents built in them (spec 3.5 §7.10, §7.19, D-5,
2//! A-I2, A-I3, A-I22).
3//!
4//! | | Public | Back office |
5//! |---|---|---|
6//! | Partition | `{site}.public`, class `website.public`, read-only mode | `{site}.back-office`, class `website.back-office`, plan mode until the charter compiles to more |
7//! | Principals | `urn:adk:agent:{site}/{agent}` | `urn:adk:agent:{site}/{agent}` |
8//! | Memory scope | `{site}/public`: no owner facts | `{site}/back-office`: the owner's facts, the charter |
9//! | Tools | declared capabilities, `search_site`, `reply_in_thread`, `emit_signal` | the back-office toolset |
10//! | Policy | [`PublicPolicy`]: the manifest's fixed list, no standing rules | the partition policy, [`WebsitePolicy`], the ladder and job pauses, `adk-drivers`' caps |
11//!
12//! Neither partition crosses into the other: a signal is not a crossing, and a back-office
13//! request for the raw text behind a signal (`signal_source_text`) is a crossing into the
14//! public partition's sessions, which the public partition refuses.
15
16use std::sync::Arc;
17
18use adk_core::audit_log::AuditActor;
19use adk_core::{Result, Tool, ToolContext, ToolEffect};
20use adk_kernel::charter::{AutonomyStore, JobPauses, SignalSink, SignalSourceTool, SignalStore};
21use adk_kernel::{AgendaStore, CrossPartition, Partition, PartitionMode, Partitions};
22use async_trait::async_trait;
23use serde_json::Value;
24
25use super::back_office::back_office_tools;
26use super::catalog::PUBLIC_ORIGIN;
27use super::ladder::LadderCompiler;
28use super::policy::WebsitePolicy;
29use super::public::{EmitSignalTool, PublicPolicy};
30use super::search::{SearchSiteTool, SiteSearch};
31use super::site::{SiteRef, SiteRuntime, kernel_error};
32use crate::builder::HarnessAgentBuilder;
33use crate::facts::FactScope;
34
35/// `AgentPrincipal.class` of the public partition's agents.
36pub const PUBLIC_CLASS: &str = "website.public";
37/// `AgentPrincipal.class` of the back office's agents.
38pub const BACK_OFFICE_CLASS: &str = "website.back-office";
39
40/// A site's public and back-office partitions (spec 3.5 §7.10).
41///
42/// Each partition's tenant is the site, so in agency mode every site's agents carry their
43/// own site as tenant and no partition of one site is another's (A-I22).
44///
45/// # Example
46///
47/// ```rust
48/// use adk_harness::website::{SitePartitions, SiteRef};
49///
50/// let partitions = SitePartitions::new(&SiteRef::new(uuid::Uuid::nil(), "bakery", "https://bakery.example"));
51/// assert_eq!(partitions.public().id.as_str(), "bakery.public");
52/// assert_eq!(partitions.back_office().memory_scope, "bakery/back-office");
53/// let principal = partitions.back_office().principal("bakery", "steward");
54/// assert_eq!(principal.id.as_str(), "urn:adk:agent:bakery/steward");
55/// assert_eq!(principal.tenant.as_deref(), Some("bakery"));
56/// ```
57#[derive(Clone, Debug, PartialEq)]
58pub struct SitePartitions {
59    site: SiteRef,
60    public: Partition,
61    back_office: Partition,
62}
63
64impl SitePartitions {
65    /// The partitions of `site`.
66    pub fn new(site: &SiteRef) -> Self {
67        let public = Partition::new(format!("{}.public", site.name), PUBLIC_CLASS)
68            .with_tenant(site.name.clone())
69            .with_memory_scope(format!("{}/public", site.name))
70            .with_mode(PartitionMode::ReadOnly)
71            .with_cross_partition(CrossPartition::Deny);
72        let back_office = Partition::new(format!("{}.back-office", site.name), BACK_OFFICE_CLASS)
73            .with_tenant(site.name.clone())
74            .with_memory_scope(format!("{}/back-office", site.name))
75            .with_mode(PartitionMode::Plan)
76            .with_cross_partition(CrossPartition::Deny);
77        Self { site: site.clone(), public, back_office }
78    }
79
80    /// The site.
81    pub fn site(&self) -> &SiteRef {
82        &self.site
83    }
84
85    /// The public partition.
86    pub fn public(&self) -> &Partition {
87        &self.public
88    }
89
90    /// The back-office partition.
91    pub fn back_office(&self) -> &Partition {
92        &self.back_office
93    }
94
95    /// Writes both partitions into the kernel's table.
96    ///
97    /// # Errors
98    ///
99    /// The table's error.
100    pub async fn install(&self, table: &Partitions, by: AuditActor) -> Result<()> {
101        table.put(self.public.clone(), by.clone()).await.map_err(kernel_error)?;
102        table.put(self.back_office.clone(), by).await.map_err(kernel_error)
103    }
104
105    /// The scope of the owner `user`'s facts in the back office: the facts claims are
106    /// checked against (A-I18).
107    pub fn fact_scope(&self, user: &str) -> FactScope {
108        FactScope::new(self.site.name.clone(), user, Some(self.back_office.memory_scope.clone()))
109    }
110
111    /// The sink public agents file signals into: the back office's agenda (spec 3.5 §7.10).
112    pub fn signal_sink(
113        &self,
114        store: Arc<dyn SignalStore>,
115        agenda: Arc<dyn AgendaStore>,
116    ) -> SignalSink {
117        SignalSink::new(store, agenda, self.back_office.id.clone())
118    }
119}
120
121/// A declared capability served by the public partition: the capability tool, published as
122/// the site's (spec 3.5 §7.4, §7.10), so the manifest policy decides it.
123struct PublicCapability {
124    inner: Arc<dyn Tool>,
125}
126
127#[async_trait]
128impl Tool for PublicCapability {
129    fn name(&self) -> &str {
130        self.inner.name()
131    }
132
133    fn description(&self) -> &str {
134        self.inner.description()
135    }
136
137    fn declaration(&self) -> Value {
138        self.inner.declaration()
139    }
140
141    fn parameters_schema(&self) -> Option<Value> {
142        self.inner.parameters_schema()
143    }
144
145    fn response_schema(&self) -> Option<Value> {
146        self.inner.response_schema()
147    }
148
149    fn annotations(&self) -> Option<&Value> {
150        self.inner.annotations()
151    }
152
153    fn origin(&self) -> &str {
154        PUBLIC_ORIGIN
155    }
156
157    fn effect(&self) -> ToolEffect {
158        self.inner.effect()
159    }
160
161    fn egress(&self, args: &serde_json::Value) -> adk_core::egress::ToolEgress {
162        self.inner.egress(args)
163    }
164
165    fn approval_evidence(&self, args: &serde_json::Value) -> Vec<adk_core::Evidence> {
166        self.inner.approval_evidence(args)
167    }
168
169    fn is_long_running(&self) -> bool {
170        self.inner.is_long_running()
171    }
172
173    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
174        self.inner.execute(ctx, args).await
175    }
176}
177
178/// What a public agent is built with (spec 3.5 §7.10).
179pub struct PublicKit {
180    /// The site's partitions.
181    pub partitions: SitePartitions,
182    /// The kernel's partition table, holding both.
183    pub table: Partitions,
184    /// The current release's index.
185    pub search: Arc<SiteSearch>,
186    /// The back office's signal sink.
187    pub signals: SignalSink,
188    /// `adk-drivers`' `reply_in_thread` over the inbox drivers, for agents that answer
189    /// threads (the Inbox).
190    pub reply: Option<Arc<adk_drivers::ReplyInThread>>,
191    /// The declared capabilities, each with whether the manifest holds its calls.
192    pub capabilities: Vec<(Arc<dyn Tool>, bool)>,
193}
194
195/// The public partition's tools when another runtime serves them, such as the AWP edge's
196/// `PublicTools` (spec 3.5 §7.9, §7.10): the agent is built over these instead of the kit's
197/// own `search_site` and `emit_signal`, which the edge's public policy would refuse.
198///
199/// # Example
200///
201/// ```rust,ignore
202/// let concierge = HarnessAgent::builder("concierge")
203///     .model(model)
204///     .workspace(workspace)
205///     .website_public_served(ServedPublicTools {
206///         partitions,
207///         table,
208///         search_site: edge_tools.search_site.clone(),
209///         reply_in_thread: Some(edge_tools.reply_in_thread.clone()),
210///         emit_signal: edge_tools.emit_signal.clone(),
211///         capabilities: edge_tools.capabilities.iter().map(|tool| (tool.clone(), false)).collect(),
212///     })
213///     .build()?;
214/// ```
215pub struct ServedPublicTools {
216    /// The site's partitions.
217    pub partitions: SitePartitions,
218    /// The kernel's partition table, holding both.
219    pub table: Partitions,
220    /// `search_site`; left out when a declared capability has that name.
221    pub search_site: Arc<dyn Tool>,
222    /// `reply_in_thread`, for agents that answer threads.
223    pub reply_in_thread: Option<Arc<dyn Tool>>,
224    /// `emit_signal`.
225    pub emit_signal: Arc<dyn Tool>,
226    /// The declared capabilities, each with whether the manifest holds its calls here; the
227    /// runtime serving them may hold them on its own governed path too.
228    pub capabilities: Vec<(Arc<dyn Tool>, bool)>,
229}
230
231/// Classes the served public tools by their own origin and name as the website preset
232/// classes the kit's: the public partition's manifest policy is the one policy that decides
233/// them (spec 3.5 §7.10 "Mode").
234#[derive(Debug)]
235struct ServedClasses {
236    tools: std::collections::BTreeSet<(String, String)>,
237}
238
239impl crate::policy::OriginClasses for ServedClasses {
240    fn class_of(&self, source: &str, tool: &str) -> Option<crate::policy::ToolKind> {
241        self.tools
242            .contains(&(source.to_string(), tool.to_string()))
243            .then_some(crate::policy::ToolKind::Todo)
244    }
245}
246
247/// What a back-office agent is built with (spec 3.5 §7.10, §7.11).
248pub struct BackOfficeKit {
249    /// The site's partitions.
250    pub partitions: SitePartitions,
251    /// The kernel's partition table, holding both.
252    pub table: Partitions,
253    /// The site runtime.
254    pub site: Arc<SiteRuntime>,
255    /// The site's jobs.
256    pub ladder: LadderCompiler,
257    /// The jobs' levels.
258    pub autonomy: Arc<dyn AutonomyStore>,
259    /// The jobs' pauses, which the KPI tracker applies (A-I15).
260    pub pauses: Arc<JobPauses>,
261    /// The owner's budgets for driver tools that act within budget.
262    pub driver_budget: adk_drivers::DriverBudget,
263}
264
265impl BackOfficeKit {
266    /// The kit, with the pauses of `ladder`'s jobs and no driver budget.
267    pub fn new(
268        partitions: SitePartitions,
269        table: Partitions,
270        site: Arc<SiteRuntime>,
271        ladder: LadderCompiler,
272        autonomy: Arc<dyn AutonomyStore>,
273    ) -> Self {
274        let pauses = Arc::new(ladder.job_pauses());
275        Self {
276            partitions,
277            table,
278            site,
279            ladder,
280            autonomy,
281            pauses,
282            driver_budget: adk_drivers::DriverBudget::new(),
283        }
284    }
285}
286
287impl HarnessAgentBuilder {
288    /// Builds an agent of the site's public partition (spec 3.5 §7.10, A-I2): the website
289    /// preset in the public partition — read-only mode, the site's tenant, the public memory
290    /// scope — with `search_site`, `emit_signal`, `reply_in_thread` when the kit has one,
291    /// the declared capabilities, and [`PublicPolicy`] denying everything else, whatever a
292    /// model asks. The agent is offered those tools and nothing else: no workspace, memory
293    /// or plan tool.
294    ///
295    /// # Example
296    ///
297    /// ```rust,ignore
298    /// let concierge = HarnessAgent::builder("concierge")
299    ///     .model(model)
300    ///     .workspace(workspace)
301    ///     .website_public(kit)
302    ///     .build()?;
303    /// ```
304    pub fn website_public(self, kit: PublicKit) -> Self {
305        let mut policy = PublicPolicy::new();
306        let mut builder = self
307            .preset(crate::Preset::Website)
308            .partition(kit.partitions.public().clone(), kit.table.clone())
309            .without_todos()
310            .tool(Arc::new(SearchSiteTool::new(kit.search.clone())))
311            .tool(Arc::new(EmitSignalTool::new(kit.signals.clone())));
312        if let Some(reply) = kit.reply {
313            builder = builder.tool(reply);
314        }
315        for (capability, held) in kit.capabilities {
316            policy = policy.with_capability(capability.name(), held);
317            builder = builder.tool(Arc::new(PublicCapability { inner: capability }));
318        }
319        let offered = policy.tools().map(str::to_string).collect();
320        builder.add_operator_policy(Arc::new(policy)).public_only(offered)
321    }
322
323    /// Builds an agent of the site's public partition over tools another runtime serves,
324    /// such as the AWP edge's `PublicTools` (spec 3.5 §7.9, §7.10, A-I2): the partition and
325    /// policy of [`website_public`](Self::website_public), with the served `search_site`
326    /// (unless a declared capability has that name), `reply_in_thread`, `emit_signal` and
327    /// capabilities, each classed by its own origin so the manifest policy decides it. The
328    /// agent is offered those tools and nothing else.
329    ///
330    /// # Example
331    ///
332    /// ```rust,ignore
333    /// let concierge = HarnessAgent::builder("concierge")
334    ///     .model(model)
335    ///     .workspace(workspace)
336    ///     .website_public_served(served)
337    ///     .build()?;
338    /// ```
339    pub fn website_public_served(self, tools: ServedPublicTools) -> Self {
340        let declared_search =
341            tools.capabilities.iter().any(|(tool, _)| tool.name() == super::catalog::SEARCH_SITE);
342        let mut policy = PublicPolicy::new();
343        let mut chosen: Vec<Arc<dyn Tool>> = Vec::new();
344        for (capability, held) in tools.capabilities {
345            policy = policy.with_capability(capability.name(), held);
346            chosen.push(capability);
347        }
348        if !declared_search {
349            chosen.push(tools.search_site);
350        }
351        chosen.extend(tools.reply_in_thread);
352        chosen.push(tools.emit_signal);
353        let classes = ServedClasses {
354            tools: chosen
355                .iter()
356                .map(|tool| (tool.origin().to_string(), tool.name().to_string()))
357                .collect(),
358        };
359        let mut builder = self
360            .preset(crate::Preset::Website)
361            .partition(tools.partitions.public().clone(), tools.table.clone())
362            .without_todos()
363            .tool_classes(Arc::new(classes));
364        for tool in chosen {
365            builder = builder.tool(tool);
366        }
367        let offered = policy.tools().map(str::to_string).collect();
368        builder.add_operator_policy(Arc::new(policy)).public_only(offered)
369    }
370
371    /// Builds an agent of the site's back office (spec 3.5 §7.10, §7.11): the website preset
372    /// in the back-office partition with the back-office toolset, `signal_source_text`
373    /// registered as a crossing into the public partition — denied — and, strictest wins,
374    /// the partition policy, [`WebsitePolicy`]'s holds, the ladder over the jobs' levels
375    /// with their pauses, and `adk-drivers`' caps, which hold every DNS change (A-I21).
376    ///
377    /// The partition starts the agent in plan mode; set the compiled mode after this call
378    /// with `.mode(kit.ladder.mode_for_agent(..))`.
379    ///
380    /// # Example
381    ///
382    /// ```rust,ignore
383    /// let steward = HarnessAgent::builder("steward")
384    ///     .model(model)
385    ///     .workspace(workspace)
386    ///     .website_back_office(&kit)
387    ///     .mode(kit.ladder.mode_for_agent("steward", &levels))
388    ///     .build()?;
389    /// ```
390    pub fn website_back_office(self, kit: &BackOfficeKit) -> Self {
391        let back_office = kit.partitions.back_office();
392        let crossings = kit.table.policy(back_office.id.clone());
393        let signal_source = SignalSourceTool::new(&crossings, kit.partitions.public().id.clone());
394        let mut builder =
395            self.preset(crate::Preset::Website).partition(back_office.clone(), kit.table.clone());
396        for tool in back_office_tools(&kit.site) {
397            builder = builder.tool(tool);
398        }
399        builder
400            .tool(Arc::new(signal_source))
401            .add_operator_policy(Arc::new(crossings))
402            .add_operator_policy(Arc::new(WebsitePolicy::new(kit.site.clone())))
403            .add_operator_policy(kit.ladder.policy(kit.autonomy.clone(), kit.pauses.clone()))
404            .add_operator_policy(Arc::new(adk_drivers::DriverCapPolicy::new(
405                kit.driver_budget.clone(),
406            )))
407    }
408}