1use adk_core::ApprovalRequest;
21use adk_kernel::PartitionMode;
22use adk_kernel::agents::{
23 AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, AgentUses, AvatarColor,
24 FileAccess, ModelChoice, ShellAccess, WebAccess,
25};
26use chrono::{DateTime, FixedOffset, Utc};
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29
30use crate::model::{AgentRef, Avatar, Mode, ModeView};
31use crate::project::CALL_TEXT_LIMIT;
32use crate::rules::Risk;
33
34const PALETTE: [&str; 8] =
36 ["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];
37
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
40#[serde(rename_all = "camelCase")]
41pub enum AgentColor {
42 #[default]
44 Orange,
45 Green,
47 Blue,
49 Violet,
51 Slate,
53 Amber,
55 Teal,
57 Pink,
59}
60
61impl AgentColor {
62 pub fn hex(self) -> &'static str {
70 PALETTE[AvatarColor::from(self).index()]
71 }
72
73 pub fn label(self) -> &'static str {
75 match self {
76 Self::Orange => "Orange",
77 Self::Green => "Green",
78 Self::Blue => "Blue",
79 Self::Violet => "Violet",
80 Self::Slate => "Slate",
81 Self::Amber => "Amber",
82 Self::Teal => "Teal",
83 Self::Pink => "Pink",
84 }
85 }
86}
87
88impl From<AgentColor> for AvatarColor {
89 fn from(color: AgentColor) -> Self {
90 match color {
91 AgentColor::Orange => Self::Orange,
92 AgentColor::Green => Self::Green,
93 AgentColor::Blue => Self::Blue,
94 AgentColor::Violet => Self::Violet,
95 AgentColor::Slate => Self::Slate,
96 AgentColor::Amber => Self::Amber,
97 AgentColor::Teal => Self::Teal,
98 AgentColor::Pink => Self::Pink,
99 }
100 }
101}
102
103impl From<AvatarColor> for AgentColor {
104 fn from(color: AvatarColor) -> Self {
105 match color {
106 AvatarColor::Green => Self::Green,
107 AvatarColor::Blue => Self::Blue,
108 AvatarColor::Violet => Self::Violet,
109 AvatarColor::Slate => Self::Slate,
110 AvatarColor::Amber => Self::Amber,
111 AvatarColor::Teal => Self::Teal,
112 AvatarColor::Pink => Self::Pink,
113 _ => Self::Orange,
114 }
115 }
116}
117
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
120#[serde(rename_all = "camelCase")]
121pub enum FileUse {
122 #[default]
124 None,
125 Read,
127 ReadWrite,
129}
130
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
133#[serde(rename_all = "camelCase")]
134pub enum ShellUse {
135 #[default]
137 None,
138 Sandboxed,
140 Host,
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
146#[serde(tag = "access", rename_all = "camelCase")]
147pub enum WebUse {
148 #[default]
150 None,
151 #[serde(rename_all = "camelCase")]
153 Listed {
154 hosts: Vec<String>,
156 },
157 Any,
159}
160
161#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
163#[serde(rename_all = "camelCase")]
164pub struct UsesDraft {
165 #[serde(default)]
167 pub files: FileUse,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub folder: Option<String>,
171 #[serde(default)]
173 pub shell: ShellUse,
174 #[serde(default)]
176 pub web: WebUse,
177 #[serde(default)]
179 pub packs: Vec<String>,
180 #[serde(default)]
182 pub drivers: Vec<String>,
183}
184
185#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "camelCase")]
188pub struct ModelView {
189 pub provider: String,
191 pub model: String,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "camelCase")]
210pub struct AgentDraft {
211 pub display_name: String,
213 #[serde(default)]
215 pub color: AgentColor,
216 #[serde(default)]
218 pub description: String,
219 #[serde(default)]
221 pub instructions: String,
222 pub area: String,
224 pub mode: Mode,
226 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub model: Option<ModelView>,
229 #[serde(default)]
231 pub uses: UsesDraft,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub daily_limit_micro_usd: Option<u64>,
235}
236
237fn mode_of(mode: PartitionMode) -> Mode {
238 match mode {
239 PartitionMode::ReadOnly => Mode::JustLook,
240 PartitionMode::Plan => Mode::Suggest,
241 PartitionMode::Auto => Mode::GoAhead,
242 _ => Mode::AskFirst,
243 }
244}
245
246fn partition_mode(mode: Mode) -> PartitionMode {
247 match mode {
248 Mode::JustLook => PartitionMode::ReadOnly,
249 Mode::Suggest => PartitionMode::Plan,
250 Mode::AskFirst => PartitionMode::Ask,
251 Mode::GoAhead => PartitionMode::Auto,
252 }
253}
254
255impl AgentDraft {
256 pub fn new(display_name: impl Into<String>, area: impl Into<String>) -> Self {
259 let display_name = display_name.into();
260 Self {
261 color: AvatarColor::for_name(&display_name).into(),
262 display_name,
263 description: String::new(),
264 instructions: String::new(),
265 area: area.into(),
266 mode: Mode::AskFirst,
267 model: None,
268 uses: UsesDraft::default(),
269 daily_limit_micro_usd: None,
270 }
271 }
272
273 #[must_use]
275 pub fn with_mode(mut self, mode: Mode) -> Self {
276 self.mode = mode;
277 self
278 }
279
280 #[must_use]
282 pub fn with_uses(mut self, uses: UsesDraft) -> Self {
283 self.uses = uses;
284 self
285 }
286
287 pub fn into_definition(self) -> AgentDefinition {
289 let mut uses = AgentUses::default()
290 .with_files(match self.uses.files {
291 FileUse::None => FileAccess::None,
292 FileUse::Read => FileAccess::Read,
293 FileUse::ReadWrite => FileAccess::ReadWrite,
294 })
295 .with_shell(match self.uses.shell {
296 ShellUse::None => ShellAccess::None,
297 ShellUse::Sandboxed => ShellAccess::Sandboxed,
298 ShellUse::Host => ShellAccess::Host,
299 })
300 .with_web(match self.uses.web {
301 WebUse::None => WebAccess::None,
302 WebUse::Listed { hosts } => WebAccess::Listed { hosts },
303 WebUse::Any => WebAccess::Any,
304 });
305 if let Some(folder) = self.uses.folder.filter(|folder| !folder.trim().is_empty()) {
306 uses = uses.with_folder(folder);
307 }
308 for pack in self.uses.packs {
309 uses = uses.with_pack(pack);
310 }
311 for driver in self.uses.drivers {
312 uses = uses.with_driver(driver);
313 }
314 let mut definition = AgentDefinition::new(self.display_name, self.area.as_str())
315 .with_color(self.color.into())
316 .with_description(self.description)
317 .with_instructions(self.instructions)
318 .with_mode(partition_mode(self.mode))
319 .with_uses(uses);
320 if let Some(model) = self.model {
321 definition = definition.with_model(ModelChoice::new(model.provider, model.model));
322 }
323 if let Some(limit) = self.daily_limit_micro_usd {
324 definition = definition.with_daily_limit(limit);
325 }
326 definition
327 }
328
329 pub fn from_definition(definition: &AgentDefinition) -> Self {
331 let uses = &definition.uses;
332 Self {
333 display_name: definition.display_name.clone(),
334 color: definition.color.into(),
335 description: definition.description.clone(),
336 instructions: definition.instructions.clone(),
337 area: definition.area.as_str().to_string(),
338 mode: mode_of(definition.mode),
339 model: definition.model.as_ref().map(|model| ModelView {
340 provider: model.provider.clone(),
341 model: model.model.clone(),
342 }),
343 uses: UsesDraft {
344 files: match uses.files {
345 FileAccess::None => FileUse::None,
346 FileAccess::Read => FileUse::Read,
347 FileAccess::ReadWrite => FileUse::ReadWrite,
348 },
349 folder: uses.folder.clone(),
350 shell: match uses.shell {
351 ShellAccess::None => ShellUse::None,
352 ShellAccess::Sandboxed => ShellUse::Sandboxed,
353 ShellAccess::Host => ShellUse::Host,
354 },
355 web: match &uses.web {
356 WebAccess::None => WebUse::None,
357 WebAccess::Listed { hosts } => WebUse::Listed { hosts: hosts.clone() },
358 WebAccess::Any => WebUse::Any,
359 },
360 packs: uses.packs.clone(),
361 drivers: uses.drivers.clone(),
362 },
363 daily_limit_micro_usd: definition.daily_limit_micro_usd,
364 }
365 }
366}
367
368#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
370#[serde(rename_all = "camelCase")]
371pub enum AgentLife {
372 Suggested,
374 Active,
376 Paused,
378 Removing,
380 Removed,
382 Refused,
384}
385
386impl From<AgentRecordState> for AgentLife {
387 fn from(state: AgentRecordState) -> Self {
388 match state {
389 AgentRecordState::Proposed => Self::Suggested,
390 AgentRecordState::Paused => Self::Paused,
391 AgentRecordState::Removing => Self::Removing,
392 AgentRecordState::Removed => Self::Removed,
393 AgentRecordState::Refused => Self::Refused,
394 _ => Self::Active,
395 }
396 }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
401#[serde(rename_all = "camelCase")]
402pub struct AgentDetail {
403 pub id: String,
405 pub agent: AgentRef,
407 pub draft: AgentDraft,
409 pub version: u64,
411 pub state: AgentLife,
413 pub origin_text: String,
415 pub mode: ModeView,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub cant_start: Option<String>,
420 pub changed_at: DateTime<Utc>,
422 #[serde(default, skip_serializing_if = "Option::is_none")]
425 pub changed_on: Option<String>,
426 #[serde(default, skip_serializing_if = "Vec::is_empty")]
430 pub granted: Vec<GrantedUse>,
431}
432
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
447#[serde(rename_all = "camelCase")]
448pub struct GrantedUse {
449 pub id: String,
451 pub text: String,
454 #[serde(default, skip_serializing_if = "Vec::is_empty")]
457 pub modes: Vec<Mode>,
458}
459
460impl GrantedUse {
461 pub fn new(id: impl Into<String>, text: impl Into<String>) -> Self {
463 Self { id: id.into(), text: text.into(), modes: Vec::new() }
464 }
465
466 #[must_use]
480 pub fn only_in(mut self, modes: impl IntoIterator<Item = Mode>) -> Self {
481 self.modes = modes.into_iter().collect();
482 self
483 }
484
485 pub fn holds_in(&self, mode: Mode) -> bool {
487 self.modes.is_empty() || self.modes.contains(&mode)
488 }
489}
490
491#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(rename_all = "camelCase")]
495pub struct RemovedAgent {
496 pub agent: AgentRef,
498 pub removed_text: String,
500 pub threads: Vec<RemovedThread>,
502}
503
504#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
506#[serde(rename_all = "camelCase")]
507pub struct RemovedThread {
508 pub session_id: String,
510 pub at: DateTime<Utc>,
512 pub when: String,
514}
515
516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
519#[serde(rename_all = "camelCase")]
520pub struct ThreadSummary {
521 pub session_id: String,
523 pub at: DateTime<Utc>,
525 pub when: String,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
531#[serde(rename_all = "camelCase")]
532pub struct AgentThreads {
533 pub agent: String,
535 pub threads: Vec<ThreadSummary>,
537}
538
539#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
541#[serde(rename_all = "camelCase")]
542pub struct EndedWork {
543 pub work: u32,
545 pub routines: u32,
547 pub decisions: u32,
549 pub follow_ups: u32,
551 pub rules: u32,
553 pub text: String,
556}
557
558impl EndedWork {
559 pub fn of(ended: &adk_kernel::agents::EndedWork, name: &str) -> Self {
576 let count = |items: &[String]| u32::try_from(items.len()).unwrap_or(u32::MAX);
577 let mut out = Self {
578 work: count(&ended.work),
579 routines: count(&ended.routines),
580 decisions: count(&ended.decisions),
581 follow_ups: count(&ended.follow_ups),
582 rules: u32::try_from(ended.rules).unwrap_or(u32::MAX),
583 text: String::new(),
584 };
585 out.text = words::removing_ends(name, &out);
586 out
587 }
588}
589
590#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
593#[serde(rename_all = "camelCase")]
594pub struct AgentPreview {
595 pub id: String,
597 pub action: String,
599 pub heading: String,
601 pub abilities: Vec<String>,
603 pub risk: Risk,
605 pub risk_text: String,
607 pub money: bool,
609 pub widens: bool,
612 pub needs_presence: bool,
614 #[serde(default, skip_serializing_if = "Vec::is_empty")]
616 pub fields: Vec<String>,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
619 pub was: Option<AgentDraft>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
622 pub now: Option<AgentDraft>,
623 #[serde(default, skip_serializing_if = "Option::is_none")]
625 pub ended: Option<EndedWork>,
626 pub digest: String,
628 pub code: String,
630}
631
632impl AgentPreview {
633 pub fn of(preview: &adk_kernel::agents::AgentPreview, name: &str) -> Self {
635 let risk = Risk::from(preview.risk);
636 Self {
637 id: preview.id.clone(),
638 action: preview.action.clone(),
639 heading: words::here_is_what_can_do(name),
640 abilities: preview.abilities.clone(),
641 risk,
642 risk_text: risk.words().to_string(),
643 money: preview.money,
644 widens: preview.widens,
645 needs_presence: preview.needs_presence(),
646 fields: preview.fields.clone(),
647 was: preview.was.as_ref().map(AgentDraft::from_definition),
648 now: preview.now.as_ref().map(AgentDraft::from_definition),
649 ended: preview.ended.as_ref().map(|ended| EndedWork::of(ended, name)),
650 digest: preview.digest.clone(),
651 code: preview.code().to_string(),
652 }
653 }
654}
655
656#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
658#[serde(tag = "action", rename_all = "camelCase")]
659pub enum AgentPreviewRequest {
660 #[serde(rename_all = "camelCase")]
662 Create {
663 draft: AgentDraft,
665 #[serde(default, skip_serializing_if = "Option::is_none")]
667 replaces: Option<String>,
668 },
669 #[serde(rename_all = "camelCase")]
671 Change {
672 agent: String,
674 version: u64,
676 draft: AgentDraft,
678 },
679 #[serde(rename_all = "camelCase")]
681 Remove {
682 agent: String,
684 version: u64,
686 },
687}
688
689impl AgentPreviewRequest {
690 pub fn into_action(self) -> adk_kernel::agents::AgentAction {
692 match self {
693 Self::Create { draft, replaces } => adk_kernel::agents::AgentAction::Create {
694 definition: draft.into_definition(),
695 replaces,
696 },
697 Self::Change { agent, version, draft } => adk_kernel::agents::AgentAction::Change {
698 id: agent,
699 expected_version: version,
700 definition: draft.into_definition(),
701 },
702 Self::Remove { agent, version } => {
703 adk_kernel::agents::AgentAction::Remove { id: agent, expected_version: version }
704 }
705 }
706 }
707}
708
709#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
711#[serde(rename_all = "camelCase")]
712pub struct AreaChoice {
713 pub id: String,
715 pub name: String,
717 pub mode: ModeView,
719 #[serde(default)]
721 pub drivers: Vec<String>,
722}
723
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
726#[serde(rename_all = "camelCase")]
727pub struct ColorChoice {
728 pub color: AgentColor,
730 pub label: String,
732 pub hex: String,
734}
735
736#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
739#[serde(rename_all = "camelCase")]
740pub struct AgentChoices {
741 pub models: Vec<ModelView>,
743 pub packs: Vec<String>,
745 pub areas: Vec<AreaChoice>,
747 pub colors: Vec<ColorChoice>,
749}
750
751impl AgentChoices {
752 pub fn of(choices: &adk_kernel::agents::AgentChoices, areas: Vec<AreaChoice>) -> Self {
754 Self {
755 models: choices
756 .models
757 .iter()
758 .map(|model| ModelView {
759 provider: model.provider.clone(),
760 model: model.model.clone(),
761 })
762 .collect(),
763 packs: choices.packs.clone(),
764 areas,
765 colors: AvatarColor::ALL
766 .iter()
767 .map(|color| {
768 let color = AgentColor::from(*color);
769 ColorChoice {
770 color,
771 label: color.label().to_string(),
772 hex: color.hex().to_string(),
773 }
774 })
775 .collect(),
776 }
777 }
778}
779
780#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
782#[serde(rename_all = "camelCase")]
783pub struct CardLine {
784 pub label: String,
786 pub value: String,
788 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
790 pub mono: bool,
791}
792
793#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
797#[serde(rename_all = "camelCase")]
798pub struct AgentCardView {
799 pub id: String,
801 pub agent: AgentRef,
803 pub description: String,
805 pub lines: Vec<CardLine>,
808 pub instructions: String,
810 pub instructions_truncated: bool,
812 pub abilities: Vec<String>,
814 #[serde(default, skip_serializing_if = "Option::is_none")]
816 pub compared: Option<String>,
817 pub allowed_without_asking: String,
819 pub draft: AgentDraft,
821}
822
823pub(crate) fn avatar_of(display_name: &str, color: AgentColor) -> Avatar {
825 let monogram: String = display_name
826 .chars()
827 .find(|c| c.is_alphanumeric())
828 .map(|c| c.to_uppercase().collect())
829 .unwrap_or_default();
830 Avatar { monogram, color: color.hex().to_string() }
831}
832
833pub(crate) fn agent_ref(record: &AgentRecord) -> AgentRef {
835 AgentRef {
836 name: record.id.clone(),
837 display_name: record.display_name.clone(),
838 avatar: avatar_of(&record.display_name, record.color.into()),
839 }
840}
841
842pub(crate) fn mode_view(mode: PartitionMode) -> ModeView {
844 crate::project::mode_view(adk_harness::HarnessMode::from(mode))
845}
846
847fn day(at: DateTime<Utc>, offset: FixedOffset) -> String {
849 at.with_timezone(&offset).format("%-d %b").to_string()
850}
851
852impl AgentDetail {
853 pub fn of(
856 record: &AgentRecord,
857 cant_start: Option<String>,
858 user: &str,
859 primary: &str,
860 offset: FixedOffset,
861 ) -> Self {
862 let you = |subject: &adk_core::principal::SubjectRef| {
863 if subject.id == user { "you".to_string() } else { subject.id.clone() }
864 };
865 let added_by = record.approved_by.as_ref().unwrap_or(&record.created_by);
866 let on = day(record.created_at, offset);
867 let origin_text = match &record.origin {
868 AgentOrigin::ByHand => format!("Added by {} on {on}", you(&record.created_by)),
869 AgentOrigin::Suggested { .. } => {
870 format!(
871 "{}, added by {} on {on}",
872 words::suggested_agent_by(primary),
873 you(added_by)
874 )
875 }
876 };
877 Self {
878 id: record.id.clone(),
879 agent: agent_ref(record),
880 draft: AgentDraft::from_definition(&record.definition()),
881 version: record.version,
882 state: record.state.into(),
883 origin_text,
884 mode: mode_view(record.mode),
885 cant_start,
886 changed_at: record.updated_at,
887 changed_on: record.changed_on.clone(),
888 granted: Vec::new(),
889 }
890 }
891}
892
893impl RemovedAgent {
894 pub(crate) fn of(
897 detail: &AgentDetail,
898 threads: Vec<(String, DateTime<Utc>)>,
899 offset: FixedOffset,
900 ) -> Self {
901 let mut threads: Vec<RemovedThread> = threads
902 .into_iter()
903 .map(|(session_id, at)| RemovedThread {
904 session_id,
905 at,
906 when: at.with_timezone(&offset).format("%-d %b %H:%M").to_string(),
907 })
908 .collect();
909 threads.sort_by_key(|thread| std::cmp::Reverse(thread.at));
910 Self {
911 agent: detail.agent.clone(),
912 removed_text: words::removed_on(&day(detail.changed_at, offset)),
913 threads,
914 }
915 }
916}
917
918fn uses_lines(uses: &AgentUses) -> Vec<CardLine> {
920 let line =
921 |label: &str, value: String| CardLine { label: label.to_string(), value, mono: false };
922 let place = uses.folder.clone().unwrap_or_else(|| "the workspace".to_string());
923 let mut lines = vec![
924 line(
925 "Files",
926 match uses.files {
927 FileAccess::None => "No files".to_string(),
928 FileAccess::Read => format!("Reads files in {place}"),
929 FileAccess::ReadWrite => format!("Reads and changes files in {place}"),
930 },
931 ),
932 line(
933 "Shell",
934 match uses.shell {
935 ShellAccess::None => "No shell",
936 ShellAccess::Sandboxed => "In the sandbox",
937 ShellAccess::Host => "On this computer",
938 }
939 .to_string(),
940 ),
941 line(
942 "Web",
943 match &uses.web {
944 WebAccess::None => "No web".to_string(),
945 WebAccess::Listed { hosts } => format!("Listed sites only: {}", hosts.join(", ")),
946 WebAccess::Any => "Any site".to_string(),
947 },
948 ),
949 ];
950 if !uses.packs.is_empty() {
951 lines.push(line("Packs", uses.packs.join(", ")));
952 }
953 if !uses.drivers.is_empty() {
954 lines.push(line("Drivers", uses.drivers.join(", ")));
955 }
956 lines
957}
958
959fn lacks(uses: &AgentUses) -> Vec<&'static str> {
961 let mut lacks = Vec::new();
962 if uses.files == FileAccess::None {
963 lacks.push("files");
964 }
965 if uses.shell == ShellAccess::None {
966 lacks.push("shell");
967 }
968 if uses.web == WebAccess::None {
969 lacks.push("web");
970 }
971 lacks
972}
973
974impl AgentCardView {
975 pub fn of_request(request: &ApprovalRequest, suggester: &str, area: &str) -> Option<Self> {
979 let definition: AgentDefinition =
980 serde_json::from_value(request.args_redacted.clone()).ok()?;
981 let record = AgentRecord::new(
982 String::new(),
983 definition.clone(),
984 AgentRecordState::Proposed,
985 AgentOrigin::ByHand,
986 request
987 .requester
988 .clone()
989 .unwrap_or_else(|| adk_core::principal::SubjectRef::human(&request.scope.user_id)),
990 request.created_at,
991 );
992 let assessment = adk_harness::assess_agent(&record);
993 let mut lines = vec![
994 CardLine { label: "Area".into(), value: area.to_string(), mono: false },
995 CardLine {
996 label: "How much it asks first".into(),
997 value: mode_view(definition.mode).status,
998 mono: false,
999 },
1000 ];
1001 lines.push(match &definition.model {
1002 Some(model) => {
1003 CardLine { label: "Runs on".into(), value: model.model.clone(), mono: true }
1004 }
1005 None => CardLine {
1006 label: "Runs on".into(),
1007 value: format!("{suggester}'s model"),
1008 mono: false,
1009 },
1010 });
1011 lines.extend(uses_lines(&definition.uses));
1012 if let Some(limit) = definition.daily_limit_micro_usd {
1013 lines.push(CardLine {
1014 label: "Daily spending limit".into(),
1015 value: crate::words::dollars(limit),
1016 mono: false,
1017 });
1018 }
1019 let truncated = definition.instructions.chars().count() > CALL_TEXT_LIMIT;
1020 let instructions = if truncated {
1021 definition.instructions.chars().take(CALL_TEXT_LIMIT).collect::<String>() + "…"
1022 } else {
1023 definition.instructions.clone()
1024 };
1025 let compared = Some(words::no_more_than(suggester, &lacks(&definition.uses)));
1029 let id = request
1031 .id
1032 .strip_prefix("agent-")
1033 .and_then(|rest| rest.rsplit_once('-'))
1034 .map(|(id, _)| id.to_string())
1035 .unwrap_or_default();
1036 Some(Self {
1037 agent: AgentRef {
1038 name: id.clone(),
1039 display_name: definition.display_name.clone(),
1040 avatar: avatar_of(&definition.display_name, definition.color.into()),
1041 },
1042 description: definition.description.clone(),
1043 lines,
1044 instructions,
1045 instructions_truncated: truncated,
1046 abilities: assessment.abilities,
1047 compared,
1048 allowed_without_asking: words::NOTHING_YET.to_string(),
1049 draft: AgentDraft::from_definition(&definition),
1050 id,
1051 })
1052 }
1053}
1054
1055pub(crate) fn area_name(area: &str) -> String {
1057 if area == adk_kernel::PartitionId::DEFAULT {
1058 return "Home".to_string();
1059 }
1060 let mut chars = area.chars();
1061 match chars.next() {
1062 Some(first) => first.to_uppercase().chain(chars).collect(),
1063 None => String::new(),
1064 }
1065}
1066
1067pub(crate) fn agent_caller(caller: &crate::origin::Caller) -> adk_kernel::agents::AgentCaller {
1072 use crate::origin::SurfaceKind;
1073 let surface = serde_json::to_value(caller.surface)
1074 .ok()
1075 .and_then(|value| value.as_str().map(str::to_string))
1076 .unwrap_or_default();
1077 let mut agent =
1078 adk_kernel::agents::AgentCaller::new(caller.subject.clone(), surface, caller.origin.kind());
1079 match caller.surface {
1080 SurfaceKind::Web | SurfaceKind::Phone | SurfaceKind::Tray => {
1081 agent = agent.with_transport(adk_kernel::control::ControlTransport::Http);
1082 }
1083 SurfaceKind::Terminal | SurfaceKind::Chat | SurfaceKind::Voice => {}
1084 }
1085 if let Some(device) = &caller.device {
1086 agent = agent.with_device(device.clone());
1087 }
1088 if caller.presence_confirmed {
1089 agent = agent.with_presence(adk_kernel::agents::Presence::Confirmed);
1090 } else if caller.paired_local {
1091 agent = agent.with_presence(adk_kernel::agents::Presence::PairedLocal);
1092 }
1093 agent
1094}
1095
1096pub(crate) mod local {
1099 use adk_kernel::agents::{AgentAction, AgentRecordState, Agents};
1100 use chrono::FixedOffset;
1101
1102 use super::{
1103 AgentChoices, AgentDetail, AgentPreview, AgentPreviewRequest, AreaChoice, EndedWork,
1104 agent_caller, area_name, mode_view,
1105 };
1106 use crate::error::{Result, SurfaceError};
1107 use crate::origin::Caller;
1108
1109 pub(crate) async fn definitions(
1111 agents: &Agents,
1112 user: &str,
1113 primary: &str,
1114 offset: FixedOffset,
1115 ) -> Result<Vec<AgentDetail>> {
1116 Ok(agents
1117 .list()
1118 .await?
1119 .into_iter()
1120 .map(|view| AgentDetail::of(&view.agent, view.cant_start, user, primary, offset))
1121 .collect())
1122 }
1123
1124 pub(crate) async fn agent(
1126 agents: &Agents,
1127 id: &str,
1128 user: &str,
1129 primary: &str,
1130 offset: FixedOffset,
1131 ) -> Result<AgentDetail> {
1132 agents
1133 .get(id)
1134 .await?
1135 .filter(|view| {
1136 !matches!(view.agent.state, AgentRecordState::Removed | AgentRecordState::Refused)
1137 })
1138 .map(|view| AgentDetail::of(&view.agent, view.cant_start, user, primary, offset))
1139 .ok_or_else(|| SurfaceError::not_found(format!("agent '{id}'")))
1140 }
1141
1142 pub(crate) async fn choices(
1144 agents: &Agents,
1145 partitions: &adk_kernel::Partitions,
1146 ) -> Result<AgentChoices> {
1147 let choices = agents.choices().await?;
1148 let mut areas: Vec<AreaChoice> = partitions
1149 .store()
1150 .list()
1151 .await?
1152 .into_iter()
1153 .map(|area| AreaChoice {
1154 name: area_name(area.id.as_str()),
1155 id: area.id.as_str().to_string(),
1156 mode: mode_view(area.default_mode),
1157 drivers: area.drivers.clone(),
1158 })
1159 .collect();
1160 if areas.is_empty() {
1161 areas.push(AreaChoice {
1162 id: adk_kernel::PartitionId::DEFAULT.to_string(),
1163 name: area_name(adk_kernel::PartitionId::DEFAULT),
1164 mode: mode_view(adk_kernel::PartitionMode::Ask),
1165 drivers: Vec::new(),
1166 });
1167 }
1168 Ok(AgentChoices::of(&choices, areas))
1169 }
1170
1171 pub(crate) async fn preview(
1173 agents: &Agents,
1174 caller: &Caller,
1175 request: AgentPreviewRequest,
1176 ) -> Result<AgentPreview> {
1177 let action = request.into_action();
1178 let name = name_of(agents, &action).await;
1179 let preview = agents.preview(&agent_caller(caller), &action).await?;
1180 Ok(AgentPreview::of(&preview, &name))
1181 }
1182
1183 async fn name_of(agents: &Agents, action: &AgentAction) -> String {
1185 match action {
1186 AgentAction::Create { definition, .. } | AgentAction::Change { definition, .. } => {
1187 definition.display_name.clone()
1188 }
1189 other => match other.id() {
1190 Some(id) => agents
1191 .get(id)
1192 .await
1193 .ok()
1194 .flatten()
1195 .map(|view| view.agent.display_name)
1196 .unwrap_or_else(|| id.to_string()),
1197 None => String::new(),
1198 },
1199 }
1200 }
1201
1202 pub(crate) enum Applied {
1204 Agent(Box<AgentDetail>),
1205 Removed(EndedWork),
1206 }
1207
1208 pub(crate) async fn apply(
1210 agents: &Agents,
1211 caller: &Caller,
1212 action: AgentAction,
1213 digest: &str,
1214 primary: &str,
1215 offset: FixedOffset,
1216 ) -> Result<Applied> {
1217 let name = name_of(agents, &action).await;
1218 let outcome = agents.apply(&agent_caller(caller), action, digest).await?;
1219 let user = caller.user_id();
1220 Ok(match outcome {
1221 adk_kernel::agents::AgentOutcome::Removed { ended, .. } => {
1222 Applied::Removed(EndedWork::of(&ended, &name))
1223 }
1224 adk_kernel::agents::AgentOutcome::Created { agent }
1225 | adk_kernel::agents::AgentOutcome::Changed { agent }
1226 | adk_kernel::agents::AgentOutcome::Paused { agent }
1227 | adk_kernel::agents::AgentOutcome::Resumed { agent } => {
1228 Applied::Agent(Box::new(AgentDetail::of(&agent, None, user, primary, offset)))
1229 }
1230 other => {
1231 return Err(SurfaceError::Invalid(format!("the kernel answered {other:?}")));
1232 }
1233 })
1234 }
1235
1236 pub(crate) fn out_of_date(error: &SurfaceError) -> bool {
1238 error.code() == adk_kernel::error::AGENT_OUT_OF_DATE_CODE
1239 }
1240}
1241
1242pub(crate) fn roster(
1247 rows: Vec<crate::model::AgentRow>,
1248 definitions: &[AgentDetail],
1249 can_change: bool,
1250) -> Vec<crate::model::AgentRow> {
1251 use crate::model::{AgentRow, AgentStatus};
1252 let (mut primary, mut added): (Vec<AgentRow>, Vec<AgentRow>) = rows
1253 .into_iter()
1254 .partition(|row| !definitions.iter().any(|detail| detail.id == row.agent.name));
1255 for detail in definitions {
1256 if !matches!(detail.state, AgentLife::Active | AgentLife::Paused) {
1257 continue;
1258 }
1259 let status = if detail.state == AgentLife::Paused {
1262 Some((AgentStatus::Paused, words::PAUSED))
1263 } else if detail.cant_start.is_some() {
1264 Some((AgentStatus::CantStart, words::CANT_START))
1265 } else {
1266 None
1267 };
1268 let area = Some(area_name(&detail.draft.area));
1269 match added.iter_mut().find(|row| row.agent.name == detail.id) {
1270 Some(row) => {
1271 row.agent = detail.agent.clone();
1272 if let Some((status, text)) = status {
1273 row.status = status;
1274 row.status_text = text.to_string();
1275 row.wake_at = None;
1276 }
1277 row.area = area;
1278 row.mode = Some(detail.mode.clone());
1279 row.added = true;
1280 row.can_change = can_change;
1281 }
1282 None => {
1283 let (status, text) = status.unwrap_or((AgentStatus::Ready, words::READY));
1284 added.push(AgentRow {
1285 agent: detail.agent.clone(),
1286 status,
1287 status_text: text.to_string(),
1288 wake_at: None,
1289 session_id: None,
1290 area,
1291 mode: Some(detail.mode.clone()),
1292 added: true,
1293 can_change,
1294 shell: None,
1295 });
1296 }
1297 }
1298 }
1299 added.sort_by(|a, b| {
1302 (!a.added, &a.area, a.agent.display_name.to_lowercase()).cmp(&(
1303 !b.added,
1304 &b.area,
1305 b.agent.display_name.to_lowercase(),
1306 ))
1307 });
1308 primary.extend(added.into_iter().filter(|row| row.added));
1309 primary
1310}
1311
1312pub(crate) fn suggestion_steps(
1316 events: &[adk_core::Event],
1317 suggester: &str,
1318 suggested_at: DateTime<Utc>,
1319 hh_mm: impl Fn(DateTime<Utc>) -> String,
1320) -> Vec<String> {
1321 let before: Vec<&adk_core::Event> =
1322 events.iter().filter(|event| event.timestamp <= suggested_at).collect();
1323 let asked = before.iter().rposition(|event| event.author == "user");
1324 let mut steps = Vec::new();
1325 if let Some(at) = asked {
1326 steps.push(format!("You asked at {}", hh_mm(before[at].timestamp)));
1327 }
1328 let turn = &before[asked.map_or(0, |at| at + 1)..];
1329 let mut files: Vec<String> = Vec::new();
1330 let mut sites: Vec<String> = Vec::new();
1331 for event in turn {
1332 let Some(content) = &event.llm_response.content else { continue };
1333 for part in &content.parts {
1334 let adk_core::Part::FunctionCall { name, args, .. } = part else { continue };
1335 match name.as_str() {
1336 "read_file" | "grep" | "glob" | "list_dir" => {
1337 if let Some(path) = args.get("path").and_then(serde_json::Value::as_str) {
1338 let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
1339 if !files.contains(&file) {
1340 files.push(file);
1341 }
1342 }
1343 }
1344 "web_fetch" => {
1345 let host = args
1346 .get("url")
1347 .and_then(serde_json::Value::as_str)
1348 .and_then(|url| url.split("://").nth(1))
1349 .and_then(|rest| rest.split(['/', '?', '#', ':']).next())
1350 .map(str::to_string);
1351 if let Some(host) = host.filter(|host| !sites.contains(host)) {
1352 sites.push(host);
1353 }
1354 }
1355 _ => {}
1356 }
1357 }
1358 }
1359 match files.len() {
1360 0 => {}
1361 1 => steps.push(format!("{suggester} read {}", files[0])),
1362 n => steps.push(format!("{suggester} read {n} files")),
1363 }
1364 if !sites.is_empty() {
1365 steps.push(format!("{suggester} read {}", sites.join(", ")));
1366 }
1367 steps.push(format!("{suggester} suggested this agent"));
1368 steps
1369}
1370
1371pub(crate) use crate::words;
1373
1374#[cfg(test)]
1375mod tests {
1376 use adk_core::principal::SubjectRef;
1377
1378 use super::words::*;
1379 use super::*;
1380
1381 #[test]
1382 fn a_draft_round_trips_through_the_kernels_definition() {
1383 let draft = AgentDraft {
1384 display_name: "Finance".into(),
1385 color: AgentColor::Teal,
1386 description: "Reads invoices".into(),
1387 instructions: "Draft reminders.".into(),
1388 area: "home".into(),
1389 mode: Mode::Suggest,
1390 model: Some(ModelView {
1391 provider: "anthropic".into(),
1392 model: "claude-sonnet-5-5".into(),
1393 }),
1394 uses: UsesDraft {
1395 files: FileUse::Read,
1396 folder: Some("Invoices".into()),
1397 shell: ShellUse::Sandboxed,
1398 web: WebUse::Listed { hosts: vec!["bank.example".into()] },
1399 packs: vec!["browser".into()],
1400 drivers: vec!["calendar".into()],
1401 },
1402 daily_limit_micro_usd: Some(2_000_000),
1403 };
1404 let definition = draft.clone().into_definition();
1405 assert!(definition.validate().is_ok());
1406 assert_eq!(AgentDraft::from_definition(&definition), draft);
1407 let wire = serde_json::to_value(&draft).unwrap();
1408 assert_eq!(
1409 wire["uses"]["web"],
1410 serde_json::json!({ "access": "listed", "hosts": ["bank.example"] })
1411 );
1412 assert_eq!(wire["color"], "teal");
1413 }
1414
1415 #[test]
1416 fn the_roster_puts_the_primary_first_and_the_persons_agents_by_name() {
1417 use crate::model::{AgentRow, AgentStatus};
1418 let detail = |id: &str, name: &str, state: AgentRecordState| {
1419 let record = AgentRecord::new(
1420 id,
1421 AgentDefinition::new(name, "default"),
1422 state,
1423 AgentOrigin::ByHand,
1424 SubjectRef::human("ana"),
1425 chrono::Utc::now(),
1426 );
1427 AgentDetail::of(&record, None, "ana", "ADK-Rust", FixedOffset::east_opt(0).unwrap())
1428 };
1429 let row = |name: &str| AgentRow {
1430 agent: AgentRef {
1431 name: name.into(),
1432 display_name: name.into(),
1433 avatar: avatar_of(name, AgentColor::Slate),
1434 },
1435 status: AgentStatus::Working,
1436 status_text: "Working".into(),
1437 wake_at: None,
1438 session_id: Some(format!("s-{name}")),
1439 area: None,
1440 mode: None,
1441 added: false,
1442 can_change: false,
1443 shell: None,
1444 };
1445 let definitions = [
1446 detail("zeta", "Zeta", AgentRecordState::Active),
1447 detail("bills", "Bills", AgentRecordState::Paused),
1448 detail("waiting", "Waiting", AgentRecordState::Proposed),
1449 ];
1450 let rows = roster(vec![row("zeta"), row("adk-rust")], &definitions, true);
1451 let names: Vec<(&str, AgentStatus)> =
1452 rows.iter().map(|row| (row.agent.display_name.as_str(), row.status)).collect();
1453 assert_eq!(
1454 names,
1455 [
1456 ("adk-rust", AgentStatus::Working),
1457 ("Bills", AgentStatus::Paused),
1458 ("Zeta", AgentStatus::Working)
1459 ]
1460 );
1461 assert!(rows[1].added && rows[1].can_change && !rows[0].added);
1462 assert_eq!(rows[2].session_id.as_deref(), Some("s-zeta"));
1463 }
1464
1465 #[test]
1468 fn paused_wins_over_cant_start_and_agents_sit_under_their_area() {
1469 let detail = |id: &str, name: &str, area: &str, state: AgentRecordState| {
1470 let record = AgentRecord::new(
1471 id,
1472 AgentDefinition::new(name, area),
1473 state,
1474 AgentOrigin::ByHand,
1475 SubjectRef::human("ana"),
1476 chrono::Utc::now(),
1477 );
1478 AgentDetail::of(
1479 &record,
1480 Some("No key for OpenAI".into()),
1481 "ana",
1482 "ADK-Rust",
1483 FixedOffset::east_opt(0).unwrap(),
1484 )
1485 };
1486 let definitions = [
1487 detail("builder", "Builder", "work", AgentRecordState::Active),
1488 detail("bills", "Bills", "home", AgentRecordState::Paused),
1489 detail("archive", "Archive", "work", AgentRecordState::Active),
1490 ];
1491 let rows = roster(Vec::new(), &definitions, true);
1492 let shown: Vec<(&str, Option<&str>, AgentStatus)> = rows
1493 .iter()
1494 .map(|row| (row.agent.display_name.as_str(), row.area.as_deref(), row.status))
1495 .collect();
1496 use crate::model::AgentStatus;
1497 assert_eq!(
1498 shown,
1499 [
1500 ("Bills", Some("Home"), AgentStatus::Paused),
1501 ("Archive", Some("Work"), AgentStatus::CantStart),
1502 ("Builder", Some("Work"), AgentStatus::CantStart),
1503 ]
1504 );
1505 }
1506
1507 #[test]
1508 fn colours_follow_the_palette() {
1509 for (index, color) in AvatarColor::ALL.iter().enumerate() {
1510 assert_eq!(AgentColor::from(*color).hex(), PALETTE[index]);
1511 assert_eq!(AvatarColor::from(AgentColor::from(*color)), *color);
1512 }
1513 }
1514
1515 #[test]
1516 fn removing_names_what_ends() {
1517 let ended = |work, decisions, routines| EndedWork {
1518 work,
1519 decisions,
1520 routines,
1521 ..EndedWork::default()
1522 };
1523 assert_eq!(
1524 removing_ends("Finance", &ended(1, 2, 1)),
1525 "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1 routine. Its threads stay."
1526 );
1527 assert_eq!(
1528 removing_ends("Bills", &ended(0, 1, 1)),
1529 "Removing Bills ends 1 decision waiting for you and 1 routine. Its threads stay."
1530 );
1531 assert_eq!(
1532 removing_ends("Bills", &ended(0, 0, 0)),
1533 "Removing Bills ends nothing that is running. Its threads stay."
1534 );
1535 }
1536
1537 #[test]
1538 fn the_detail_says_how_the_agent_was_added() {
1539 let record = AgentRecord::new(
1540 "finance",
1541 AgentDefinition::new("Finance", "default"),
1542 AgentRecordState::Active,
1543 AgentOrigin::Suggested {
1544 agent: adk_core::AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
1545 session: "s1".into(),
1546 run: None,
1547 unattended: false,
1548 },
1549 SubjectRef::agent(&adk_core::AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap()),
1550 "2026-10-25T09:12:00Z".parse().unwrap(),
1551 )
1552 .with_approved_by(SubjectRef::human("ana"));
1553 let detail =
1554 AgentDetail::of(&record, None, "ana", "ADK-Rust", FixedOffset::east_opt(0).unwrap());
1555 assert_eq!(detail.origin_text, "Suggested by ADK-Rust, added by you on 25 Oct");
1556 assert_eq!(detail.state, AgentLife::Active);
1557 assert_eq!(detail.agent.avatar.color, AgentColor::from(record.color).hex());
1558 }
1559
1560 #[test]
1561 fn the_card_shows_the_definition_in_full_from_the_inbox_entry() {
1562 let definition = AgentDefinition::new("Finance", "default")
1563 .with_mode(PartitionMode::Ask)
1564 .with_instructions("Read invoices.\nDraft reminders.")
1565 .with_uses(AgentUses::default().with_files(FileAccess::Read).with_folder("Invoices"));
1566 let call = adk_core::ToolConfirmationRequest::new(
1567 "kernel:agent.create",
1568 serde_json::to_value(&definition).unwrap(),
1569 );
1570 let request = adk_core::ApprovalRequest::new(
1571 "agent-finance-0123",
1572 adk_core::ApprovalScope::new("adk-rust", "ana", "s1"),
1573 &call,
1574 adk_core::ApprovalPolicy::new([adk_core::ApproverSelector::human("ana")]),
1575 );
1576 let card = AgentCardView::of_request(&request, "ADK-Rust", "Home").unwrap();
1577 let line =
1578 |label: &str| card.lines.iter().find(|line| line.label == label).unwrap().value.clone();
1579 assert_eq!(line("Area"), "Home");
1580 assert_eq!(line("How much it asks first"), "Asks first");
1581 assert_eq!(line("Files"), "Reads files in Invoices");
1582 assert_eq!(line("Shell"), "No shell");
1583 assert_eq!(
1586 card.compared.as_deref(),
1587 Some("It can do no more than ADK-Rust, and has no shell or web.")
1588 );
1589 assert_eq!(card.allowed_without_asking, NOTHING_YET);
1590 assert!(!card.instructions_truncated);
1591 }
1592}