1use 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
41const OPERATOR_GROUP: &str = "operator";
44
45pub const MAX_OPEN_SUGGESTIONS: usize = 3;
47
48const WEB_SURFACE: &str = "web";
50
51const ROUTE_IDS: [&str; 1] = ["new"];
54
55const 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
83pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "camelCase")]
124#[non_exhaustive]
125pub struct AgentProposer {
126 pub agent: AgentId,
128 pub user: String,
130 pub session: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub run: Option<String>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub ceiling: Option<AgentCeiling>,
140}
141
142impl AgentProposer {
143 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 #[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 #[must_use]
157 pub fn with_ceiling(mut self, ceiling: AgentCeiling) -> Self {
158 self.ceiling = Some(ceiling);
159 self
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166#[non_exhaustive]
167pub struct AgentProposal {
168 pub agent: AgentRecord,
170 pub request_id: String,
172 pub risk: ApprovalRisk,
174 pub merged: bool,
176}
177
178#[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 Created {
185 agent: AgentRecord,
187 },
188 Changed {
190 agent: AgentRecord,
192 },
193 Paused {
195 agent: AgentRecord,
197 },
198 Resumed {
200 agent: AgentRecord,
202 },
203 Removed {
205 agent: AgentRecord,
207 ended: EndedWork,
209 },
210}
211
212#[derive(Default)]
214struct Local {
215 cant_start: BTreeMap<String, (u64, String)>,
217 ignored: BTreeSet<String>,
219 settling: BTreeSet<String>,
221}
222
223pub(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 pub(crate) statics: BTreeSet<String>,
234 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 removing: tokio::sync::Mutex<()>,
263}
264
265#[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#[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 pub fn new() -> Self {
339 Self::default()
340 }
341
342 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
353struct 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 pub fn store(&self) -> &Arc<dyn AgentStore> {
387 &self.inner.store
388 }
389
390 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 "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 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 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 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 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 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 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 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 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 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 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 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 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 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(¤t.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(¤t).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 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(¤t, 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 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 let waiting = match plan.preview.widens {
1281 true => self.ended_work(¤t).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(¤t.id).await?.ok_or_else(|| not_found(¤t.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, ¬e).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 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(¤t.id).await?.ok_or_else(|| not_found(¤t.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(¤t.id).await?.ok_or_else(|| not_found(¤t.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 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 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(¤t.id).await?.ok_or_else(|| not_found(¤t.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 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, ¬e).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(¬e)).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 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 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 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 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 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 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 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 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 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 if let Some(unserved) = inner.targets.host(&record.id, added) {
1666 unserved.close_when_idle();
1667 }
1668 Ok(())
1669 }
1670
1671 pub(crate) async fn close_hosted(&self) {
1673 for added in self.inner.targets.drain() {
1674 added.close().await;
1675 }
1676 }
1677
1678 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 let Ok(_removing) = inner.removing.try_lock() else { continue };
1694 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 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 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 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 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 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 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 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 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 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 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 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 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
2061fn 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}