adk_kernel/agents/factory.rs
1//! How a host builds the agents a person adds (spec 3.3 §5.7, §10 K7).
2
3use std::sync::Arc;
4
5use adk_core::{AgentId, ApprovalRisk};
6use adk_runner::Runner;
7use async_trait::async_trait;
8use serde::{Deserialize, Serialize};
9
10use crate::agents::record::{AgentDefinition, AgentRecord, AgentUses, ModelChoice};
11use crate::error::Result;
12use crate::partition::{PartitionId, PartitionMode};
13use crate::process::ProgressSource;
14
15/// What an agent definition lets it do, as a factory or the kernel assesses it (spec 3.3
16/// §5.7): the risk of adding it, whether it can spend money, and its abilities in plain
17/// sentences.
18///
19/// The risk is one of [`ApprovalRisk::Low`], [`Medium`](ApprovalRisk::Medium) and
20/// [`High`](ApprovalRisk::High); "High, spends money" is `High` with
21/// [`money`](Self::money).
22///
23/// # Example
24///
25/// ```rust
26/// use adk_core::ApprovalRisk;
27/// use adk_kernel::agents::AgentAssessment;
28///
29/// let low = AgentAssessment::new(ApprovalRisk::Low).with_ability("It can read files in Invoices.");
30/// let high = AgentAssessment::new(ApprovalRisk::High).with_money();
31/// let both = low.clone().merge(high);
32/// assert_eq!(both.risk, ApprovalRisk::High);
33/// assert!(both.money);
34/// assert_eq!(both.abilities, ["It can read files in Invoices."]);
35/// ```
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38#[non_exhaustive]
39pub struct AgentAssessment {
40 /// The risk of adding the agent, or of the change.
41 pub risk: ApprovalRisk,
42 /// Whether it can spend money: the payments or computer-use pack, or a driver that
43 /// spends or publishes (K-I9).
44 #[serde(default)]
45 pub money: bool,
46 /// What it can do, one plain sentence each.
47 #[serde(default, skip_serializing_if = "Vec::is_empty")]
48 pub abilities: Vec<String>,
49}
50
51impl AgentAssessment {
52 /// An assessment at `risk`, spending no money, with no abilities listed.
53 pub fn new(risk: ApprovalRisk) -> Self {
54 Self { risk, money: false, abilities: Vec::new() }
55 }
56
57 /// Marks it as spending money; the risk is then at least high.
58 #[must_use]
59 pub fn with_money(mut self) -> Self {
60 self.money = true;
61 self.risk = self.risk.max(ApprovalRisk::High);
62 self
63 }
64
65 /// Adds an ability.
66 #[must_use]
67 pub fn with_ability(mut self, ability: impl Into<String>) -> Self {
68 self.abilities.push(ability.into());
69 self
70 }
71
72 /// The higher risk of the two, money if either spends it, and the abilities of both,
73 /// each once, `self`'s first.
74 #[must_use]
75 pub fn merge(mut self, other: Self) -> Self {
76 self.risk = self.risk.max(other.risk);
77 self.money |= other.money;
78 for ability in other.abilities {
79 if !self.abilities.contains(&ability) {
80 self.abilities.push(ability);
81 }
82 }
83 if self.money {
84 self.risk = self.risk.max(ApprovalRisk::High);
85 }
86 self
87 }
88}
89
90/// The most a suggesting agent may give an agent it suggests: its own limits now (spec 3.3
91/// §5.7, S-I12).
92///
93/// # Example
94///
95/// ```rust
96/// use adk_kernel::agents::{AgentCeiling, AgentUses, FileAccess};
97/// use adk_kernel::PartitionMode;
98///
99/// let ceiling = AgentCeiling::new(PartitionMode::Ask, AgentUses::default().with_files(FileAccess::Read))
100/// .with_daily_limit(2_000_000);
101/// assert_eq!(ceiling.mode, PartitionMode::Ask);
102/// assert_eq!(ceiling.daily_limit_micro_usd, Some(2_000_000));
103/// ```
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "camelCase")]
106#[non_exhaustive]
107pub struct AgentCeiling {
108 /// The suggesting agent's mode in the suggesting session.
109 pub mode: PartitionMode,
110 /// What the suggesting agent can use.
111 pub uses: AgentUses,
112 /// What the suggesting agent may spend a day, in micro-USD; `None` when nothing limits
113 /// it (spec 3.3 S-I12). The kernel lowers it to the area's daily limit, which every agent
114 /// in the area spends within.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub daily_limit_micro_usd: Option<u64>,
117}
118
119impl AgentCeiling {
120 /// A ceiling of `mode` and `uses`, with no spending limit of its own.
121 pub fn new(mode: PartitionMode, uses: AgentUses) -> Self {
122 Self { mode, uses, daily_limit_micro_usd: None }
123 }
124
125 /// Sets what the suggesting agent may spend a day, in micro-USD (spec 3.3 S-I12).
126 #[must_use]
127 pub fn with_daily_limit(mut self, micro_usd: u64) -> Self {
128 self.daily_limit_micro_usd = Some(micro_usd);
129 self
130 }
131
132 /// This ceiling with its spending limit lowered to `cap`, when there is one.
133 #[must_use]
134 pub(crate) fn within_daily_limit(mut self, cap: Option<u64>) -> Self {
135 self.daily_limit_micro_usd = match (self.daily_limit_micro_usd, cap) {
136 (Some(own), Some(cap)) => Some(own.min(cap)),
137 (own, cap) => own.or(cap),
138 };
139 self
140 }
141}
142
143/// What a person may choose for an agent on this host (spec 3.3 §5.7, decision 21): the
144/// models of every provider whose key the host has, and the packs it can give.
145///
146/// # Example
147///
148/// ```rust
149/// use adk_kernel::agents::{AgentChoices, ModelChoice};
150///
151/// let choices = AgentChoices::default().with_model(ModelChoice::new("anthropic", "claude-sonnet-5-5"));
152/// assert_eq!(choices.models.len(), 1);
153/// ```
154#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "camelCase")]
156#[non_exhaustive]
157pub struct AgentChoices {
158 /// The models an agent may run on, the primary agent's first.
159 #[serde(default)]
160 pub models: Vec<ModelChoice>,
161 /// The packs an agent may have.
162 #[serde(default)]
163 pub packs: Vec<String>,
164}
165
166impl AgentChoices {
167 /// Adds a model.
168 #[must_use]
169 pub fn with_model(mut self, model: ModelChoice) -> Self {
170 self.models.push(model);
171 self
172 }
173
174 /// Adds a pack.
175 #[must_use]
176 pub fn with_pack(mut self, pack: impl Into<String>) -> Self {
177 self.packs.push(pack.into());
178 self
179 }
180}
181
182/// What a hosted agent holds beyond its runner, closed once the kernel stops serving that
183/// build of the agent: when a change replaced it, the agent was removed, or the kernel stops
184/// (spec 3.3 §5.7). A harness closes its toolsets, its container shell's sessions and
185/// distils its sessions' turns into long-term memory.
186///
187/// # Example
188///
189/// ```rust
190/// use adk_kernel::agents::HostedClose;
191///
192/// struct Quiet;
193///
194/// #[async_trait::async_trait]
195/// impl HostedClose for Quiet {
196/// async fn close(&self) {}
197/// }
198/// ```
199#[async_trait]
200pub trait HostedClose: Send + Sync {
201 /// Closes it. Called once, after the runs that started on it have finished.
202 async fn close(&self);
203}
204
205/// An agent a factory built: its runner, and the progress source its harness reports usage,
206/// goal progress and loop-guard verdicts through (spec 3.3 §5.7). The kernel attaches the
207/// source when it hosts the agent, so the agent's spending reaches its own processes.
208#[derive(Clone)]
209#[non_exhaustive]
210pub struct HostedAgent {
211 /// The runner, whose root agent is named by the record's id.
212 pub runner: Arc<Runner>,
213 /// The agent's progress source, when its harness keeps one.
214 pub progress: Option<Arc<dyn ProgressSource>>,
215 /// What closes it once the kernel stops serving it; without one the kernel closes the
216 /// runner.
217 pub close: Option<Arc<dyn HostedClose>>,
218}
219
220impl HostedAgent {
221 /// An agent built as `runner`, with no progress source.
222 pub fn new(runner: Arc<Runner>) -> Self {
223 Self { runner, progress: None, close: None }
224 }
225
226 /// Sets the progress source.
227 #[must_use]
228 pub fn with_progress(mut self, progress: Arc<dyn ProgressSource>) -> Self {
229 self.progress = Some(progress);
230 self
231 }
232
233 /// Sets what closes the agent once the kernel stops serving it, in place of closing its
234 /// runner.
235 #[must_use]
236 pub fn with_close(mut self, close: Arc<dyn HostedClose>) -> Self {
237 self.close = Some(close);
238 self
239 }
240}
241
242impl std::fmt::Debug for HostedAgent {
243 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244 f.debug_struct("HostedAgent")
245 .field("root", &self.runner.root_agent_name())
246 .field("progress", &self.progress.is_some())
247 .field("close", &self.close.is_some())
248 .finish()
249 }
250}
251
252/// How a host builds the agents a person adds (spec 3.3 §5.7, §10 K7), registered with
253/// `KernelBuilder::agent_factory` beside the agent store. `adk-rust up`'s factory builds a
254/// harness agent with the composition the primary agent uses.
255///
256/// The kernel adds its own checks on top of [`assess`](Self::assess) and
257/// [`ceiling`](Self::ceiling): the risk of the agent's drivers by their effect class, its
258/// mode at most its area's, its limit at most its area's; the higher risk wins.
259///
260/// # Example
261///
262/// ```rust
263/// use std::sync::Arc;
264/// use adk_core::{AgentId, ApprovalRisk};
265/// use adk_kernel::agents::{
266/// AgentAssessment, AgentCeiling, AgentChoices, AgentFactory, AgentRecord, HostedAgent,
267/// };
268/// use async_trait::async_trait;
269///
270/// struct Fixed(Arc<adk_runner::Runner>);
271///
272/// #[async_trait]
273/// impl AgentFactory for Fixed {
274/// fn assess(&self, _record: &AgentRecord) -> AgentAssessment {
275/// AgentAssessment::new(ApprovalRisk::Low)
276/// }
277/// async fn ceiling(&self, _agent: &AgentId, _session: &str) -> adk_kernel::Result<Option<AgentCeiling>> {
278/// Ok(None)
279/// }
280/// async fn choices(&self) -> adk_kernel::Result<AgentChoices> {
281/// Ok(AgentChoices::default())
282/// }
283/// async fn build(&self, _record: &AgentRecord) -> adk_kernel::Result<HostedAgent> {
284/// Ok(HostedAgent::new(self.0.clone()))
285/// }
286/// async fn retired(&self, _record: &AgentRecord) -> adk_kernel::Result<u64> {
287/// Ok(0)
288/// }
289/// }
290/// ```
291#[async_trait]
292pub trait AgentFactory: Send + Sync {
293 /// The risk, money and abilities of `record`'s definition (spec 3.3 §5.7's risk table).
294 fn assess(&self, record: &AgentRecord) -> AgentAssessment;
295
296 /// The suggesting agent `agent`'s limits now, in `session`, the session it suggested
297 /// in; `None` when it may suggest nothing.
298 ///
299 /// # Errors
300 ///
301 /// Returns the host's error; the kernel then refuses the suggestion.
302 async fn ceiling(&self, agent: &AgentId, session: &str) -> Result<Option<AgentCeiling>>;
303
304 /// The suggesting agent `agent`'s limits now in `session`, as the agent of `area`, the
305 /// area it suggests in: a host that runs one agent per area answers with that area's
306 /// limits, its drivers included (spec 3.3 S-I12). By default [`ceiling`](Self::ceiling).
307 ///
308 /// # Errors
309 ///
310 /// Returns the host's error; the kernel then refuses the suggestion.
311 async fn ceiling_in(
312 &self,
313 agent: &AgentId,
314 session: &str,
315 area: &PartitionId,
316 ) -> Result<Option<AgentCeiling>> {
317 let _ = area;
318 self.ceiling(agent, session).await
319 }
320
321 /// `definition` as the kernel keeps an agent a person sets up by hand: its instructions
322 /// with secrets redacted and injection patterns labelled, as fetched text is, and its
323 /// line with secrets redacted (spec 3.3 §5.7, spec 3.1 I47). Screening twice changes
324 /// nothing. By default as it is.
325 async fn screen(&self, definition: AgentDefinition) -> AgentDefinition {
326 definition
327 }
328
329 /// What a person may choose for an agent: the models whose key the host has, and the
330 /// packs.
331 ///
332 /// # Errors
333 ///
334 /// Returns the host's error.
335 async fn choices(&self) -> Result<AgentChoices>;
336
337 /// Builds `record`, an active or paused agent, with its root agent named by its id.
338 ///
339 /// # Errors
340 ///
341 /// Returns why it cannot be built, such as a missing key; the kernel keeps the record
342 /// and shows the agent as "Can't start" with the reason.
343 async fn build(&self, record: &AgentRecord) -> Result<HostedAgent>;
344
345 /// Called once when `record` is removed: revokes the standing rules pinned to it and
346 /// answers how many it revoked.
347 ///
348 /// # Errors
349 ///
350 /// Returns the host's error; the next tick calls it again.
351 async fn retired(&self, record: &AgentRecord) -> Result<u64>;
352
353 /// Ids no added agent may take beside the kernel's own: member names, say.
354 fn reserved_ids(&self) -> Vec<String> {
355 Vec::new()
356 }
357
358 /// Names no added agent may take, ignoring case: the primary agent's display name.
359 fn reserved_names(&self) -> Vec<String> {
360 Vec::new()
361 }
362}