Skip to main content

adk_kernel/agents/
change.rs

1//! The changes the agent table makes, their previews, and what removing an agent ends
2//! (spec 3.3 §5.7).
3
4use std::fmt;
5
6use adk_core::ApprovalRisk;
7use serde::{Deserialize, Serialize};
8
9use crate::agents::record::{AgentDefinition, AgentRecord};
10
11/// A change a person asks the agent table for (spec 3.3 §5.7). Every change is previewed
12/// first and applied only with its preview's digest.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_kernel::agents::{AgentAction, AgentDefinition};
18///
19/// let add = AgentAction::Create { definition: AgentDefinition::new("Finance", "default"), replaces: None };
20/// let pause = AgentAction::Pause { id: "finance".into() };
21/// assert_ne!(add.digest(), pause.digest());
22/// assert_eq!(serde_json::to_value(&pause).unwrap()["action"], "pause");
23/// ```
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(tag = "action", rename_all = "camelCase", rename_all_fields = "camelCase")]
26#[non_exhaustive]
27pub enum AgentAction {
28    /// Add an agent by hand.
29    Create {
30        /// What it is.
31        definition: AgentDefinition,
32        /// The waiting suggestion this replaces, by its agent id, when the person changed a
33        /// suggestion before adding it ("Change it first"); the suggestion then ends as
34        /// "You changed it and added it".
35        #[serde(default, skip_serializing_if = "Option::is_none")]
36        replaces: Option<String>,
37    },
38    /// Change an agent's definition; its area stays.
39    Change {
40        /// The agent.
41        id: String,
42        /// The version the change was made against.
43        expected_version: u64,
44        /// What it becomes.
45        definition: AgentDefinition,
46    },
47    /// Pause an agent: its work stops at its next step.
48    Pause {
49        /// The agent.
50        id: String,
51    },
52    /// Resume an agent a person paused.
53    Resume {
54        /// The agent.
55        id: String,
56    },
57    /// Remove an agent, ending its work, routines, waiting decisions and follow-ups.
58    Remove {
59        /// The agent.
60        id: String,
61        /// The version the removal was asked against.
62        expected_version: u64,
63    },
64}
65
66impl AgentAction {
67    /// The agent it names; `None` for a new one.
68    pub fn id(&self) -> Option<&str> {
69        match self {
70            Self::Create { .. } => None,
71            Self::Change { id, .. }
72            | Self::Pause { id }
73            | Self::Resume { id }
74            | Self::Remove { id, .. } => Some(id),
75        }
76    }
77
78    /// The action's name: `create`, `change`, `pause`, `resume` or `remove`.
79    pub fn name(&self) -> &'static str {
80        match self {
81            Self::Create { .. } => "create",
82            Self::Change { .. } => "change",
83            Self::Pause { .. } => "pause",
84            Self::Resume { .. } => "resume",
85            Self::Remove { .. } => "remove",
86        }
87    }
88
89    /// The digest of the change as asked: the SHA-256, in lowercase hex, of its canonical
90    /// JSON with any definition [normalized](AgentDefinition::normalized). A preview carries
91    /// it, and the table applies the change only with it.
92    pub fn digest(&self) -> String {
93        use sha2::Digest as _;
94
95        let canonical = match self {
96            Self::Create { definition, replaces } => Self::Create {
97                definition: definition.clone().normalized(),
98                replaces: replaces.clone(),
99            },
100            Self::Change { id, expected_version, definition } => Self::Change {
101                id: id.clone(),
102                expected_version: *expected_version,
103                definition: definition.clone().normalized(),
104            },
105            other => other.clone(),
106        };
107        let bytes = serde_json::to_vec(&canonical).unwrap_or_default();
108        sha2::Sha256::digest(&bytes).iter().map(|byte| format!("{byte:02x}")).collect()
109    }
110}
111
112/// What removing an agent ends, named before it happens and recorded when it has (spec 3.3
113/// §5.7, S-I16).
114///
115/// # Example
116///
117/// ```rust
118/// use adk_kernel::agents::EndedWork;
119///
120/// let ended = EndedWork::default();
121/// assert!(ended.is_empty());
122/// assert_eq!(serde_json::to_value(&ended).unwrap()["work"], serde_json::json!([]));
123/// ```
124#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase")]
126#[non_exhaustive]
127pub struct EndedWork {
128    /// The pids of its processes that are not routines and have not finished.
129    #[serde(default)]
130    pub work: Vec<String>,
131    /// The pids of its routines: its scheduled processes and sleepers.
132    #[serde(default)]
133    pub routines: Vec<String>,
134    /// The ids of the inbox requests waiting for a person that its runs made.
135    #[serde(default)]
136    pub decisions: Vec<String>,
137    /// The ids of its open agenda follow-ups.
138    #[serde(default)]
139    pub follow_ups: Vec<String>,
140    /// How many standing rules pinned to it were revoked; known once it is removed.
141    #[serde(default)]
142    pub rules: u64,
143}
144
145impl EndedWork {
146    /// Whether nothing ends.
147    pub fn is_empty(&self) -> bool {
148        self.work.is_empty()
149            && self.routines.is_empty()
150            && self.decisions.is_empty()
151            && self.follow_ups.is_empty()
152            && self.rules == 0
153    }
154}
155
156/// What a change would do, shown before it is applied (spec 3.3 §5.7): the agent's
157/// abilities and risk as it would be, what the change touches, and the digest that confirms
158/// it.
159///
160/// # Example
161///
162/// ```rust
163/// use adk_core::ApprovalRisk;
164/// use adk_kernel::agents::{AgentAssessment, AgentPreview};
165///
166/// let preview = AgentPreview::new("finance", "create", "0a1b2c3d", AgentAssessment::new(ApprovalRisk::Medium));
167/// assert_eq!(preview.code(), "0a1b2c");
168/// assert!(preview.needs_presence() == false);
169/// ```
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "camelCase")]
172#[non_exhaustive]
173pub struct AgentPreview {
174    /// The agent: the id a new one would get.
175    pub id: String,
176    /// The action: `create`, `change`, `pause`, `resume` or `remove`.
177    pub action: String,
178    /// What the agent can do as it would be, in plain sentences.
179    #[serde(default)]
180    pub abilities: Vec<String>,
181    /// The risk of the change: of the agent as it would be when it can do more, low when it
182    /// can only do less.
183    pub risk: ApprovalRisk,
184    /// Whether the agent as it would be can spend money.
185    #[serde(default)]
186    pub money: bool,
187    /// Whether the change lets the agent do more than it could; a new agent always does.
188    #[serde(default)]
189    pub widens: bool,
190    /// The definition fields a change touches, by their wire names.
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    pub fields: Vec<String>,
193    /// The definition before a change.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub was: Option<AgentDefinition>,
196    /// The definition after a create or change.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub now: Option<AgentDefinition>,
199    /// What a removal ends.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub ended: Option<EndedWork>,
202    /// The digest that applies the change ([`AgentAction::digest`]).
203    pub digest: String,
204}
205
206impl AgentPreview {
207    /// A preview of `action` on `id` with `digest`, at `assessment`'s risk.
208    pub fn new(
209        id: impl Into<String>,
210        action: impl Into<String>,
211        digest: impl Into<String>,
212        assessment: crate::agents::AgentAssessment,
213    ) -> Self {
214        Self {
215            id: id.into(),
216            action: action.into(),
217            abilities: assessment.abilities,
218            risk: assessment.risk,
219            money: assessment.money,
220            widens: false,
221            fields: Vec::new(),
222            was: None,
223            now: None,
224            ended: None,
225            digest: digest.into(),
226        }
227    }
228
229    /// The short code a text command confirms the change with: the digest's first six
230    /// characters (`/agent remove finance --confirm 3f9a2c`).
231    pub fn code(&self) -> &str {
232        &self.digest[..self.digest.len().min(6)]
233    }
234
235    /// Whether applying it needs the person's presence: a change that lets the agent do
236    /// more at high risk or with money (spec 3.3 §7.2).
237    pub fn needs_presence(&self) -> bool {
238        self.widens && (self.risk >= ApprovalRisk::High || self.money)
239    }
240}
241
242/// What happened to an agent, as `KernelEvent::Agent` and the `kernel.agent.*` records name
243/// it (spec 3.3 §5.7, §10 K7).
244///
245/// # Example
246///
247/// ```rust
248/// use adk_kernel::agents::AgentChange;
249///
250/// assert_eq!(AgentChange::CantStart.to_string(), "cantStart");
251/// assert_eq!(serde_json::to_value(AgentChange::Created).unwrap(), "created");
252/// ```
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255#[non_exhaustive]
256pub enum AgentChange {
257    /// An agent suggested one; it waits for a person.
258    Proposed,
259    /// A person added it, by hand or by approving a suggestion.
260    Created,
261    /// A person changed its definition.
262    Changed,
263    /// A person paused it.
264    Paused,
265    /// A person resumed it.
266    Resumed,
267    /// Its removal started.
268    Removing,
269    /// It was removed.
270    Removed,
271    /// A suggestion or change was refused.
272    Refused,
273    /// The host could not build it.
274    CantStart,
275    /// The kernel built and hosts it.
276    Hosted,
277}
278
279impl AgentChange {
280    /// The change's name.
281    pub fn as_str(self) -> &'static str {
282        match self {
283            Self::Proposed => "proposed",
284            Self::Created => "created",
285            Self::Changed => "changed",
286            Self::Paused => "paused",
287            Self::Resumed => "resumed",
288            Self::Removing => "removing",
289            Self::Removed => "removed",
290            Self::Refused => "refused",
291            Self::CantStart => "cantStart",
292            Self::Hosted => "hosted",
293        }
294    }
295}
296
297impl fmt::Display for AgentChange {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        f.pad(self.as_str())
300    }
301}
302
303/// An agent as the table lists it (spec 3.3 §5.7): its record, and why the host cannot
304/// build it when it cannot ("Can't start").
305///
306/// # Example
307///
308/// ```rust
309/// use adk_core::principal::SubjectRef;
310/// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, AgentView};
311///
312/// let record = AgentRecord::new("finance", AgentDefinition::new("Finance", "default"),
313///     AgentRecordState::Active, AgentOrigin::ByHand, SubjectRef::human("alice"), chrono::Utc::now());
314/// let view = AgentView::new(record).with_cant_start("No key for Anthropic");
315/// assert_eq!(serde_json::to_value(&view).unwrap()["cantStart"], "No key for Anthropic");
316/// ```
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
318#[serde(rename_all = "camelCase")]
319#[non_exhaustive]
320pub struct AgentView {
321    /// The record.
322    pub agent: AgentRecord,
323    /// Why the host cannot build it, on this kernel.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub cant_start: Option<String>,
326}
327
328impl AgentView {
329    /// A view of `agent` that starts.
330    pub fn new(agent: AgentRecord) -> Self {
331        Self { agent, cant_start: None }
332    }
333
334    /// Sets why it cannot start.
335    #[must_use]
336    pub fn with_cant_start(mut self, reason: impl Into<String>) -> Self {
337        self.cant_start = Some(reason.into());
338        self
339    }
340}