Skip to main content

adk_kernel/agents/
table.rs

1//! The kernel's audited agent table (spec 3.3 §5.7, §10 K7): every change to an agent a
2//! person adds goes through it, recorded before it acts.
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::sync::{Arc, Mutex, RwLock, Weak};
6
7use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
8use adk_core::principal::{SubjectKind, SubjectRef};
9use adk_core::{
10    AdkError, AgentId, ApprovalAction, ApprovalPolicy, ApprovalRequest, ApprovalRisk,
11    ApprovalScope, ApprovalService, ApprovalState, ApproverSelector, ErrorCategory, ErrorComponent,
12    InboxQuery, RunState, ToolConfirmationRequest,
13};
14use adk_server::background::WorkflowExecutor;
15use serde::{Deserialize, Serialize};
16use serde_json::{Value, json};
17
18use crate::agenda::{Agenda, AgendaFilter};
19use crate::agents::AGENT_CREATE_TOOL_NAME;
20use crate::agents::caller::AgentCaller;
21use crate::agents::change::{AgentAction, AgentChange, AgentPreview, AgentView, EndedWork};
22use crate::agents::check::{area_limits, changed_fields, kernel_assessment, over_ceiling, widened};
23use crate::agents::factory::{AgentAssessment, AgentCeiling, AgentChoices, AgentFactory};
24use crate::agents::record::{
25    AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, RESERVED_AGENT_NAME, agent_id_for,
26};
27use crate::agents::store::AgentStore;
28use crate::agents::targets::{Added, Targets};
29use crate::audit;
30use crate::bus::KernelEvent;
31use crate::drivers::EffectClass;
32use crate::error::{
33    AGENT_INVALID_CODE, AGENT_NOT_FOUND_CODE, AGENT_OUT_OF_DATE_CODE, AGENT_REFUSED_CODE,
34    AGENT_UNCONFIRMED_CODE, KernelError, Result,
35};
36use crate::partition::{Partition, PartitionId, PartitionMode};
37use crate::process::{ProcessHandle, ProcessKind, ProcessTable, Suspension};
38use crate::stores::ProcessFilter;
39use crate::supervise::Supervision;
40
41/// The approver group of the inbox `adk-rust up` serves: the control plane's `operator`
42/// scope.
43const OPERATOR_GROUP: &str = "operator";
44
45/// The most suggestions one agent may have waiting at once (spec 3.3 §5.7).
46pub const MAX_OPEN_SUGGESTIONS: usize = 3;
47
48/// The surface name of the web home, where an agent paused by hand may be resumed.
49const WEB_SURFACE: &str = "web";
50
51/// Ids no agent gets because the web home's addresses use them: `/ui/agents/new` is the
52/// New agent screen (spec 3.3 §5.7).
53const ROUTE_IDS: [&str; 1] = ["new"];
54
55/// How old a suggestion whose decision was never written must be before the tick ends it:
56/// long enough that no suggestion is still being written.
57const SUGGESTION_GRACE: chrono::Duration = chrono::Duration::minutes(5);
58
59fn agent_error(
60    category: ErrorCategory,
61    code: &'static str,
62    message: impl Into<String>,
63) -> KernelError {
64    KernelError::Core(AdkError::new(ErrorComponent::Server, category, code, message.into()))
65}
66
67fn refused(message: impl Into<String>) -> KernelError {
68    agent_error(ErrorCategory::Forbidden, AGENT_REFUSED_CODE, message)
69}
70
71fn invalid(message: impl Into<String>) -> KernelError {
72    agent_error(ErrorCategory::InvalidInput, AGENT_INVALID_CODE, message)
73}
74
75fn not_found(id: &str) -> KernelError {
76    agent_error(
77        ErrorCategory::NotFound,
78        AGENT_NOT_FOUND_CODE,
79        format!("no agent `{id}`; list them with `adk-rust agents` or `GET /api/kernel/agents`"),
80    )
81}
82
83/// The inbox request id of the suggestion `record`: `agent-<id>-<12 hex>`, the hex from its
84/// definition's digest and the instant it was suggested, so a suggestion made again after a
85/// refusal freed its id gets a request of its own (spec 3.3 §5.7).
86///
87/// # Example
88///
89/// ```rust
90/// use adk_core::principal::SubjectRef;
91/// use adk_kernel::agents::{AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, suggestion_request_id};
92///
93/// let at = chrono::Utc::now();
94/// let record = |at| AgentRecord::new("finance", AgentDefinition::new("Finance", "default"),
95///     AgentRecordState::Proposed, AgentOrigin::ByHand, SubjectRef::human("alice"), at);
96/// let first = suggestion_request_id(&record(at));
97/// assert!(first.starts_with("agent-finance-") && first.len() == "agent-finance-".len() + 12);
98/// assert_ne!(first, suggestion_request_id(&record(at + chrono::Duration::milliseconds(1))));
99/// ```
100pub fn suggestion_request_id(record: &AgentRecord) -> String {
101    use sha2::Digest as _;
102
103    let mut hash = sha2::Sha256::new();
104    hash.update(record.digest.as_bytes());
105    hash.update(record.created_at.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true).as_bytes());
106    let hex: String = hash.finalize().iter().take(6).map(|byte| format!("{byte:02x}")).collect();
107    format!("agent-{}-{hex}", record.id)
108}
109
110/// The agent that suggests an agent, and where (spec 3.3 §5.7): `propose_agent`'s caller.
111///
112/// # Example
113///
114/// ```rust
115/// use adk_core::AgentId;
116/// use adk_kernel::agents::AgentProposer;
117///
118/// let proposer = AgentProposer::new(AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(), "alice", "s-1")
119///     .with_run("run-7");
120/// assert_eq!(proposer.run.as_deref(), Some("run-7"));
121/// ```
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124#[non_exhaustive]
125pub struct AgentProposer {
126    /// The suggesting agent.
127    pub agent: AgentId,
128    /// The person whose session it is; the suggestion waits in their inbox.
129    pub user: String,
130    /// The session it suggests in.
131    pub session: String,
132    /// The durable run it suggests from, when it runs as a kernel process.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub run: Option<String>,
135    /// The suggesting agent's own limits in the turn it suggests in, such as the mode its
136    /// run holds; the kernel checks the suggestion against these as well as the host's
137    /// ceiling, so they only ever tighten it (spec 3.3 S-I12).
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub ceiling: Option<AgentCeiling>,
140}
141
142impl AgentProposer {
143    /// `agent` suggesting in `user`'s session `session`.
144    pub fn new(agent: AgentId, user: impl Into<String>, session: impl Into<String>) -> Self {
145        Self { agent, user: user.into(), session: session.into(), run: None, ceiling: None }
146    }
147
148    /// Sets the durable run.
149    #[must_use]
150    pub fn with_run(mut self, run: impl Into<String>) -> Self {
151        self.run = Some(run.into());
152        self
153    }
154
155    /// Sets the suggesting agent's own limits in this turn.
156    #[must_use]
157    pub fn with_ceiling(mut self, ceiling: AgentCeiling) -> Self {
158        self.ceiling = Some(ceiling);
159        self
160    }
161}
162
163/// A suggestion the table keeps (spec 3.3 §5.7): the suggested agent and its inbox request.
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166#[non_exhaustive]
167pub struct AgentProposal {
168    /// The suggested agent, `Proposed`.
169    pub agent: AgentRecord,
170    /// Its inbox request.
171    pub request_id: String,
172    /// The risk the inbox shows.
173    pub risk: ApprovalRisk,
174    /// Whether the same suggestion was already waiting, so nothing new was added.
175    pub merged: bool,
176}
177
178/// What [`Agents::apply`] did.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(tag = "outcome", rename_all = "camelCase", rename_all_fields = "camelCase")]
181#[non_exhaustive]
182pub enum AgentOutcome {
183    /// The agent was added.
184    Created {
185        /// It.
186        agent: AgentRecord,
187    },
188    /// The agent was changed.
189    Changed {
190        /// It, as it is now.
191        agent: AgentRecord,
192    },
193    /// The agent was paused.
194    Paused {
195        /// It.
196        agent: AgentRecord,
197    },
198    /// The agent was resumed.
199    Resumed {
200        /// It.
201        agent: AgentRecord,
202    },
203    /// The agent was removed.
204    Removed {
205        /// Its tombstone.
206        agent: AgentRecord,
207        /// What ended.
208        ended: EndedWork,
209    },
210}
211
212/// What this replica remembers between ticks.
213#[derive(Default)]
214struct Local {
215    /// Why an agent could not be built, by id, with the version that failed.
216    cant_start: BTreeMap<String, (u64, String)>,
217    /// Suggestions whose approval by someone other than a person was already logged.
218    ignored: BTreeSet<String>,
219    /// Suggestions being settled now, by the tick or by an answer, so one is applied once.
220    settling: BTreeSet<String>,
221}
222
223/// What the kernel gives its agent table when it builds it.
224pub(crate) struct AgentsParts {
225    pub(crate) sup: Arc<Supervision>,
226    pub(crate) processes: ProcessTable,
227    pub(crate) agenda: Agenda,
228    pub(crate) targets: Arc<Targets>,
229    pub(crate) store: Arc<dyn AgentStore>,
230    pub(crate) factory: Option<Arc<dyn AgentFactory>>,
231    pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
232    /// The agent targets the host registered at build.
233    pub(crate) statics: BTreeSet<String>,
234    /// The mode each area's agent started in, as the host told the control plane.
235    pub(crate) start_modes: BTreeMap<PartitionId, PartitionMode>,
236    pub(crate) workflows: Option<Arc<dyn WorkflowExecutor>>,
237    #[cfg(feature = "drivers")]
238    pub(crate) drivers: Option<crate::drivers::DriverSupervisor>,
239    #[cfg(feature = "proc")]
240    pub(crate) ledger: Option<crate::proc::Ledger>,
241}
242
243pub(crate) struct AgentsInner {
244    pub(crate) sup: Arc<Supervision>,
245    pub(crate) processes: ProcessTable,
246    pub(crate) agenda: Agenda,
247    pub(crate) targets: Arc<Targets>,
248    pub(crate) store: Arc<dyn AgentStore>,
249    pub(crate) factory: Option<Arc<dyn AgentFactory>>,
250    pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
251    pub(crate) statics: BTreeSet<String>,
252    pub(crate) start_modes: BTreeMap<PartitionId, PartitionMode>,
253    pub(crate) workflows: Option<Arc<dyn WorkflowExecutor>>,
254    #[cfg(feature = "drivers")]
255    pub(crate) drivers: Option<crate::drivers::DriverSupervisor>,
256    #[cfg(feature = "proc")]
257    pub(crate) ledger: Option<crate::proc::Ledger>,
258    local: Mutex<Local>,
259    /// Held while this replica finishes a removal, so the tick never finishes one beside a
260    /// person's: both would revoke the agent's rules, and the person's outcome would count
261    /// only those it reached first.
262    removing: tokio::sync::Mutex<()>,
263}
264
265/// The kernel's audited agent table (spec 3.3 §5.7, §10 K7), from
266/// [`Kernel::agents`](crate::Kernel::agents): the one front door for adding, changing,
267/// pausing and removing the agents a person adds, whichever surface asks.
268///
269/// Its rules:
270///
271/// | Rule | Spec |
272/// |---|---|
273/// | Only a person changes an agent; a device only answers suggestions | S-I11, decision 16 |
274/// | A change previews first and applies only with its preview's digest | §5.7 |
275/// | High risk or money needs presence: a paired local terminal or "Confirm it's you" | §7.2, decision 22 |
276/// | A definition stays within its area: its mode, limit and mounted drivers | §5.7, K-I13 |
277/// | A suggestion stays within its suggester, checked when made and again when approved | S-I12 |
278/// | Every change is recorded (`kernel.agent.*`) before it acts, and refused when the record cannot be written | S-I18, K-I16 |
279/// | A removed agent's id is never given again | S-I14 |
280///
281/// Cloning shares the table.
282///
283/// # Example
284///
285/// ```rust,no_run
286/// use adk_core::principal::SubjectRef;
287/// use adk_kernel::agents::{AgentAction, AgentCaller, AgentDefinition, Presence};
288///
289/// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
290/// let caller = AgentCaller::new(SubjectRef::human("alice"), "terminal", "keyboard")
291///     .with_presence(Presence::PairedLocal);
292/// let add = AgentAction::Create { definition: AgentDefinition::new("Finance", "default"), replaces: None };
293/// let preview = kernel.agents().preview(&caller, &add).await?;
294/// println!("{} — {:?} risk; confirm with {}", preview.id, preview.risk, preview.code());
295/// kernel.agents().apply(&caller, add, &preview.digest).await?;
296/// # Ok(())
297/// # }
298/// ```
299#[derive(Clone)]
300pub struct Agents {
301    inner: Arc<AgentsInner>,
302}
303
304impl std::fmt::Debug for Agents {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        f.debug_struct("Agents")
307            .field("factory", &self.inner.factory.is_some())
308            .field("hosted", &self.inner.targets.hosted_ids())
309            .finish_non_exhaustive()
310    }
311}
312
313/// A handle on a kernel's agent table that does not keep the kernel alive, bound when the
314/// kernel is built (spec 3.3 §10 K7): the harness's `propose_agent` tool exists before the
315/// kernel that hosts it, as `propose_followup`'s [`AgendaHandle`](crate::AgendaHandle) does.
316///
317/// # Example
318///
319/// ```rust
320/// use adk_kernel::agents::AgentsHandle;
321///
322/// let handle = AgentsHandle::new();
323/// assert!(handle.get().is_none(), "no kernel was built with it");
324/// ```
325#[derive(Clone, Default)]
326pub struct AgentsHandle {
327    slot: Arc<RwLock<Weak<AgentsInner>>>,
328}
329
330impl std::fmt::Debug for AgentsHandle {
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332        f.debug_struct("AgentsHandle").field("bound", &self.get().is_some()).finish()
333    }
334}
335
336impl AgentsHandle {
337    /// An unbound handle.
338    pub fn new() -> Self {
339        Self::default()
340    }
341
342    /// The agent table of the kernel last built with this handle, while that kernel lives.
343    pub fn get(&self) -> Option<Agents> {
344        let slot = self.slot.read().unwrap_or_else(|e| e.into_inner());
345        slot.upgrade().map(|inner| Agents { inner })
346    }
347
348    pub(crate) fn bind(&self, agents: &Agents) {
349        *self.slot.write().unwrap_or_else(|e| e.into_inner()) = Arc::downgrade(&agents.inner);
350    }
351}
352
353/// What a change would do, worked out once for its preview and its apply.
354struct Plan {
355    preview: AgentPreview,
356    current: Option<AgentRecord>,
357    next: Option<AgentRecord>,
358    replaces: Option<AgentRecord>,
359}
360
361impl Agents {
362    pub(crate) fn new(parts: AgentsParts) -> Self {
363        Self {
364            inner: Arc::new(AgentsInner {
365                sup: parts.sup,
366                processes: parts.processes,
367                agenda: parts.agenda,
368                targets: parts.targets,
369                store: parts.store,
370                factory: parts.factory,
371                approvals: parts.approvals,
372                statics: parts.statics,
373                start_modes: parts.start_modes,
374                workflows: parts.workflows,
375                #[cfg(feature = "drivers")]
376                drivers: parts.drivers,
377                #[cfg(feature = "proc")]
378                ledger: parts.ledger,
379                local: Mutex::default(),
380                removing: tokio::sync::Mutex::default(),
381            }),
382        }
383    }
384
385    /// The store the agents live in.
386    pub fn store(&self) -> &Arc<dyn AgentStore> {
387        &self.inner.store
388    }
389
390    /// Every agent with its state — suggested, active, paused, being removed and removed —
391    /// ordered by id, each with why this kernel cannot build it when it cannot ("Can't
392    /// start"). Refused suggestions, which never were agents, are left out. A surface reads a
393    /// removed agent's state here, so it never looks agents up one by one (spec 3.3 §5.7).
394    ///
395    /// # Errors
396    ///
397    /// Returns the store's error.
398    pub async fn list(&self) -> Result<Vec<AgentView>> {
399        let records = self.inner.store.list().await?;
400        Ok(records
401            .into_iter()
402            .filter(|record| record.state != AgentRecordState::Refused)
403            .map(|record| self.view(record))
404            .collect())
405    }
406
407    /// The agent `id`, tombstones included, or `None`.
408    ///
409    /// # Errors
410    ///
411    /// Returns the store's error.
412    pub async fn get(&self, id: &str) -> Result<Option<AgentView>> {
413        Ok(self.inner.store.get(id).await?.map(|record| self.view(record)))
414    }
415
416    fn view(&self, record: AgentRecord) -> AgentView {
417        let local = self.inner.local.lock().unwrap_or_else(|e| e.into_inner());
418        let reason = local
419            .cant_start
420            .get(&record.id)
421            .filter(|(version, _)| *version == record.version && record.state.is_hosted())
422            .map(|(_, reason)| reason.clone());
423        drop(local);
424        match reason {
425            Some(reason) => AgentView::new(record).with_cant_start(reason),
426            None => AgentView::new(record),
427        }
428    }
429
430    /// What a person may choose for an agent on this host: the models whose key it has, and
431    /// the packs.
432    ///
433    /// # Errors
434    ///
435    /// Returns the factory's error; an empty choice when the host builds no agents.
436    pub async fn choices(&self) -> Result<AgentChoices> {
437        match &self.inner.factory {
438            Some(factory) => factory.choices().await,
439            None => Ok(AgentChoices::default()),
440        }
441    }
442
443    /// What `action` would do, without doing it: the agent's abilities and risk as it would
444    /// be, what it changes, what a removal ends, and the digest that applies it (spec 3.3
445    /// §5.7).
446    ///
447    /// # Errors
448    ///
449    /// Returns `kernel.agent.refused` when `caller` may change no agent, `kernel.agent.invalid`
450    /// for a definition that breaks a rule, `kernel.agent.not_found`,
451    /// `kernel.agent.out_of_date` for a change against an older version, or a store error.
452    pub async fn preview(
453        &self,
454        caller: &AgentCaller,
455        action: &AgentAction,
456    ) -> Result<AgentPreview> {
457        if let Some(reason) = caller.refusal() {
458            return Err(refused(reason));
459        }
460        Ok(self.plan(action).await?.preview)
461    }
462
463    /// Applies `action` for `caller` when `digest` is its preview's (spec 3.3 §5.7), writing
464    /// its `kernel.agent.*` record first.
465    ///
466    /// # Errors
467    ///
468    /// As [`preview`](Self::preview); `kernel.agent.unconfirmed` when `digest` is not the
469    /// preview's; `kernel.agent.refused` for high risk or money without presence; the audit
470    /// trail's error under `AuditFailureMode::Block`, in which case nothing changed.
471    pub async fn apply(
472        &self,
473        caller: &AgentCaller,
474        action: AgentAction,
475        digest: &str,
476    ) -> Result<AgentOutcome> {
477        if let Some(reason) = caller.refusal() {
478            self.record_refused(Some(caller), action.id(), None, &reason).await;
479            return Err(refused(reason));
480        }
481        let plan = match self.plan(&action).await {
482            Ok(plan) => plan,
483            Err(error) => {
484                let message = error.to_string();
485                self.record_refused(Some(caller), action.id(), definition_name(&action), &message)
486                    .await;
487                return Err(error);
488            }
489        };
490        if digest != plan.preview.digest {
491            // Refused as a digest that changed (spec 3.3 §11 `kernel.agent.refused`).
492            let reason = "a digest that changed: this is not the change that was previewed";
493            self.record_refused(Some(caller), action.id(), definition_name(&action), reason).await;
494            return Err(agent_error(
495                ErrorCategory::Conflict,
496                AGENT_UNCONFIRMED_CODE,
497                format!(
498                    "this {} is not the one that was previewed; preview it again and confirm \
499                     with its code ({})",
500                    plan.preview.action,
501                    plan.preview.code()
502                ),
503            ));
504        }
505        if plan.preview.needs_presence() && !caller.presence.is_present() {
506            let reason = "this change is high risk: confirm it's you, or make it on the \
507                          kernel's own terminal";
508            self.record_refused(Some(caller), Some(&plan.preview.id), None, reason).await;
509            return Err(refused(reason));
510        }
511        // An agent paused by hand is resumed in the web home or on a paired local terminal,
512        // where Resume all is (spec 3.3 §5.7, S-I10).
513        if matches!(action, AgentAction::Resume { .. })
514            && caller.surface != WEB_SURFACE
515            && !caller.presence.is_present()
516        {
517            let reason = "resume it in the web home or on the kernel's own terminal";
518            self.record_refused(Some(caller), Some(&plan.preview.id), None, reason).await;
519            return Err(refused(reason));
520        }
521        match action {
522            AgentAction::Create { .. } => self.create_planned(caller, plan).await,
523            AgentAction::Change { .. } => self.change_planned(caller, plan).await,
524            AgentAction::Pause { .. } => self.pause_planned(caller, plan).await,
525            AgentAction::Resume { .. } => self.resume_planned(caller, plan).await,
526            AgentAction::Remove { .. } => self.remove_planned(caller, plan).await,
527        }
528    }
529
530    /// Adds an agent by hand: [`apply`](Self::apply) of [`AgentAction::Create`].
531    ///
532    /// # Errors
533    ///
534    /// As [`apply`](Self::apply).
535    pub async fn create(
536        &self,
537        caller: &AgentCaller,
538        definition: AgentDefinition,
539        digest: &str,
540    ) -> Result<AgentRecord> {
541        match self.apply(caller, AgentAction::Create { definition, replaces: None }, digest).await?
542        {
543            AgentOutcome::Created { agent } => Ok(agent),
544            other => Err(KernelError::Config { reason: format!("unexpected outcome {other:?}") }),
545        }
546    }
547
548    /// Changes agent `id` made against `expected_version`: [`apply`](Self::apply) of
549    /// [`AgentAction::Change`].
550    ///
551    /// # Errors
552    ///
553    /// As [`apply`](Self::apply).
554    pub async fn change(
555        &self,
556        caller: &AgentCaller,
557        id: &str,
558        expected_version: u64,
559        definition: AgentDefinition,
560        digest: &str,
561    ) -> Result<AgentRecord> {
562        let action = AgentAction::Change { id: id.to_string(), expected_version, definition };
563        match self.apply(caller, action, digest).await? {
564            AgentOutcome::Changed { agent } => Ok(agent),
565            other => Err(KernelError::Config { reason: format!("unexpected outcome {other:?}") }),
566        }
567    }
568
569    /// Pauses agent `id`: its work stops at its next step, and it takes no new work until
570    /// it is resumed. Pausing only makes an agent do less, so it needs no digest.
571    ///
572    /// # Errors
573    ///
574    /// As [`apply`](Self::apply), without the digest check.
575    pub async fn pause(&self, caller: &AgentCaller, id: &str) -> Result<AgentRecord> {
576        let action = AgentAction::Pause { id: id.to_string() };
577        let digest = action.digest();
578        match self.apply(caller, action, &digest).await? {
579            AgentOutcome::Paused { agent } => Ok(agent),
580            other => Err(KernelError::Config { reason: format!("unexpected outcome {other:?}") }),
581        }
582    }
583
584    /// Resumes agent `id`, waking only the work its pause stopped.
585    ///
586    /// # Errors
587    ///
588    /// As [`apply`](Self::apply), without the digest check.
589    pub async fn resume(&self, caller: &AgentCaller, id: &str) -> Result<AgentRecord> {
590        let action = AgentAction::Resume { id: id.to_string() };
591        let digest = action.digest();
592        match self.apply(caller, action, &digest).await? {
593            AgentOutcome::Resumed { agent } => Ok(agent),
594            other => Err(KernelError::Config { reason: format!("unexpected outcome {other:?}") }),
595        }
596    }
597
598    /// Removes agent `id` asked against `expected_version`, returning what ended:
599    /// [`apply`](Self::apply) of [`AgentAction::Remove`].
600    ///
601    /// # Errors
602    ///
603    /// As [`apply`](Self::apply).
604    pub async fn remove(
605        &self,
606        caller: &AgentCaller,
607        id: &str,
608        expected_version: u64,
609        digest: &str,
610    ) -> Result<EndedWork> {
611        let action = AgentAction::Remove { id: id.to_string(), expected_version };
612        match self.apply(caller, action, digest).await? {
613            AgentOutcome::Removed { ended, .. } => Ok(ended),
614            other => Err(KernelError::Config { reason: format!("unexpected outcome {other:?}") }),
615        }
616    }
617
618    /// Suggests `definition` for `proposer`, an agent (spec 3.3 §5.7, S-I12): checks it
619    /// against the suggester's limits now and its area's, keeps it `Proposed`, and puts one
620    /// `kernel:agent.create` request in the inbox, which only a person's approval of the
621    /// same definition applies. The same suggestion waiting already is returned merged; at
622    /// most [`MAX_OPEN_SUGGESTIONS`] wait per suggesting agent.
623    ///
624    /// # Errors
625    ///
626    /// `kernel.agent.refused` for a suggestion over its suggester's or area's limits, too
627    /// many waiting, or a kernel without an inbox or a factory; `kernel.agent.invalid` for a
628    /// definition that breaks a rule; a store or audit error.
629    pub async fn propose(
630        &self,
631        definition: AgentDefinition,
632        proposer: &AgentProposer,
633    ) -> Result<AgentProposal> {
634        let definition = definition.normalized();
635        let name = definition.display_name.clone();
636        let result = self.propose_checked(definition, proposer).await;
637        if let Err(error) = &result {
638            let fields = json!({
639                "name": name,
640                "reason": error.to_string(),
641                "suggestingAgent": proposer.agent,
642                "session": proposer.session,
643                "run": proposer.run,
644            });
645            if let Err(error) =
646                self.record(audit::AGENT_REFUSED, None, Some(&proposer.agent), fields).await
647            {
648                tracing::warn!(error = %error, "could not record a refused suggestion");
649            }
650        }
651        result
652    }
653
654    async fn propose_checked(
655        &self,
656        mut definition: AgentDefinition,
657        proposer: &AgentProposer,
658    ) -> Result<AgentProposal> {
659        let inner = &self.inner;
660        let Some(approvals) = inner.approvals.clone() else {
661            return Err(refused("this kernel has no inbox, so no agent can be suggested"));
662        };
663        if inner.factory.is_none() {
664            return Err(refused("this kernel builds no agents of a person's own"));
665        }
666        definition.validate()?;
667        // A suggestion spends at most what its suggester may, which is within its area's daily
668        // limit: one that names no limit of its own is kept with the suggester's, so the card
669        // shows it (spec 3.3 S-I12).
670        if definition.daily_limit_micro_usd.is_none() {
671            let partition = self.area(&definition.area).await?;
672            let ceiling =
673                self.suggester_ceiling(&proposer.agent, &proposer.session, &partition).await?;
674            let cap = ceiling
675                .map(|ceiling| {
676                    let own = proposer.ceiling.as_ref().and_then(|own| own.daily_limit_micro_usd);
677                    ceiling.within_daily_limit(own)
678                })
679                .and_then(|ceiling| ceiling.daily_limit_micro_usd);
680            if let Some(cap) = cap {
681                definition = definition.with_daily_limit(cap);
682            }
683        }
684        let records = inner.store.list().await?;
685        let digest = definition.digest();
686        let mine = |record: &&AgentRecord| {
687            matches!(&record.origin, AgentOrigin::Suggested { agent, .. } if *agent == proposer.agent)
688                && record.state == AgentRecordState::Proposed
689        };
690        if let Some(waiting) = records.iter().filter(mine).find(|record| record.digest == digest) {
691            let request_id = suggestion_request_id(waiting);
692            let risk = match approvals.get(&request_id).await? {
693                Some(request) => request.risk,
694                // Its request was never written: write it now, so the suggestion reaches
695                // Decisions (spec 3.3 §5.7).
696                None => {
697                    let risk = self.assess(waiting).await.risk;
698                    let request = self.suggestion_request(waiting, proposer, risk)?;
699                    approvals.submit(request).await?;
700                    risk
701                }
702            };
703            return Ok(AgentProposal { agent: waiting.clone(), request_id, risk, merged: true });
704        }
705        if records.iter().filter(mine).count() >= MAX_OPEN_SUGGESTIONS {
706            return Err(refused(format!(
707                "{MAX_OPEN_SUGGESTIONS} suggested agents already wait for a person; answer them \
708                 first"
709            )));
710        }
711        let (unattended, area) = self.suggesting_process(proposer).await?;
712        match area {
713            Some(area) if area != definition.area => {
714                return Err(refused(format!(
715                    "a suggested agent works in its suggester's area `{area}`, not `{}`",
716                    definition.area
717                )));
718            }
719            Some(_) => {}
720            // A suggestion from a run the kernel does not know might come from any area, so
721            // it is refused wherever there is more than one (spec 3.3 S-I12).
722            None if self.has_areas_beside(&definition.area).await? => {
723                return Err(refused(format!(
724                    "the kernel cannot tell which area {} suggests from, so it suggests no \
725                     agent in `{}`; suggest it from a turn the kernel runs",
726                    proposer.agent, definition.area
727                )));
728            }
729            None => {}
730        }
731        self.check_names(&definition, &records, None, None)?;
732        let partition = self.area(&definition.area).await?;
733        let over_area = area_limits(&definition, &partition);
734        if !over_area.is_empty() {
735            return Err(refused(format!("it would exceed its area: {}", over_area.join("; "))));
736        }
737        let Some(over) =
738            self.over_suggester(&definition, &proposer.agent, &proposer.session).await?
739        else {
740            return Err(refused(format!("{} may not suggest agents", proposer.agent)));
741        };
742        // The suggester's own limits in the turn it suggests in, such as a mode its run still
743        // holds, only ever tighten the host's (spec 3.3 S-I12).
744        let over = match &proposer.ceiling {
745            Some(own) => {
746                let mut over = over;
747                for item in over_ceiling(&definition, own) {
748                    if !over.contains(&item) {
749                        over.push(item);
750                    }
751                }
752                over
753            }
754            None => over,
755        };
756        if !over.is_empty() {
757            return Err(refused(format!(
758                "{} can't give {} {}: a suggested agent never does more than its suggester",
759                proposer.agent,
760                definition.display_name,
761                over.join(", ")
762            )));
763        }
764        let id = self.allocate_id(&definition.display_name, &records, None);
765        let origin = AgentOrigin::Suggested {
766            agent: proposer.agent.clone(),
767            session: proposer.session.clone(),
768            run: proposer.run.clone(),
769            unattended,
770        };
771        let now = inner.sup.clock.now();
772        let record = AgentRecord::new(
773            id,
774            definition.clone(),
775            AgentRecordState::Proposed,
776            origin,
777            SubjectRef::agent(&proposer.agent),
778            now,
779        );
780        let assessment = self.assess(&record).await;
781        let request_id = suggestion_request_id(&record);
782        // A request of an earlier suggestion with this id, made at this very instant, would
783        // answer this one; it is suggested again instead.
784        if approvals.get(&request_id).await?.is_some() {
785            return Err(agent_error(
786                ErrorCategory::Conflict,
787                AGENT_OUT_OF_DATE_CODE,
788                "an earlier suggestion of this agent was answered at this very moment; suggest \
789                 it again",
790            ));
791        }
792        self.record(
793            audit::AGENT_PROPOSED,
794            None,
795            Some(&proposer.agent),
796            json!({
797                "id": record.id,
798                "digest": record.digest,
799                "risk": assessment.risk,
800                "money": assessment.money,
801                "area": record.area,
802                "suggestingAgent": proposer.agent,
803                "session": proposer.session,
804                "run": proposer.run,
805                "unattended": unattended,
806                // No person acted: the suggesting agent did, through `propose_agent` (spec 3.3
807                // §12 phase 4 step 7: every record names its surface).
808                "surface": "agent",
809                "how": "agent",
810            }),
811        )
812        .await?;
813        if !inner.store.put_if_version(record.clone(), 0).await? {
814            return Err(agent_error(
815                ErrorCategory::Conflict,
816                AGENT_OUT_OF_DATE_CODE,
817                format!("the id `{}` was taken meanwhile; suggest it again", record.id),
818            ));
819        }
820        let request = self.suggestion_request(&record, proposer, assessment.risk)?;
821        if let Err(error) = approvals.submit(request).await {
822            // Without its decision the suggestion would hold its name and a slot for ever:
823            // it is taken back, and the refusal recorded (spec 3.3 §5.7).
824            if let Err(delete) = inner.store.delete(&record.id).await {
825                tracing::warn!(agent.id = %record.id, error = %delete, "could not take back a suggestion whose decision was not written; the tick ends it");
826            }
827            return Err(error.into());
828        }
829        inner.sup.publish(KernelEvent::Agent {
830            id: record.id.clone(),
831            change: AgentChange::Proposed,
832            reason: None,
833        });
834        Ok(AgentProposal { agent: record, request_id, risk: assessment.risk, merged: false })
835    }
836
837    /// The inbox request of the suggestion `record` made by `proposer`: one decision whose
838    /// arguments are the definition, Approve and Reject its only actions, no expiry.
839    fn suggestion_request(
840        &self,
841        record: &AgentRecord,
842        proposer: &AgentProposer,
843        risk: ApprovalRisk,
844    ) -> Result<ApprovalRequest> {
845        let args = serde_json::to_value(record.definition())?;
846        let call = ToolConfirmationRequest::new(AGENT_CREATE_TOOL_NAME, args.clone());
847        let scope = ApprovalScope::new(
848            self.inner.sup.app_name.clone(),
849            proposer.user.clone(),
850            proposer.session.clone(),
851        );
852        // The person or the operators decide; the default forbid_self_approval keeps the
853        // suggesting agent from approving its own suggestion.
854        let policy = ApprovalPolicy::new([
855            ApproverSelector::human(proposer.user.clone()),
856            ApproverSelector::group(OPERATOR_GROUP),
857        ]);
858        let mut request = ApprovalRequest::new(suggestion_request_id(record), scope, &call, policy)
859            .with_redacted_args(args)
860            .with_requester(SubjectRef::agent(&proposer.agent))
861            .with_summary(format!("Add an agent called {}", record.display_name))
862            .with_risk(risk)
863            .with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject]);
864        if let Some(run) = &proposer.run {
865            request = request.with_run_id(run.clone());
866        }
867        Ok(request)
868    }
869
870    /// What `definition` has beyond what the suggesting `agent` may give in `session`, in the
871    /// definition's area; `None` when the agent may suggest none.
872    async fn over_suggester(
873        &self,
874        definition: &AgentDefinition,
875        agent: &AgentId,
876        session: &str,
877    ) -> Result<Option<Vec<String>>> {
878        let partition = self.area(&definition.area).await?;
879        let ceiling = self.suggester_ceiling(agent, session, &partition).await?;
880        Ok(ceiling.map(|ceiling| over_ceiling(definition, &ceiling)))
881    }
882
883    /// What the suggesting `agent` may give in `session` in `area`, as its factory reports it,
884    /// its spending lowered to the area's daily limit, within which it spends (spec 3.3
885    /// S-I12); `None` when it may suggest none.
886    async fn suggester_ceiling(
887        &self,
888        agent: &AgentId,
889        session: &str,
890        area: &Partition,
891    ) -> Result<Option<AgentCeiling>> {
892        let ceiling = match &self.inner.factory {
893            Some(factory) => factory.ceiling_in(agent, session, &area.id).await?,
894            None => None,
895        };
896        Ok(ceiling.map(|ceiling| ceiling.within_daily_limit(area.quotas.daily_spend_cap)))
897    }
898
899    /// Whether the kernel has an area other than `area`: the default area counts, record or
900    /// not.
901    async fn has_areas_beside(&self, area: &PartitionId) -> Result<bool> {
902        let others = self.inner.sup.partitions.list().await?;
903        Ok(area.as_str() != PartitionId::DEFAULT
904            || others.iter().any(|partition| partition.id != *area))
905    }
906
907    /// Whether the suggesting run is work the person did not start at a screen: a process
908    /// that is not interactive, or a turn a chat message started (decision 20); and the area
909    /// it runs in.
910    async fn suggesting_process(
911        &self,
912        proposer: &AgentProposer,
913    ) -> Result<(bool, Option<PartitionId>)> {
914        let Some(pid) = &proposer.run else { return Ok((false, None)) };
915        let sup = &self.inner.sup;
916        let Some(run) = sup.runs.get(pid).await? else { return Ok((false, None)) };
917        let meta = match sup.processes.get(pid).await? {
918            Some(meta) => meta,
919            None => sup.inferred_meta(&run),
920        };
921        let chat = run.input.get("channel").is_some();
922        Ok((chat || meta.kind != ProcessKind::Interactive, Some(meta.partition)))
923    }
924
925    /// The area `id` as the table checks a definition against it (spec 3.3 §5.7): its mode —
926    /// the mode its agent started in, else its record's, tightened by a mode the person set
927    /// while the kernel runs — and its quotas — the kernel's, lowered by its own and by a
928    /// daily limit the person set. The default area exists even when no record of it does.
929    ///
930    /// # Errors
931    ///
932    /// `kernel.agent.invalid` for an area the kernel does not have, or the store's error.
933    ///
934    /// # Example
935    ///
936    /// ```rust,no_run
937    /// # async fn example(kernel: adk_kernel::Kernel) -> adk_kernel::Result<()> {
938    /// let home = kernel.agents().area(&adk_kernel::PartitionId::default()).await?;
939    /// println!("agents in Home ask at most as {:?}", home.default_mode);
940    /// # Ok(())
941    /// # }
942    /// ```
943    pub async fn area(&self, id: &PartitionId) -> Result<Partition> {
944        let sup = &self.inner.sup;
945        let mut partition = match sup.partitions.get(id).await? {
946            Some(partition) => partition,
947            None if id.as_str() == PartitionId::DEFAULT => {
948                Partition::new(PartitionId::DEFAULT, PartitionId::DEFAULT)
949                    .with_mode(PartitionMode::Auto)
950            }
951            None => return Err(invalid(format!("there is no area named `{id}`"))),
952        };
953        let start = self.inner.start_modes.get(id).copied().unwrap_or(partition.default_mode);
954        partition.default_mode = sup.area_mode(id, start).await;
955        partition.quotas = sup.quotas_of(id).await;
956        Ok(partition)
957    }
958
959    /// Refuses a name another agent holds, a reserved one, or the primary agent's.
960    fn check_names(
961        &self,
962        definition: &AgentDefinition,
963        records: &[AgentRecord],
964        own: Option<&str>,
965        replaces: Option<&str>,
966    ) -> Result<()> {
967        let name = definition.display_name.trim();
968        let mut reserved = vec![RESERVED_AGENT_NAME.to_string(), self.inner.sup.app_name.clone()];
969        if let Some(factory) = &self.inner.factory {
970            reserved.extend(factory.reserved_names());
971        }
972        if reserved.iter().any(|taken| taken.trim().eq_ignore_ascii_case(name)) {
973            return Err(invalid(format!("\"{name}\" is reserved; choose another name")));
974        }
975        let lower = name.to_lowercase();
976        if let Some(record) = records.iter().find(|record| {
977            record.state.holds_its_name()
978                && Some(record.id.as_str()) != own
979                && Some(record.id.as_str()) != replaces
980                && record.display_name.trim().to_lowercase() == lower
981        }) {
982            return Err(invalid(if record.state == AgentRecordState::Proposed {
983                format!(
984                    "an agent called {name} is waiting for your answer; add or refuse that \
985                     suggestion first"
986                )
987            } else {
988                format!(
989                    "you already have an agent called {}; choose another name",
990                    record.display_name
991                )
992            }));
993        }
994        Ok(())
995    }
996
997    /// The id a new agent named `name` gets: never one any record ever had, a reserved one,
998    /// a target the host registered, or a workflow it runs (S-I14).
999    fn allocate_id(&self, name: &str, records: &[AgentRecord], reuse: Option<&str>) -> String {
1000        let inner = &self.inner;
1001        let ever: BTreeSet<&str> = records
1002            .iter()
1003            .map(|record| record.id.as_str())
1004            .filter(|id| Some(*id) != reuse)
1005            .collect();
1006        let reserved: BTreeSet<String> = inner
1007            .factory
1008            .as_ref()
1009            .map(|factory| factory.reserved_ids().into_iter().collect())
1010            .unwrap_or_default();
1011        agent_id_for(name, |id| {
1012            ever.contains(id)
1013                || ROUTE_IDS.contains(&id)
1014                || reserved.contains(id)
1015                || inner.statics.contains(id)
1016                || id == inner.sup.app_name
1017                || inner.workflows.as_ref().is_some_and(|workflows| workflows.has_workflow(id))
1018        })
1019    }
1020
1021    /// The effect classes of each driver `record` uses, from the driver store.
1022    async fn driver_classes(&self, record: &AgentRecord) -> Vec<(String, Vec<EffectClass>)> {
1023        #[cfg(feature = "drivers")]
1024        if let Some(drivers) = &self.inner.drivers {
1025            let mut classes = Vec::new();
1026            for driver in &record.uses.drivers {
1027                if let Ok(Some(stored)) = drivers.store().get(driver).await {
1028                    classes
1029                        .push((driver.clone(), stored.manifest.tools.values().copied().collect()));
1030                }
1031            }
1032            return classes;
1033        }
1034        let _ = record;
1035        Vec::new()
1036    }
1037
1038    /// The factory's assessment of `record` with the kernel's own on top: the higher risk
1039    /// wins.
1040    async fn assess(&self, record: &AgentRecord) -> AgentAssessment {
1041        let drivers = self.driver_classes(record).await;
1042        let own = kernel_assessment(&record.definition(), &record.origin, &drivers);
1043        match &self.inner.factory {
1044            Some(factory) => factory.assess(record).merge(own),
1045            None => own,
1046        }
1047    }
1048
1049    /// `definition` as the kernel keeps one a person set up by hand: normalized, its
1050    /// instructions screened and its line redacted by the host (spec 3.3 §5.7, spec 3.1 I47).
1051    async fn screened(&self, definition: AgentDefinition) -> AgentDefinition {
1052        let definition = definition.normalized();
1053        match &self.inner.factory {
1054            Some(factory) => factory.screen(definition).await.normalized(),
1055            None => definition,
1056        }
1057    }
1058
1059    async fn plan(&self, action: &AgentAction) -> Result<Plan> {
1060        let inner = &self.inner;
1061        let now = inner.sup.clock.now();
1062        let digest = action.digest();
1063        match action {
1064            AgentAction::Create { definition, replaces } => {
1065                if inner.factory.is_none() {
1066                    return Err(refused(
1067                        "this kernel builds no agents of a person's own: its host registered no \
1068                         agent factory",
1069                    ));
1070                }
1071                let definition = self.screened(definition.clone()).await;
1072                definition.validate()?;
1073                let records = inner.store.list().await?;
1074                let replaced = match replaces {
1075                    Some(id) => match records.iter().find(|record| record.id == *id) {
1076                        Some(record) if record.state == AgentRecordState::Proposed => {
1077                            Some(record.clone())
1078                        }
1079                        _ => {
1080                            return Err(invalid(format!(
1081                                "`{id}` is not a suggestion waiting for an answer"
1082                            )));
1083                        }
1084                    },
1085                    None => None,
1086                };
1087                let replaced_id = replaced.as_ref().map(|record| record.id.as_str());
1088                self.check_names(&definition, &records, None, replaced_id)?;
1089                let partition = self.area(&definition.area).await?;
1090                let over = area_limits(&definition, &partition);
1091                if !over.is_empty() {
1092                    return Err(refused(format!("it would exceed its area: {}", over.join("; "))));
1093                }
1094                let id = self.allocate_id(&definition.display_name, &records, replaced_id);
1095                let caller_unknown = SubjectRef::human("");
1096                let next = AgentRecord::new(
1097                    id.clone(),
1098                    definition.clone(),
1099                    AgentRecordState::Active,
1100                    AgentOrigin::ByHand,
1101                    caller_unknown,
1102                    now,
1103                );
1104                let assessment = self.assess(&next).await;
1105                let mut preview = AgentPreview::new(id, "create", digest, assessment);
1106                preview.widens = true;
1107                preview.now = Some(definition);
1108                Ok(Plan { preview, current: None, next: Some(next), replaces: replaced })
1109            }
1110            AgentAction::Change { id, expected_version, definition } => {
1111                let current = self.current(id, Some(*expected_version)).await?;
1112                if !current.state.is_hosted() {
1113                    return Err(invalid(format!(
1114                        "{} is {}, so it cannot be changed",
1115                        current.display_name, current.state
1116                    )));
1117                }
1118                let definition = self.screened(definition.clone()).await;
1119                if definition.area != current.area {
1120                    return Err(invalid(format!(
1121                        "an agent's area is fixed; add a new agent in `{}` instead",
1122                        definition.area
1123                    )));
1124                }
1125                definition.validate()?;
1126                let records = inner.store.list().await?;
1127                self.check_names(&definition, &records, Some(id), None)?;
1128                let partition = self.area(&current.area).await?;
1129                let over = area_limits(&definition, &partition);
1130                if !over.is_empty() {
1131                    return Err(refused(format!("it would exceed its area: {}", over.join("; "))));
1132                }
1133                let was = current.definition();
1134                let mut next = current.clone().with_definition(definition.clone());
1135                next.version = current.version + 1;
1136                next.updated_at = now;
1137                let more = widened(&was, &definition);
1138                let assessment = self.assess(&next).await;
1139                let mut preview = AgentPreview::new(id, "change", digest, assessment);
1140                if more.is_empty() {
1141                    preview.risk = ApprovalRisk::Low;
1142                }
1143                preview.widens = !more.is_empty();
1144                preview.fields = changed_fields(&was, &definition);
1145                preview.was = Some(was);
1146                preview.now = Some(definition);
1147                Ok(Plan { preview, current: Some(current), next: Some(next), replaces: None })
1148            }
1149            AgentAction::Pause { id } | AgentAction::Resume { id } => {
1150                let current = self.current(id, None).await?;
1151                let pausing = matches!(action, AgentAction::Pause { .. });
1152                let from =
1153                    if pausing { AgentRecordState::Active } else { AgentRecordState::Paused };
1154                if current.state != from {
1155                    return Err(invalid(format!(
1156                        "{} is {}, so it cannot be {}",
1157                        current.display_name,
1158                        current.state,
1159                        if pausing { "paused" } else { "resumed" }
1160                    )));
1161                }
1162                let mut next = current.clone().with_state(if pausing {
1163                    AgentRecordState::Paused
1164                } else {
1165                    AgentRecordState::Active
1166                });
1167                next.version = current.version + 1;
1168                next.updated_at = now;
1169                let assessment = AgentAssessment::new(ApprovalRisk::Low);
1170                let preview = AgentPreview::new(id, action.name(), digest, assessment);
1171                Ok(Plan { preview, current: Some(current), next: Some(next), replaces: None })
1172            }
1173            AgentAction::Remove { id, expected_version } => {
1174                let current = self.current(id, Some(*expected_version)).await?;
1175                if !matches!(
1176                    current.state,
1177                    AgentRecordState::Active
1178                        | AgentRecordState::Paused
1179                        | AgentRecordState::Removing
1180                ) {
1181                    return Err(invalid(format!(
1182                        "{} is {}, so it cannot be removed",
1183                        current.display_name, current.state
1184                    )));
1185                }
1186                let ended = self.ended_work(&current).await?;
1187                let assessment = AgentAssessment::new(ApprovalRisk::Low);
1188                let mut preview = AgentPreview::new(id, "remove", digest, assessment);
1189                preview.ended = Some(ended);
1190                Ok(Plan { preview, current: Some(current), next: None, replaces: None })
1191            }
1192        }
1193    }
1194
1195    /// The stored record `id`, at `version` when one is asked.
1196    async fn current(&self, id: &str, version: Option<u64>) -> Result<AgentRecord> {
1197        let current = self.inner.store.get(id).await?.ok_or_else(|| not_found(id))?;
1198        if let Some(version) = version
1199            && current.version != version
1200        {
1201            return Err(out_of_date(&current, version));
1202        }
1203        Ok(current)
1204    }
1205
1206    async fn create_planned(&self, caller: &AgentCaller, plan: Plan) -> Result<AgentOutcome> {
1207        let inner = &self.inner;
1208        let mut record =
1209            plan.next.expect("a create plans its record").with_changed_on(caller.surface.clone());
1210        record.created_by = caller.by.clone();
1211        record.approved_by = Some(caller.by.clone());
1212        self.record(
1213            audit::AGENT_CREATED,
1214            Some(caller),
1215            None,
1216            json!({
1217                "id": record.id,
1218                "version": record.version,
1219                "digest": record.digest,
1220                "risk": plan.preview.risk,
1221                "money": plan.preview.money,
1222                "origin": record.origin,
1223                "replaces": plan.replaces.as_ref().map(|replaced| &replaced.id),
1224            }),
1225        )
1226        .await?;
1227        // Over the suggestion it replaces when it keeps that suggestion's id.
1228        let expected = match &plan.replaces {
1229            Some(replaced) if replaced.id == record.id => replaced.version,
1230            _ => 0,
1231        };
1232        if expected > 0 {
1233            record.version = expected + 1;
1234        }
1235        if !inner.store.put_if_version(record.clone(), expected).await? {
1236            return Err(agent_error(
1237                ErrorCategory::Conflict,
1238                AGENT_OUT_OF_DATE_CODE,
1239                format!("the id `{}` was taken meanwhile; add the agent again", record.id),
1240            ));
1241        }
1242        if let Some(replaced) = &plan.replaces {
1243            self.end_suggestion(replaced, "You changed it and added it").await;
1244            if replaced.id != record.id {
1245                let _ = inner.store.delete(&replaced.id).await;
1246            }
1247        }
1248        inner.sup.publish(KernelEvent::Agent {
1249            id: record.id.clone(),
1250            change: AgentChange::Created,
1251            reason: None,
1252        });
1253        self.host(&record).await;
1254        Ok(AgentOutcome::Created { agent: record })
1255    }
1256
1257    async fn change_planned(&self, caller: &AgentCaller, plan: Plan) -> Result<AgentOutcome> {
1258        let inner = &self.inner;
1259        let current = plan.current.expect("a change plans from the stored record");
1260        let next =
1261            plan.next.expect("a change plans its record").with_changed_on(caller.surface.clone());
1262        self.record(
1263            audit::AGENT_CHANGED,
1264            Some(caller),
1265            None,
1266            json!({
1267                "id": next.id,
1268                "version": next.version,
1269                "fields": plan.preview.fields,
1270                "from": plan.preview.was,
1271                "to": plan.preview.now,
1272                "risk": plan.preview.risk,
1273                "widens": plan.preview.widens,
1274            }),
1275        )
1276        .await?;
1277        // A change that lets the agent do more ends its waiting decisions, as loosening a mode
1278        // does (spec 3.3 §5.7): those waiting when it was made, ended only once it is written,
1279        // so a change that loses to another ends nothing.
1280        let waiting = match plan.preview.widens {
1281            true => self.ended_work(&current).await?.decisions,
1282            false => Vec::new(),
1283        };
1284        if !inner.store.put_if_version(next.clone(), current.version).await? {
1285            let now = inner.store.get(&current.id).await?.ok_or_else(|| not_found(&current.id))?;
1286            return Err(out_of_date(&now, current.version));
1287        }
1288        if !waiting.is_empty() {
1289            let note = format!("{} was changed to do more", current.display_name);
1290            self.cancel_decisions(&waiting, &note).await;
1291        }
1292        inner.sup.publish(KernelEvent::Agent {
1293            id: next.id.clone(),
1294            change: AgentChange::Changed,
1295            reason: Some(plan.preview.fields.join(", ")),
1296        });
1297        self.host(&next).await;
1298        // A changed daily limit meets the unattended work the old one held at its next step,
1299        // as the area's does (spec 3.3 §5.7).
1300        if next.daily_limit_micro_usd != current.daily_limit_micro_usd {
1301            let filter = ProcessFilter::default().target(next.id.clone());
1302            inner.sup.readmit(&filter, &[crate::supervise::AGENT_LIMIT_HOLD]).await;
1303        }
1304        Ok(AgentOutcome::Changed { agent: next })
1305    }
1306
1307    async fn pause_planned(&self, caller: &AgentCaller, plan: Plan) -> Result<AgentOutcome> {
1308        let inner = &self.inner;
1309        let current = plan.current.expect("a pause plans from the stored record");
1310        let next =
1311            plan.next.expect("a pause plans its record").with_changed_on(caller.surface.clone());
1312        self.record(audit::AGENT_PAUSED, Some(caller), None, json!({ "id": next.id })).await?;
1313        if !inner.store.put_if_version(next.clone(), current.version).await? {
1314            let now = inner.store.get(&current.id).await?.ok_or_else(|| not_found(&current.id))?;
1315            return Err(out_of_date(&now, current.version));
1316        }
1317        inner.targets.set_paused(&next.id, true);
1318        inner.targets.revise(&next.id, &next.digest, next.version);
1319        self.suspend_work(&next).await;
1320        inner.sup.publish(KernelEvent::Agent {
1321            id: next.id.clone(),
1322            change: AgentChange::Paused,
1323            reason: None,
1324        });
1325        Ok(AgentOutcome::Paused { agent: next })
1326    }
1327
1328    async fn resume_planned(&self, caller: &AgentCaller, plan: Plan) -> Result<AgentOutcome> {
1329        let inner = &self.inner;
1330        let current = plan.current.expect("a resume plans from the stored record");
1331        let next =
1332            plan.next.expect("a resume plans its record").with_changed_on(caller.surface.clone());
1333        self.record(audit::AGENT_RESUMED, Some(caller), None, json!({ "id": next.id })).await?;
1334        if !inner.store.put_if_version(next.clone(), current.version).await? {
1335            let now = inner.store.get(&current.id).await?.ok_or_else(|| not_found(&current.id))?;
1336            return Err(out_of_date(&now, current.version));
1337        }
1338        inner.targets.set_paused(&next.id, false);
1339        inner.targets.revise(&next.id, &next.digest, next.version);
1340        let paused = Suspension::Paused { agent: next.id.clone() };
1341        // A queued process the pause caught before its claim runs at its claim again; a
1342        // parked one is woken, and a sleeper among them sleeps on its own wake set again.
1343        let filter = ProcessFilter::default().target(next.id.clone()).states([RunState::Queued]);
1344        for process in inner.processes.ps(filter).await.unwrap_or_default() {
1345            if process.meta.suspended_by.as_ref() == Some(&paused) && process.meta.wake.is_none() {
1346                let mut meta = process.meta;
1347                meta.suspended_by = None;
1348                meta.suspend_requested = false;
1349                inner.sup.put_meta(meta).await;
1350            }
1351        }
1352        inner.sup.wake_suspended(&paused).await;
1353        inner.sup.nudge();
1354        inner.sup.publish(KernelEvent::Agent {
1355            id: next.id.clone(),
1356            change: AgentChange::Resumed,
1357            reason: None,
1358        });
1359        Ok(AgentOutcome::Resumed { agent: next })
1360    }
1361
1362    async fn remove_planned(&self, caller: &AgentCaller, plan: Plan) -> Result<AgentOutcome> {
1363        let inner = &self.inner;
1364        let current = plan.current.expect("a removal plans from the stored record");
1365        let ended = plan.preview.ended.clone().unwrap_or_default();
1366        // Taken before the record reads `Removing`, which is when the tick would start on it.
1367        let _removing = inner.removing.lock().await;
1368        self.record(
1369            audit::AGENT_REMOVING,
1370            Some(caller),
1371            None,
1372            json!({ "id": current.id, "ended": ended }),
1373        )
1374        .await?;
1375        let removing = if current.state == AgentRecordState::Removing {
1376            current.clone()
1377        } else {
1378            let mut removing = current.clone().with_state(AgentRecordState::Removing);
1379            removing.version = current.version + 1;
1380            removing.updated_at = inner.sup.clock.now();
1381            if !inner.store.put_if_version(removing.clone(), current.version).await? {
1382                let now =
1383                    inner.store.get(&current.id).await?.ok_or_else(|| not_found(&current.id))?;
1384                return Err(out_of_date(&now, current.version));
1385            }
1386            inner.sup.publish(KernelEvent::Agent {
1387                id: removing.id.clone(),
1388                change: AgentChange::Removing,
1389                reason: None,
1390            });
1391            removing
1392        };
1393        let (tombstone, ended) = self.finish_removal(&removing, Some(caller)).await?;
1394        Ok(AgentOutcome::Removed { agent: tombstone, ended })
1395    }
1396
1397    /// Ends what the `Removing` agent `record` had, step by step, each step safe to repeat,
1398    /// then writes its tombstone (spec 3.3 §5.7, S-I16): its processes (routines and
1399    /// sleepers included) are killed, its waiting decisions cancelled, its follow-ups
1400    /// withdrawn, its rules revoked, its target retired.
1401    async fn finish_removal(
1402        &self,
1403        record: &AgentRecord,
1404        caller: Option<&AgentCaller>,
1405    ) -> Result<(AgentRecord, EndedWork)> {
1406        let inner = &self.inner;
1407        let mut ended = self.ended_work(record).await?;
1408        inner.targets.set_paused(&record.id, false);
1409        for pid in ended.work.iter().chain(&ended.routines) {
1410            if let Err(error) =
1411                inner.processes.kill(pid, &format!("{} was removed", record.display_name)).await
1412            {
1413                tracing::debug!(process.pid = %pid, error = %error, "could not kill a removed agent's process");
1414            }
1415        }
1416        let at = record.updated_at.with_timezone(&chrono::Local).format("%H:%M");
1417        let note = format!("You removed {} at {at}", record.display_name);
1418        self.cancel_decisions(&ended.decisions, &note).await;
1419        let by = caller.map_or_else(|| SubjectRef::service("kernel"), |caller| caller.by.clone());
1420        for item in &ended.follow_ups {
1421            if let Err(error) = inner.agenda.reject(item, &by, Some(&note)).await {
1422                tracing::debug!(agenda.item = %item, error = %error, "could not withdraw a removed agent's follow-up");
1423            }
1424        }
1425        if let Some(factory) = &inner.factory {
1426            ended.rules = factory.retired(record).await?;
1427        }
1428        if let Some(retired) = inner.targets.retire(&record.id) {
1429            retired.close_when_idle();
1430        }
1431        inner.local.lock().unwrap_or_else(|e| e.into_inner()).cant_start.remove(&record.id);
1432        let mut tombstone = record.clone().with_state(AgentRecordState::Removed);
1433        tombstone.version = record.version + 1;
1434        tombstone.updated_at = inner.sup.clock.now();
1435        self.record(audit::AGENT_REMOVED, caller, None, json!({ "id": record.id, "ended": ended }))
1436            .await?;
1437        if !inner.store.put_if_version(tombstone.clone(), record.version).await? {
1438            // Another replica finished it first.
1439            let now = inner.store.get(&record.id).await?.ok_or_else(|| not_found(&record.id))?;
1440            return Ok((now, ended));
1441        }
1442        inner.sup.publish(KernelEvent::Agent {
1443            id: record.id.clone(),
1444            change: AgentChange::Removed,
1445            reason: None,
1446        });
1447        Ok((tombstone, ended))
1448    }
1449
1450    /// What removing `record` ends now: its unfinished processes, split into work and
1451    /// routines, the decisions its runs wait on, and its open follow-ups.
1452    async fn ended_work(&self, record: &AgentRecord) -> Result<EndedWork> {
1453        let inner = &self.inner;
1454        let processes =
1455            inner.processes.ps(ProcessFilter::default().target(record.id.clone())).await?;
1456        let pids: BTreeSet<String> =
1457            processes.iter().map(|process| process.run.run_id.clone()).collect();
1458        let mut ended = EndedWork::default();
1459        let mut sessions = BTreeSet::new();
1460        for process in &processes {
1461            sessions.insert((
1462                process.run.app_name.clone(),
1463                process.run.user_id.clone(),
1464                crate::supervise::run_session(&process.run),
1465            ));
1466            if process.run.state.is_terminal() {
1467                continue;
1468            }
1469            let routine =
1470                process.meta.kind == ProcessKind::Scheduled || process.meta.wake.is_some();
1471            if routine {
1472                ended.routines.push(process.run.run_id.clone());
1473            } else {
1474                ended.work.push(process.run.run_id.clone());
1475            }
1476        }
1477        if let Some(approvals) = &inner.approvals {
1478            let agent = record.agent_id(&inner.sup.app_name);
1479            let mut decisions = BTreeSet::new();
1480            for (app, user, session) in sessions {
1481                let query =
1482                    InboxQuery::for_approver(SubjectRef::human(user.clone()), [OPERATOR_GROUP])
1483                        .with_app_name(app)
1484                        .with_user_id(user)
1485                        .with_session_id(session)
1486                        .with_limit(500);
1487                for request in approvals.inbox(query).await?.items {
1488                    let acting =
1489                        request.acting.as_ref().is_some_and(|acting| acting.agent.id == agent);
1490                    let run = request.run_id.as_ref().is_some_and(|run| pids.contains(run));
1491                    // A follow-up's own request ends with the follow-up, counted once.
1492                    let follow_up = request.tool_name == crate::agenda::AGENDA_TOOL_NAME;
1493                    if request.state == ApprovalState::Pending && (acting || run) && !follow_up {
1494                        decisions.insert(request.id);
1495                    }
1496                }
1497            }
1498            ended.decisions = decisions.into_iter().collect();
1499        }
1500        for item in inner.agenda.list(&AgendaFilter::default().open()).await? {
1501            if item.proposer().is_some_and(|pid| pids.contains(pid))
1502                && matches!(
1503                    item.state,
1504                    crate::agenda::AgendaState::Proposed | crate::agenda::AgendaState::Approved
1505                )
1506            {
1507                ended.follow_ups.push(item.id);
1508            }
1509        }
1510        Ok(ended)
1511    }
1512
1513    /// Cancels the waiting decisions `ids` with `note`, so each shows "Ended without an
1514    /// answer", never a yes or a no.
1515    async fn cancel_decisions(&self, ids: &[String], note: &str) {
1516        let Some(approvals) = &self.inner.approvals else { return };
1517        for id in ids {
1518            if let Err(error) = approvals.cancel(id, Some(note.to_string())).await {
1519                tracing::debug!(approval.id = %id, error = %error, "could not end a decision");
1520            }
1521        }
1522    }
1523
1524    /// Marks the unfinished processes of `record` paused: a running one stops at its next
1525    /// step, a queued or sleeping one is held until the agent is resumed.
1526    async fn suspend_work(&self, record: &AgentRecord) {
1527        let inner = &self.inner;
1528        let processes = match inner
1529            .processes
1530            .ps(ProcessFilter::default().target(record.id.clone()))
1531            .await
1532        {
1533            Ok(processes) => processes,
1534            Err(error) => {
1535                tracing::warn!(agent.id = %record.id, error = %error, "could not list a paused agent's processes");
1536                return;
1537            }
1538        };
1539        let paused = Suspension::Paused { agent: record.id.clone() };
1540        for process in processes.iter().filter(|process| !process.run.state.is_terminal()) {
1541            if let Err(error) =
1542                inner.processes.suspend_as(&process.run.run_id, paused.clone()).await
1543            {
1544                tracing::debug!(process.pid = %process.run.run_id, error = %error, "could not suspend a paused agent's process");
1545            }
1546        }
1547    }
1548
1549    /// Ends the inbox request of the suggestion `record` with `note`.
1550    async fn end_suggestion(&self, record: &AgentRecord, note: &str) {
1551        let Some(approvals) = &self.inner.approvals else { return };
1552        let id = suggestion_request_id(record);
1553        if let Ok(Some(request)) = approvals.get(&id).await
1554            && request.state == ApprovalState::Pending
1555            && let Err(error) = approvals.cancel(&id, Some(note.to_string())).await
1556        {
1557            tracing::debug!(approval.id = %id, error = %error, "could not end a suggestion");
1558        }
1559    }
1560
1561    /// Builds and hosts `record` when it is active or paused and this replica does not host
1562    /// its version yet (spec 3.3 §5.7): the factory builds it, the kernel refuses a runner
1563    /// whose kill switch is not its own (S-I15) or whose root agent is not the record's id,
1564    /// attaches its progress source and the ledger, and swaps it in. A build error keeps the
1565    /// record and shows "Can't start".
1566    async fn host(&self, record: &AgentRecord) {
1567        let inner = &self.inner;
1568        if !record.state.is_hosted() {
1569            return;
1570        }
1571        inner.targets.expect(&record.id);
1572        let hosted = inner.targets.hosted(&record.id);
1573        // A read older than what is hosted — a tick's list taken before a change or a pause
1574        // — never puts the older definition or state back.
1575        if hosted.as_ref().is_some_and(|hosted| hosted.version > record.version) {
1576            return;
1577        }
1578        inner.targets.set_paused(&record.id, record.state == AgentRecordState::Paused);
1579        if let Some(hosted) = &hosted {
1580            // Pausing and resuming change the record's state, not what the agent is: the
1581            // build stays.
1582            if hosted.version == record.version
1583                || inner.targets.revise(&record.id, &record.digest, record.version)
1584            {
1585                return;
1586            }
1587        }
1588        let failed = inner
1589            .local
1590            .lock()
1591            .unwrap_or_else(|e| e.into_inner())
1592            .cant_start
1593            .get(&record.id)
1594            .is_some_and(|(version, _)| *version == record.version);
1595        if failed {
1596            return;
1597        }
1598        match self.build(record).await {
1599            Ok(()) => {
1600                inner.local.lock().unwrap_or_else(|e| e.into_inner()).cant_start.remove(&record.id);
1601                inner.sup.publish(KernelEvent::Agent {
1602                    id: record.id.clone(),
1603                    change: AgentChange::Hosted,
1604                    reason: None,
1605                });
1606            }
1607            Err(reason) => {
1608                tracing::warn!(agent.id = %record.id, reason = %reason, "an added agent cannot start");
1609                inner
1610                    .local
1611                    .lock()
1612                    .unwrap_or_else(|e| e.into_inner())
1613                    .cant_start
1614                    .insert(record.id.clone(), (record.version, reason.clone()));
1615                inner.sup.publish(KernelEvent::Agent {
1616                    id: record.id.clone(),
1617                    change: AgentChange::CantStart,
1618                    reason: Some(reason),
1619                });
1620            }
1621        }
1622    }
1623
1624    async fn build(&self, record: &AgentRecord) -> std::result::Result<(), String> {
1625        let inner = &self.inner;
1626        if inner.statics.contains(&record.id) || record.validate().is_err() {
1627            return Err(format!("`{}` is not an id an added agent may have", record.id));
1628        }
1629        let Some(factory) = &inner.factory else {
1630            return Err("this kernel builds no agents of a person's own".to_string());
1631        };
1632        let hosted = factory.build(record).await.map_err(|error| AdkError::from(error).message)?;
1633        if !hosted.runner.governance().same_as(&inner.sup.governance) {
1634            return Err(
1635                "its kill switch is not the kernel's, so Stop all would not reach it (spec 3.3 \
1636                 S-I15)"
1637                    .to_string(),
1638            );
1639        }
1640        if hosted.runner.root_agent_name() != record.id {
1641            return Err(format!(
1642                "its root agent is `{}`, not `{}`, so it would act as another agent",
1643                hosted.runner.root_agent_name(),
1644                record.id
1645            ));
1646        }
1647        if let Some(progress) = &hosted.progress {
1648            progress.attach(ProcessHandle::new(&inner.sup));
1649            #[cfg(feature = "proc")]
1650            if let Some(ledger) = &inner.ledger {
1651                progress.attach_ledger(Arc::new(ledger.clone()));
1652            }
1653        }
1654        let added = Added {
1655            area: record.area.clone(),
1656            progress: hosted.progress,
1657            version: record.version,
1658            digest: record.digest.clone(),
1659            daily_limit: record.daily_limit_micro_usd,
1660            runner: hosted.runner,
1661            close: hosted.close,
1662        };
1663        // What the new build replaced — or the new build itself, when a later version was
1664        // hosted meanwhile — is closed once its runs finish.
1665        if let Some(unserved) = inner.targets.host(&record.id, added) {
1666            unserved.close_when_idle();
1667        }
1668        Ok(())
1669    }
1670
1671    /// Closes every agent this replica hosts: the kernel is stopping (spec 3.3 §5.7).
1672    pub(crate) async fn close_hosted(&self) {
1673        for added in self.inner.targets.drain() {
1674            added.close().await;
1675        }
1676    }
1677
1678    /// Reconciles this replica's hosted agents with the store (spec 3.3 §5.7): builds and
1679    /// hosts active and paused agents not hosted at their version, retires the rest, and
1680    /// finishes interrupted removals.
1681    ///
1682    /// # Errors
1683    ///
1684    /// Returns the store's error.
1685    pub(crate) async fn reconcile(&self) -> Result<()> {
1686        let inner = &self.inner;
1687        let records = inner.store.list().await?;
1688        for record in &records {
1689            match record.state {
1690                AgentRecordState::Active | AgentRecordState::Paused => self.host(record).await,
1691                AgentRecordState::Removing => {
1692                    // A removal finishing here already is left to it; the next tick retries.
1693                    let Ok(_removing) = inner.removing.try_lock() else { continue };
1694                    // The list may be older than a removal that finished since.
1695                    let Ok(Some(now)) = inner.store.get(&record.id).await else { continue };
1696                    if now.state != AgentRecordState::Removing || now.version != record.version {
1697                        continue;
1698                    }
1699                    // The removal's own record names the person; the tick that finishes it
1700                    // names itself (spec 3.3 S-I16, S-I18).
1701                    let tick = AgentCaller::new(SubjectRef::service("kernel"), "kernel", "tick");
1702                    if let Err(error) = self.finish_removal(record, Some(&tick)).await {
1703                        tracing::warn!(agent.id = %record.id, error = %error, "could not finish removing an agent; the next tick retries");
1704                    }
1705                }
1706                AgentRecordState::Proposed => self.settle(record, None).await,
1707                AgentRecordState::Removed | AgentRecordState::Refused => {}
1708            }
1709        }
1710        // Read again: a suggestion settled above is live now.
1711        let live: BTreeSet<String> = inner
1712            .store
1713            .list()
1714            .await?
1715            .into_iter()
1716            .filter(|record| record.state.is_hosted())
1717            .map(|record| record.id)
1718            .collect();
1719        for id in inner.targets.hosted_ids() {
1720            if !live.contains(&id)
1721                && let Some(retired) = inner.targets.retire(&id)
1722            {
1723                retired.close_when_idle();
1724            }
1725        }
1726        Ok(())
1727    }
1728
1729    /// One scheduler tick (spec 3.3 §5.7): applies the inbox's answers to suggestions and
1730    /// reconciles hosting with the store.
1731    pub(crate) async fn tick(&self) {
1732        if let Err(error) = self.reconcile().await {
1733            tracing::debug!(error = %error, "agent table tick failed");
1734        }
1735    }
1736
1737    /// Applies a person's answer to the suggestion whose inbox request is `request_id` now,
1738    /// as `caller` gave it, rather than on the next tick, so the agent's
1739    /// `kernel.agent.created` names the surface, device and presence it was approved with
1740    /// (spec 3.3 §11). Does nothing for a request that is not a waiting suggestion's.
1741    ///
1742    /// # Example
1743    ///
1744    /// ```rust,no_run
1745    /// use adk_core::principal::SubjectRef;
1746    /// use adk_kernel::agents::AgentCaller;
1747    ///
1748    /// # async fn example(kernel: adk_kernel::Kernel) {
1749    /// let phone = AgentCaller::new(SubjectRef::human("alice"), "phone", "touch");
1750    /// kernel.agents().answered("agent-finance-0123456789ab", &phone).await;
1751    /// # }
1752    /// ```
1753    pub async fn answered(&self, request_id: &str, caller: &AgentCaller) {
1754        let Some(id) = request_id
1755            .strip_prefix("agent-")
1756            .and_then(|rest| rest.rsplit_once('-'))
1757            .map(|(id, _)| id)
1758        else {
1759            return;
1760        };
1761        match self.inner.store.get(id).await {
1762            Ok(Some(record))
1763                if record.state == AgentRecordState::Proposed
1764                    && suggestion_request_id(&record) == request_id =>
1765            {
1766                self.settle(&record, Some(caller)).await;
1767            }
1768            Ok(_) => {}
1769            Err(error) => {
1770                tracing::debug!(agent.id = %id, error = %error, "could not read an answered suggestion; the tick applies it");
1771            }
1772        }
1773    }
1774
1775    /// Applies the inbox's answer to the suggestion `record`: a person's approval of the
1776    /// same definition, still within the suggester's and the area's limits, adds the agent,
1777    /// as `caller` when the answer came through a surface; any other approval is logged and
1778    /// ignored; a rejection deletes the suggestion, whose id was never used. A suggestion
1779    /// whose request was never written ends refused once it is old enough.
1780    async fn settle(&self, record: &AgentRecord, caller: Option<&AgentCaller>) {
1781        let inner = &self.inner;
1782        if !inner.local.lock().unwrap_or_else(|e| e.into_inner()).settling.insert(record.id.clone())
1783        {
1784            return;
1785        }
1786        self.settle_once(record, caller).await;
1787        inner.local.lock().unwrap_or_else(|e| e.into_inner()).settling.remove(&record.id);
1788    }
1789
1790    async fn settle_once(&self, record: &AgentRecord, caller: Option<&AgentCaller>) {
1791        let inner = &self.inner;
1792        let Some(approvals) = &inner.approvals else { return };
1793        // The tick's list may be older than an answer applied since.
1794        match inner.store.get(&record.id).await {
1795            Ok(Some(now))
1796                if now.state == AgentRecordState::Proposed && now.version == record.version => {}
1797            _ => return,
1798        }
1799        let request_id = suggestion_request_id(record);
1800        let request = match approvals.get(&request_id).await {
1801            Ok(Some(request)) => request,
1802            Ok(None) => {
1803                if inner.sup.clock.now() - record.created_at > SUGGESTION_GRACE {
1804                    let reason = "its decision was never written".to_string();
1805                    let fields = json!({ "id": record.id, "reason": reason });
1806                    if self.record(audit::AGENT_REFUSED, None, None, fields).await.is_ok()
1807                        && matches!(inner.store.delete(&record.id).await, Ok(true))
1808                    {
1809                        inner.sup.publish(KernelEvent::Agent {
1810                            id: record.id.clone(),
1811                            change: AgentChange::Refused,
1812                            reason: Some(reason),
1813                        });
1814                    }
1815                }
1816                return;
1817            }
1818            Err(error) => {
1819                tracing::debug!(approval.id = %request_id, error = %error, "could not read a suggestion's request");
1820                return;
1821            }
1822        };
1823        match request.state {
1824            ApprovalState::Pending => {}
1825            ApprovalState::Approved => {
1826                let approver = request.decisions.last().map(|decision| decision.approver.clone());
1827                match approver {
1828                    Some(approver) if approver.kind == SubjectKind::Human => {
1829                        if let Err(error) = self.approve(record, &request, approver, caller).await {
1830                            tracing::warn!(agent.id = %record.id, error = %error, "could not add an approved agent; the next tick retries");
1831                        }
1832                    }
1833                    other => {
1834                        let first = inner
1835                            .local
1836                            .lock()
1837                            .unwrap_or_else(|e| e.into_inner())
1838                            .ignored
1839                            .insert(request_id.clone());
1840                        if first {
1841                            tracing::warn!(agent.id = %record.id, approver = ?other, "a suggested agent's approval by someone other than a person was ignored (spec 3.3 S-I11)");
1842                            let fields = json!({
1843                                "id": record.id,
1844                                "reason": "an approver who is not a person",
1845                                "approver": other,
1846                            });
1847                            let _ = self.record(audit::AGENT_REFUSED, None, None, fields).await;
1848                        }
1849                    }
1850                }
1851            }
1852            ApprovalState::Rejected
1853            | ApprovalState::Responded
1854            | ApprovalState::Cancelled
1855            | ApprovalState::Expired => {
1856                let reason = request
1857                    .note
1858                    .clone()
1859                    .or_else(|| request.decisions.last().and_then(|d| d.reason.clone()))
1860                    .unwrap_or_else(|| "not added".to_string());
1861                let fields = json!({ "id": record.id, "reason": reason, "approvalId": request.id });
1862                if self.record(audit::AGENT_REFUSED, None, None, fields).await.is_ok()
1863                    && matches!(inner.store.delete(&record.id).await, Ok(true))
1864                {
1865                    inner.sup.publish(KernelEvent::Agent {
1866                        id: record.id.clone(),
1867                        change: AgentChange::Refused,
1868                        reason: Some(reason),
1869                    });
1870                }
1871            }
1872        }
1873    }
1874
1875    /// Adds the approved suggestion `record`, or ends it refused; `caller` is how the
1876    /// approver answered, when the answer came through a surface.
1877    async fn approve(
1878        &self,
1879        record: &AgentRecord,
1880        request: &ApprovalRequest,
1881        approver: SubjectRef,
1882        caller: Option<&AgentCaller>,
1883    ) -> Result<()> {
1884        let inner = &self.inner;
1885        let approved: Option<AgentDefinition> =
1886            serde_json::from_value(request.args_redacted.clone()).ok();
1887        let mut refusal = match approved {
1888            Some(definition) if definition.digest() == record.digest => None,
1889            _ => Some("the approved definition is not the one suggested".to_string()),
1890        };
1891        if refusal.is_none()
1892            && let AgentOrigin::Suggested { agent, session, .. } = &record.origin
1893        {
1894            let definition = record.definition();
1895            refusal = match self.over_suggester(&definition, agent, session).await? {
1896                None => Some(format!("{agent} may no longer suggest agents")),
1897                Some(over) => (!over.is_empty()).then(|| {
1898                    format!("the agent that suggested it can no longer give it {}", over.join(", "))
1899                }),
1900            };
1901            if refusal.is_none() {
1902                let over = area_limits(&definition, &self.area(&record.area).await?);
1903                if !over.is_empty() {
1904                    refusal = Some(format!("it would exceed its area: {}", over.join("; ")));
1905                }
1906            }
1907        }
1908        let now = inner.sup.clock.now();
1909        if let Some(reason) = refusal {
1910            self.record(
1911                audit::AGENT_REFUSED,
1912                None,
1913                None,
1914                json!({ "id": record.id, "reason": reason, "approvalId": request.id }),
1915            )
1916            .await?;
1917            let mut refused_record = record.clone().with_state(AgentRecordState::Refused);
1918            refused_record.version = record.version + 1;
1919            refused_record.updated_at = now;
1920            if inner.store.put_if_version(refused_record, record.version).await? {
1921                let text = format!("{} wasn't added: {reason}.", record.display_name);
1922                self.notify_session(record, &request.scope, &text).await;
1923                inner.sup.publish(KernelEvent::Agent {
1924                    id: record.id.clone(),
1925                    change: AgentChange::Refused,
1926                    reason: Some(reason),
1927                });
1928            }
1929            return Ok(());
1930        }
1931        let assessment = self.assess(record).await;
1932        // Where the person approved it, when the answer came through a surface; the inbox
1933        // when the tick found the answer.
1934        let actor = match caller {
1935            Some(caller) if caller.by == approver => caller.clone(),
1936            _ => AgentCaller::new(approver.clone(), "inbox", "approval"),
1937        };
1938        let mut active = record
1939            .clone()
1940            .with_state(AgentRecordState::Active)
1941            .with_approved_by(approver)
1942            .with_changed_on(actor.surface.clone());
1943        active.version = record.version + 1;
1944        active.updated_at = now;
1945        self.record(
1946            audit::AGENT_CREATED,
1947            Some(&actor),
1948            None,
1949            json!({
1950                "id": active.id,
1951                "version": active.version,
1952                "digest": active.digest,
1953                "risk": assessment.risk,
1954                "money": assessment.money,
1955                "origin": active.origin,
1956                "approvalId": request.id,
1957            }),
1958        )
1959        .await?;
1960        if !inner.store.put_if_version(active.clone(), record.version).await? {
1961            // Another replica added it first.
1962            return Ok(());
1963        }
1964        inner.sup.publish(KernelEvent::Agent {
1965            id: active.id.clone(),
1966            change: AgentChange::Created,
1967            reason: None,
1968        });
1969        self.host(&active).await;
1970        Ok(())
1971    }
1972
1973    /// Writes `text` as a system notice in the session the suggestion was made in.
1974    async fn notify_session(&self, record: &AgentRecord, scope: &ApprovalScope, text: &str) {
1975        let Some(sessions) = &self.inner.sup.sessions else { return };
1976        let identity = match (
1977            adk_core::AppName::try_from(scope.app_name.as_str()),
1978            adk_core::UserId::try_from(scope.user_id.as_str()),
1979            adk_core::SessionId::try_from(scope.session_id.as_str()),
1980        ) {
1981            (Ok(app), Ok(user), Ok(session)) => adk_core::AdkIdentity::new(app, user, session),
1982            _ => return,
1983        };
1984        let event =
1985            adk_core::history::system_notice_event(format!("kernel-agent-{}", record.id), text);
1986        if let Err(error) = sessions
1987            .append_event_for_identity(adk_session::AppendEventRequest { identity, event })
1988            .await
1989        {
1990            tracing::debug!(agent.id = %record.id, error = %error, "could not tell the suggesting session");
1991        }
1992    }
1993
1994    /// Writes a `kernel.agent.*` record before the change it records (S-I18, K-I16).
1995    ///
1996    /// # Errors
1997    ///
1998    /// The trail's error under `AuditFailureMode::Block`; the change is then refused.
1999    async fn record(
2000        &self,
2001        action: &str,
2002        caller: Option<&AgentCaller>,
2003        agent: Option<&AgentId>,
2004        fields: Value,
2005    ) -> Result<()> {
2006        let sup = &self.inner.sup;
2007        let Some(trail) = &sup.audit else { return Ok(()) };
2008        let mut actor = match caller {
2009            Some(caller) => AuditActor::subject(caller.by.clone()),
2010            None => AuditActor::default(),
2011        };
2012        actor.agent = agent.cloned();
2013        actor.instance = Some(sup.kernel_id.clone());
2014        let mut draft = AuditRecordDraft::new(
2015            AuditRecordKind::Other(audit::KERNEL_AUDIT_KIND.to_string()),
2016            action,
2017        )
2018        .actor(actor);
2019        if let Value::Object(fields) = fields {
2020            for (key, value) in fields {
2021                draft = draft.ext(key, value);
2022            }
2023        }
2024        if let Some(caller) = caller {
2025            draft = draft
2026                .ext("by", json!(caller.by))
2027                .ext("surface", json!(caller.surface))
2028                .ext("how", json!(caller.how))
2029                .ext("device", json!(caller.device))
2030                .ext("presence", json!(caller.presence))
2031                .ext("transport", json!(caller.transport))
2032                .ext("peerPid", json!(caller.peer_pid));
2033        }
2034        trail.record(draft).await.map_err(KernelError::Core)
2035    }
2036
2037    /// Records a refused change; a failed record is logged, the refusal stands anyway.
2038    async fn record_refused(
2039        &self,
2040        caller: Option<&AgentCaller>,
2041        id: Option<&str>,
2042        name: Option<&str>,
2043        reason: &str,
2044    ) {
2045        let fields = json!({ "id": id, "name": name, "reason": reason });
2046        if let Err(error) = self.record(audit::AGENT_REFUSED, caller, None, fields).await {
2047            tracing::warn!(error = %error, "could not record a refused agent change");
2048        }
2049    }
2050}
2051
2052fn definition_name(action: &AgentAction) -> Option<&str> {
2053    match action {
2054        AgentAction::Create { definition, .. } | AgentAction::Change { definition, .. } => {
2055            Some(definition.display_name.as_str())
2056        }
2057        _ => None,
2058    }
2059}
2060
2061/// The refusal of a change made against `asked` when `current` is newer.
2062fn out_of_date(current: &AgentRecord, asked: u64) -> KernelError {
2063    let at = current.updated_at.with_timezone(&chrono::Local).format("%H:%M");
2064    agent_error(
2065        ErrorCategory::Conflict,
2066        AGENT_OUT_OF_DATE_CODE,
2067        format!(
2068            "{} was changed at {at} (version {}); this change was made against version \
2069             {asked}, so look at it again first",
2070            current.display_name, current.version
2071        ),
2072    )
2073}