Skip to main content

adk_surface/
agents.rs

1//! Agents a person adds, as every surface shows and changes them (spec 3.3 §5.7).
2//!
3//! The kernel keeps each agent in its store and changes it only through its audited agent
4//! table (`adk_kernel::agents`); this module is the wire between that table and the surfaces:
5//!
6//! | Type | What a surface does with it |
7//! |---|---|
8//! | [`AgentDraft`] | The definition as **Set it up yourself** and **Settings** edit it |
9//! | [`AgentDetail`] | One agent: its definition, version, state and how it was added |
10//! | [`AgentPreview`] | **Here is what Finance can do**: the abilities, the risk and the digest a change is confirmed with; "Was … Now …" for a change; what removing it ends |
11//! | [`EndedWork`] | What removing an agent stops, counted |
12//! | [`AgentChoices`] | The models, packs, areas and colours a person may choose |
13//! | [`AgentCardView`] | The definition list on the decision that adds a suggested agent |
14//! | [`GrantedUse`] | What the home lets every agent on it do, beyond its definition: "On this home it can also:" |
15//! | [`AgentPreviewRequest`] | What `POST /surface/agents/preview` previews |
16//!
17//! Every name and instruction is data: renderers escape it (S-I9). No surface shows an
18//! agent's id (§8).
19
20use 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
34/// The eight avatar colours, in the kernel's palette order (spec 3.3 §9).
35const PALETTE: [&str; 8] =
36    ["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];
37
38/// An agent's colour: one of the eight avatar colours, never a free value (spec 3.3 §5.7).
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
40#[serde(rename_all = "camelCase")]
41pub enum AgentColor {
42    /// `#C03A00`.
43    #[default]
44    Orange,
45    /// `#15803D`.
46    Green,
47    /// `#1D4ED8`.
48    Blue,
49    /// `#7C3AED`.
50    Violet,
51    /// `#475569`.
52    Slate,
53    /// `#B45309`.
54    Amber,
55    /// `#0E7490`.
56    Teal,
57    /// `#BE185D`.
58    Pink,
59}
60
61impl AgentColor {
62    /// The colour drawn, `#RRGGBB`.
63    ///
64    /// # Example
65    ///
66    /// ```rust
67    /// assert_eq!(adk_surface::AgentColor::Green.hex(), "#15803D");
68    /// ```
69    pub fn hex(self) -> &'static str {
70        PALETTE[AvatarColor::from(self).index()]
71    }
72
73    /// The colour's name on screen: "Green".
74    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/// Where an agent's files are: none, read, or read and change (spec 3.3 §5.7).
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
120#[serde(rename_all = "camelCase")]
121pub enum FileUse {
122    /// No files.
123    #[default]
124    None,
125    /// It reads files.
126    Read,
127    /// It reads and changes files.
128    ReadWrite,
129}
130
131/// Where an agent's commands run: nowhere, in the sandbox, or on this computer.
132#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
133#[serde(rename_all = "camelCase")]
134pub enum ShellUse {
135    /// No shell.
136    #[default]
137    None,
138    /// The sandboxed shell.
139    Sandboxed,
140    /// A shell on this computer.
141    Host,
142}
143
144/// What of the web an agent reaches.
145#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
146#[serde(tag = "access", rename_all = "camelCase")]
147pub enum WebUse {
148    /// No web.
149    #[default]
150    None,
151    /// Listed sites only.
152    #[serde(rename_all = "camelCase")]
153    Listed {
154        /// The sites, such as `example.com`.
155        hosts: Vec<String>,
156    },
157    /// Any site.
158    Any,
159}
160
161/// What an agent can use (spec 3.3 §5.7 "What it can use").
162#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
163#[serde(rename_all = "camelCase")]
164pub struct UsesDraft {
165    /// Its files.
166    #[serde(default)]
167    pub files: FileUse,
168    /// One folder inside its area's workspace, relative to it; none for the whole workspace.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub folder: Option<String>,
171    /// Its shell.
172    #[serde(default)]
173    pub shell: ShellUse,
174    /// Its web.
175    #[serde(default)]
176    pub web: WebUse,
177    /// Its packs.
178    #[serde(default)]
179    pub packs: Vec<String>,
180    /// The drivers mounted for its area that it may use.
181    #[serde(default)]
182    pub drivers: Vec<String>,
183}
184
185/// A model an agent runs on; never a key (spec 3.3 decision 21).
186#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "camelCase")]
188pub struct ModelView {
189    /// The provider: `anthropic`, `openai`, `gemini`.
190    pub provider: String,
191    /// The model, shown in mono: `claude-sonnet-5-5`.
192    pub model: String,
193}
194
195/// An agent's definition as **Set it up yourself** and **Settings** edit it, in the order of
196/// spec 3.3 §5.7 "The definition".
197///
198/// # Example
199///
200/// ```rust
201/// use adk_surface::{AgentDraft, Mode};
202///
203/// let draft = AgentDraft::new("Finance", "default").with_mode(Mode::AskFirst);
204/// let definition = draft.clone().into_definition();
205/// assert_eq!(definition.display_name, "Finance");
206/// assert_eq!(AgentDraft::from_definition(&definition), draft);
207/// ```
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
209#[serde(rename_all = "camelCase")]
210pub struct AgentDraft {
211    /// Its name: "Finance".
212    pub display_name: String,
213    /// Its colour.
214    #[serde(default)]
215    pub color: AgentColor,
216    /// What it does, in one line.
217    #[serde(default)]
218    pub description: String,
219    /// How it works.
220    #[serde(default)]
221    pub instructions: String,
222    /// Its area.
223    pub area: String,
224    /// How much it asks first.
225    pub mode: Mode,
226    /// What it runs on; none for the primary agent's model.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub model: Option<ModelView>,
229    /// What it can use.
230    #[serde(default)]
231    pub uses: UsesDraft,
232    /// Its daily spending limit, micro-USD.
233    #[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    /// A draft named `display_name` in `area`, asking first, using nothing, in the colour the
257    /// name gives it.
258    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    /// Sets how much it asks first.
274    #[must_use]
275    pub fn with_mode(mut self, mode: Mode) -> Self {
276        self.mode = mode;
277        self
278    }
279
280    /// Sets what it can use.
281    #[must_use]
282    pub fn with_uses(mut self, uses: UsesDraft) -> Self {
283        self.uses = uses;
284        self
285    }
286
287    /// The kernel's definition of this draft.
288    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    /// The draft of a kernel definition.
330    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/// Where an agent is in its life, as a surface shows it (spec 3.3 §5.7, §8.1).
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
370#[serde(rename_all = "camelCase")]
371pub enum AgentLife {
372    /// Suggested by an agent and waiting for a person.
373    Suggested,
374    /// Added: **Ready** until it runs.
375    Active,
376    /// **Paused** by hand.
377    Paused,
378    /// Being removed.
379    Removing,
380    /// Removed; its threads stay.
381    Removed,
382    /// A suggestion the kernel refused.
383    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/// One agent a person added (spec 3.3 §5.7): what **Settings** shows.
400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
401#[serde(rename_all = "camelCase")]
402pub struct AgentDetail {
403    /// Its kernel target, for commands. Never shown.
404    pub id: String,
405    /// The agent as threads and decisions name it.
406    pub agent: AgentRef,
407    /// Its definition.
408    pub draft: AgentDraft,
409    /// The version a change is made against. Never shown.
410    pub version: u64,
411    /// Where it is in its life.
412    pub state: AgentLife,
413    /// "Added by you on 25 Oct", or "Suggested by ADK-Rust, added by you on 25 Oct".
414    pub origin_text: String,
415    /// How much it asks first, with its words.
416    pub mode: ModeView,
417    /// Why the kernel cannot build it: "No key for Anthropic".
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub cant_start: Option<String>,
420    /// When it was last changed.
421    pub changed_at: DateTime<Utc>,
422    /// The surface it was last changed on — `web`, `terminal`, `phone` — when the kernel
423    /// knows it; a change refused as out of date names it.
424    #[serde(default, skip_serializing_if = "Option::is_none")]
425    pub changed_on: Option<String>,
426    /// What the home lets it do beyond its definition, "On this home it can also:", from the
427    /// uses the host granted every agent it runs; empty for an agent that does not run, and
428    /// absent when empty (spec 3.3 §5.7, S-I12, S-I13).
429    #[serde(default, skip_serializing_if = "Vec::is_empty")]
430    pub granted: Vec<GrantedUse>,
431}
432
433/// Something the home lets every agent on it do beyond its definition, because the host
434/// gives each agent it runs the tools for it (spec 3.3 §5.7, S-I12, S-I13): shown under
435/// "Here is what Finance can do" as "On this home it can also:". Hosts register each with
436/// [`SurfaceEngineBuilder::grant`](crate::SurfaceEngineBuilder::grant).
437///
438/// # Example
439///
440/// ```rust
441/// use adk_surface::GrantedUse;
442///
443/// let draws = GrantedUse::new("genui", "Show forms and tables in your threads — sending asks you first");
444/// assert_eq!(draws.id, "genui");
445/// ```
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
447#[serde(rename_all = "camelCase")]
448pub struct GrantedUse {
449    /// The feature that grants it, such as `genui`: one line per id. Never shown.
450    pub id: String,
451    /// What it can do, in plain words: "Ask to change things on your screens — always asks
452    /// you first".
453    pub text: String,
454    /// The modes in which an agent can use it; empty for every mode. A surface lists it for an
455    /// agent only in one of them, so what an agent's settings say it can do is true (S-I13).
456    #[serde(default, skip_serializing_if = "Vec::is_empty")]
457    pub modes: Vec<Mode>,
458}
459
460impl GrantedUse {
461    /// The use `text`, granted by the feature `id`, in every mode.
462    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    /// Granted only to an agent in one of `modes`: one that asks, for a use that asks the
467    /// person, as the modes that only look or suggest refuse every such call (spec 3.3 §5.7).
468    ///
469    /// # Example
470    ///
471    /// ```rust
472    /// use adk_surface::{GrantedUse, Mode};
473    ///
474    /// let asks = GrantedUse::new("verb-ui", "Ask to change things on your screens")
475    ///     .only_in([Mode::AskFirst, Mode::GoAhead]);
476    /// assert!(asks.holds_in(Mode::GoAhead));
477    /// assert!(!asks.holds_in(Mode::Suggest));
478    /// ```
479    #[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    /// Whether an agent in `mode` can use it.
486    pub fn holds_in(&self, mode: Mode) -> bool {
487        self.modes.is_empty() || self.modes.contains(&mode)
488    }
489}
490
491/// An agent the person removed, whose threads stay readable (spec 3.3 §5.7, §13 decision 18;
492/// owner, at the wave 3 gate: "Removed agents" at the roster's foot).
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
494#[serde(rename_all = "camelCase")]
495pub struct RemovedAgent {
496    /// The agent as its threads name it.
497    pub agent: AgentRef,
498    /// "Removed on 25 Oct".
499    pub removed_text: String,
500    /// Its threads, newest first.
501    pub threads: Vec<RemovedThread>,
502}
503
504/// One thread of a removed agent, read only.
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
506#[serde(rename_all = "camelCase")]
507pub struct RemovedThread {
508    /// The session to open.
509    pub session_id: String,
510    /// When it last changed.
511    pub at: DateTime<Utc>,
512    /// "25 Oct 10:02".
513    pub when: String,
514}
515
516/// One of an agent's threads (spec 3.3 §5.1 "Thread history"): its session and when it last
517/// changed.
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
519#[serde(rename_all = "camelCase")]
520pub struct ThreadSummary {
521    /// The session to open.
522    pub session_id: String,
523    /// When it last changed.
524    pub at: DateTime<Utc>,
525    /// "25 Oct 10:02".
526    pub when: String,
527}
528
529/// An agent's threads, newest first: `GET /surface/agents/{id}/threads`.
530#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
531#[serde(rename_all = "camelCase")]
532pub struct AgentThreads {
533    /// The agent, by its roster name.
534    pub agent: String,
535    /// Its threads, newest first.
536    pub threads: Vec<ThreadSummary>,
537}
538
539/// What removing an agent ends, counted (spec 3.3 §5.7 "Pausing and removing").
540#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
541#[serde(rename_all = "camelCase")]
542pub struct EndedWork {
543    /// Pieces of work stopped.
544    pub work: u32,
545    /// Routines ended.
546    pub routines: u32,
547    /// Decisions waiting for you that end without an answer.
548    pub decisions: u32,
549    /// Follow-ups withdrawn.
550    pub follow_ups: u32,
551    /// "Allowed without asking" rules removed.
552    pub rules: u32,
553    /// "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1
554    /// routine. Its threads stay."
555    pub text: String,
556}
557
558impl EndedWork {
559    /// The counts of the kernel's `ended`, worded for `name`.
560    ///
561    /// # Example
562    ///
563    /// ```rust
564    /// use adk_surface::EndedWork;
565    ///
566    /// let mut ended = adk_kernel::agents::EndedWork::default();
567    /// ended.work = vec!["p1".into()];
568    /// ended.decisions = vec!["d1".into(), "d2".into()];
569    /// ended.routines = vec!["r1".into()];
570    /// assert_eq!(
571    ///     EndedWork::of(&ended, "Finance").text,
572    ///     "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1 routine. Its threads stay."
573    /// );
574    /// ```
575    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/// **Here is what Finance can do** (spec 3.3 §5.7): what a change lets an agent do, its risk,
591/// and the digest the change is confirmed with.
592#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
593#[serde(rename_all = "camelCase")]
594pub struct AgentPreview {
595    /// The agent's kernel target; for an agent not added yet, the id it would get. Never shown.
596    pub id: String,
597    /// The change: `create`, `change`, `pause`, `resume` or `remove`.
598    pub action: String,
599    /// "Here is what Finance can do".
600    pub heading: String,
601    /// What it can do, one plain sentence each.
602    pub abilities: Vec<String>,
603    /// The risk of the result.
604    pub risk: Risk,
605    /// "Medium risk".
606    pub risk_text: String,
607    /// It can spend money.
608    pub money: bool,
609    /// The change lets the agent do more: it needs what adding it at that risk needs, and it
610    /// first ends the agent's waiting decisions.
611    pub widens: bool,
612    /// Confirming needs presence: "Confirm it's you" in the home, or a paired local terminal.
613    pub needs_presence: bool,
614    /// The fields a change changes.
615    #[serde(default, skip_serializing_if = "Vec::is_empty")]
616    pub fields: Vec<String>,
617    /// "Was": the definition before a change.
618    #[serde(default, skip_serializing_if = "Option::is_none")]
619    pub was: Option<AgentDraft>,
620    /// "Now": the definition after it.
621    #[serde(default, skip_serializing_if = "Option::is_none")]
622    pub now: Option<AgentDraft>,
623    /// What removing it ends.
624    #[serde(default, skip_serializing_if = "Option::is_none")]
625    pub ended: Option<EndedWork>,
626    /// The digest the change applies with. Never shown.
627    pub digest: String,
628    /// The first six characters of the digest: the terminal's `--confirm` code.
629    pub code: String,
630}
631
632impl AgentPreview {
633    /// The kernel's preview of a change to the agent named `name`, in the surfaces' words.
634    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/// What `POST /surface/agents/preview` previews (spec 3.3 §5.7 "Show, then confirm").
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
658#[serde(tag = "action", rename_all = "camelCase")]
659pub enum AgentPreviewRequest {
660    /// Adding an agent: **Set it up yourself**, or **Change it first** on a suggestion.
661    #[serde(rename_all = "camelCase")]
662    Create {
663        /// The definition.
664        draft: AgentDraft,
665        /// The suggestion it replaces, when it came from **Change it first**.
666        #[serde(default, skip_serializing_if = "Option::is_none")]
667        replaces: Option<String>,
668    },
669    /// Changing an agent at the version seen.
670    #[serde(rename_all = "camelCase")]
671    Change {
672        /// The agent.
673        agent: String,
674        /// The version seen.
675        version: u64,
676        /// The definition after the change.
677        draft: AgentDraft,
678    },
679    /// Removing an agent at the version seen.
680    #[serde(rename_all = "camelCase")]
681    Remove {
682        /// The agent.
683        agent: String,
684        /// The version seen.
685        version: u64,
686    },
687}
688
689impl AgentPreviewRequest {
690    /// The kernel's action of this request.
691    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/// An area a person may put an agent in.
710#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
711#[serde(rename_all = "camelCase")]
712pub struct AreaChoice {
713    /// The area's id.
714    pub id: String,
715    /// Its name: "Home".
716    pub name: String,
717    /// Its mode: an agent there asks at least this much.
718    pub mode: ModeView,
719    /// The drivers mounted for it.
720    #[serde(default)]
721    pub drivers: Vec<String>,
722}
723
724/// A colour a person may choose.
725#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
726#[serde(rename_all = "camelCase")]
727pub struct ColorChoice {
728    /// The colour.
729    pub color: AgentColor,
730    /// Its name: "Green".
731    pub label: String,
732    /// What is drawn, `#RRGGBB`.
733    pub hex: String,
734}
735
736/// What a person may choose for an agent on this kernel (spec 3.3 §5.7, decision 21): the
737/// models of the providers whose key the kernel has, the packs, the areas and the colours.
738#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
739#[serde(rename_all = "camelCase")]
740pub struct AgentChoices {
741    /// The models, the primary agent's first.
742    pub models: Vec<ModelView>,
743    /// The packs.
744    pub packs: Vec<String>,
745    /// The areas.
746    pub areas: Vec<AreaChoice>,
747    /// The eight colours.
748    pub colors: Vec<ColorChoice>,
749}
750
751impl AgentChoices {
752    /// The kernel's choices, with `areas`.
753    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/// One line of an agent's definition on a card: "Area · Home".
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
782#[serde(rename_all = "camelCase")]
783pub struct CardLine {
784    /// "Runs on".
785    pub label: String,
786    /// "claude-sonnet-5-5".
787    pub value: String,
788    /// The value is a technical name, shown in mono. Absent when false.
789    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
790    pub mono: bool,
791}
792
793/// The definition on the decision that adds a suggested agent (spec 3.3 §5.7 "The decision
794/// that adds an agent", S-I13): every field, from the inbox entry the kernel wrote, never from
795/// the model.
796#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
797#[serde(rename_all = "camelCase")]
798pub struct AgentCardView {
799    /// The id the suggested agent would get: what **Change it first** replaces. Never shown.
800    pub id: String,
801    /// The agent it would add.
802    pub agent: AgentRef,
803    /// "What it does", in one line.
804    pub description: String,
805    /// The definition, one line per field: area, how much it asks first, what it runs on,
806    /// files, shell, web, packs, drivers, the daily limit.
807    pub lines: Vec<CardLine>,
808    /// The instructions, quoted, cut short past the call limit.
809    pub instructions: String,
810    /// The instructions are cut short: they must be expanded before the agent can be added.
811    pub instructions_truncated: bool,
812    /// What it can do, in plain words.
813    pub abilities: Vec<String>,
814    /// "It can do no more than ADK-Rust, and has no shell or web."
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub compared: Option<String>,
817    /// What it would start with: "Nothing yet".
818    pub allowed_without_asking: String,
819    /// The suggestion, for **Change it first**.
820    pub draft: AgentDraft,
821}
822
823/// The avatar of an agent named `display_name` in `color`.
824pub(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
833/// The agent a record names, with its own colour (spec 3.3 §5.7: kept across a rename).
834pub(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
842/// The mode with its words.
843pub(crate) fn mode_view(mode: PartitionMode) -> ModeView {
844    crate::project::mode_view(adk_harness::HarnessMode::from(mode))
845}
846
847/// "25 Oct".
848fn day(at: DateTime<Utc>, offset: FixedOffset) -> String {
849    at.with_timezone(&offset).format("%-d %b").to_string()
850}
851
852impl AgentDetail {
853    /// The detail of `record` for `user`, with the kernel's reason it cannot start, when it
854    /// cannot; `primary` names the suggesting agent ("ADK-Rust").
855    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    /// The removed agent `detail` with its threads: each session and when it last changed,
895    /// newest first.
896    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
918/// What a definition's files, shell and web are, in the card's words.
919fn 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
959/// What an agent has none of, in plain words.
960fn 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    /// The card of the suggestion `request` (`kernel:agent.create`), whose arguments are the
976    /// definition; `None` when they are not one. `suggester` is the suggesting agent's display
977    /// name, `area` its area's name.
978    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        // The kernel let the suggestion through only within its suggester's limits, so it
1026        // can do no more; what it has none of is said as the card knows it, not as a
1027        // difference from the suggester, whose limits the card does not hold.
1028        let compared = Some(words::no_more_than(suggester, &lacks(&definition.uses)));
1029        // The kernel names a suggestion's request `agent-<id>-<digest[..12]>`.
1030        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
1055/// An area's name on screen: "Home" for the kernel's default area, else its id capitalised.
1056pub(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
1067/// The kernel's caller for a surface's `caller` (spec 3.3 §5.7, S-I18): who, from which
1068/// surface and how, the paired device, whether the person is present, and the transport: the
1069/// web home, the phone and the tray reach the engine over HTTP only; a terminal's own
1070/// transport is recorded by the kernel's command routes.
1071pub(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
1096/// The agents a person added and the changes to them, over a kernel's agent table (spec 3.3
1097/// §5.7): what `LocalSource` reads and does.
1098pub(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    /// The agents of `user` the kernel keeps: active, paused and suggested ones.
1110    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    /// One agent of `user`.
1125    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    /// What a person may choose, with the kernel's areas.
1143    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    /// The preview of `request` for `caller`.
1172    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    /// The name the change is about: the definition's, or the agent's now.
1184    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    /// What a change applied, in the surfaces' words.
1203    pub(crate) enum Applied {
1204        Agent(Box<AgentDetail>),
1205        Removed(EndedWork),
1206    }
1207
1208    /// Applies `action` for `caller` with the digest its preview showed.
1209    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    /// Whether `error` says the agent changed since the version the surface showed.
1237    pub(crate) fn out_of_date(error: &SurfaceError) -> bool {
1238        error.code() == adk_kernel::error::AGENT_OUT_OF_DATE_CODE
1239    }
1240}
1241
1242/// The roster with the person's own agents (spec 3.3 §5.7 "The roster"): each process row of
1243/// an added agent takes its name, colour, area and mode from its definition; an agent that has
1244/// not run is listed as **Ready**, a paused one as **Paused**, one the kernel cannot build as
1245/// **Can't start**. The primary agent comes first, then the person's agents by name.
1246pub(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        // Paused by hand says what the person did: an agent that also cannot start shows
1260        // Paused, so Resume is what is offered (wave 3 finding 40).
1261        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 agents follow the primary, under their area, by name (spec 3.3 §5.7 "The
1300    // roster"); without areas every one is in Home.
1301    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
1312/// The first steps of "How it got here" for a suggested agent (spec 3.3 §5.7): when the person
1313/// asked, what the suggesting agent read in that turn — file names and sites only — and that it
1314/// suggested the agent. `events` is the suggesting session's history.
1315pub(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
1371/// The words of agents a person adds live in [`words`](crate::words) (spec 3.3 §8).
1372pub(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    /// Wave 3 findings 40 and 43: an agent paused by hand shows Paused even when it cannot
1466    /// start; added agents are listed under their area, then by name.
1467    #[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        // Wave 3 finding 36: the card never claims a difference from the suggester it cannot
1584        // check; the kernel kept the suggestion within the suggester's limits.
1585        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}