adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
//! Agents a person adds, as every surface shows and changes them (spec 3.3 §5.7).
//!
//! The kernel keeps each agent in its store and changes it only through its audited agent
//! table (`adk_kernel::agents`); this module is the wire between that table and the surfaces:
//!
//! | Type | What a surface does with it |
//! |---|---|
//! | [`AgentDraft`] | The definition as **Set it up yourself** and **Settings** edit it |
//! | [`AgentDetail`] | One agent: its definition, version, state and how it was added |
//! | [`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 |
//! | [`EndedWork`] | What removing an agent stops, counted |
//! | [`AgentChoices`] | The models, packs, areas and colours a person may choose |
//! | [`AgentCardView`] | The definition list on the decision that adds a suggested agent |
//! | [`GrantedUse`] | What the home lets every agent on it do, beyond its definition: "On this home it can also:" |
//! | [`AgentPreviewRequest`] | What `POST /surface/agents/preview` previews |
//!
//! Every name and instruction is data: renderers escape it (S-I9). No surface shows an
//! agent's id (§8).

use adk_core::ApprovalRequest;
use adk_kernel::PartitionMode;
use adk_kernel::agents::{
    AgentDefinition, AgentOrigin, AgentRecord, AgentRecordState, AgentUses, AvatarColor,
    FileAccess, ModelChoice, ShellAccess, WebAccess,
};
use chrono::{DateTime, FixedOffset, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::model::{AgentRef, Avatar, Mode, ModeView};
use crate::project::CALL_TEXT_LIMIT;
use crate::rules::Risk;

/// The eight avatar colours, in the kernel's palette order (spec 3.3 §9).
const PALETTE: [&str; 8] =
    ["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];

/// An agent's colour: one of the eight avatar colours, never a free value (spec 3.3 §5.7).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum AgentColor {
    /// `#C03A00`.
    #[default]
    Orange,
    /// `#15803D`.
    Green,
    /// `#1D4ED8`.
    Blue,
    /// `#7C3AED`.
    Violet,
    /// `#475569`.
    Slate,
    /// `#B45309`.
    Amber,
    /// `#0E7490`.
    Teal,
    /// `#BE185D`.
    Pink,
}

impl AgentColor {
    /// The colour drawn, `#RRGGBB`.
    ///
    /// # Example
    ///
    /// ```rust
    /// assert_eq!(adk_surface::AgentColor::Green.hex(), "#15803D");
    /// ```
    pub fn hex(self) -> &'static str {
        PALETTE[AvatarColor::from(self).index()]
    }

    /// The colour's name on screen: "Green".
    pub fn label(self) -> &'static str {
        match self {
            Self::Orange => "Orange",
            Self::Green => "Green",
            Self::Blue => "Blue",
            Self::Violet => "Violet",
            Self::Slate => "Slate",
            Self::Amber => "Amber",
            Self::Teal => "Teal",
            Self::Pink => "Pink",
        }
    }
}

impl From<AgentColor> for AvatarColor {
    fn from(color: AgentColor) -> Self {
        match color {
            AgentColor::Orange => Self::Orange,
            AgentColor::Green => Self::Green,
            AgentColor::Blue => Self::Blue,
            AgentColor::Violet => Self::Violet,
            AgentColor::Slate => Self::Slate,
            AgentColor::Amber => Self::Amber,
            AgentColor::Teal => Self::Teal,
            AgentColor::Pink => Self::Pink,
        }
    }
}

impl From<AvatarColor> for AgentColor {
    fn from(color: AvatarColor) -> Self {
        match color {
            AvatarColor::Green => Self::Green,
            AvatarColor::Blue => Self::Blue,
            AvatarColor::Violet => Self::Violet,
            AvatarColor::Slate => Self::Slate,
            AvatarColor::Amber => Self::Amber,
            AvatarColor::Teal => Self::Teal,
            AvatarColor::Pink => Self::Pink,
            _ => Self::Orange,
        }
    }
}

/// Where an agent's files are: none, read, or read and change (spec 3.3 §5.7).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum FileUse {
    /// No files.
    #[default]
    None,
    /// It reads files.
    Read,
    /// It reads and changes files.
    ReadWrite,
}

/// Where an agent's commands run: nowhere, in the sandbox, or on this computer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum ShellUse {
    /// No shell.
    #[default]
    None,
    /// The sandboxed shell.
    Sandboxed,
    /// A shell on this computer.
    Host,
}

/// What of the web an agent reaches.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "access", rename_all = "camelCase")]
pub enum WebUse {
    /// No web.
    #[default]
    None,
    /// Listed sites only.
    #[serde(rename_all = "camelCase")]
    Listed {
        /// The sites, such as `example.com`.
        hosts: Vec<String>,
    },
    /// Any site.
    Any,
}

/// What an agent can use (spec 3.3 §5.7 "What it can use").
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct UsesDraft {
    /// Its files.
    #[serde(default)]
    pub files: FileUse,
    /// One folder inside its area's workspace, relative to it; none for the whole workspace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
    /// Its shell.
    #[serde(default)]
    pub shell: ShellUse,
    /// Its web.
    #[serde(default)]
    pub web: WebUse,
    /// Its packs.
    #[serde(default)]
    pub packs: Vec<String>,
    /// The drivers mounted for its area that it may use.
    #[serde(default)]
    pub drivers: Vec<String>,
}

/// A model an agent runs on; never a key (spec 3.3 decision 21).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ModelView {
    /// The provider: `anthropic`, `openai`, `gemini`.
    pub provider: String,
    /// The model, shown in mono: `claude-sonnet-5-5`.
    pub model: String,
}

/// An agent's definition as **Set it up yourself** and **Settings** edit it, in the order of
/// spec 3.3 §5.7 "The definition".
///
/// # Example
///
/// ```rust
/// use adk_surface::{AgentDraft, Mode};
///
/// let draft = AgentDraft::new("Finance", "default").with_mode(Mode::AskFirst);
/// let definition = draft.clone().into_definition();
/// assert_eq!(definition.display_name, "Finance");
/// assert_eq!(AgentDraft::from_definition(&definition), draft);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentDraft {
    /// Its name: "Finance".
    pub display_name: String,
    /// Its colour.
    #[serde(default)]
    pub color: AgentColor,
    /// What it does, in one line.
    #[serde(default)]
    pub description: String,
    /// How it works.
    #[serde(default)]
    pub instructions: String,
    /// Its area.
    pub area: String,
    /// How much it asks first.
    pub mode: Mode,
    /// What it runs on; none for the primary agent's model.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelView>,
    /// What it can use.
    #[serde(default)]
    pub uses: UsesDraft,
    /// Its daily spending limit, micro-USD.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daily_limit_micro_usd: Option<u64>,
}

fn mode_of(mode: PartitionMode) -> Mode {
    match mode {
        PartitionMode::ReadOnly => Mode::JustLook,
        PartitionMode::Plan => Mode::Suggest,
        PartitionMode::Auto => Mode::GoAhead,
        _ => Mode::AskFirst,
    }
}

fn partition_mode(mode: Mode) -> PartitionMode {
    match mode {
        Mode::JustLook => PartitionMode::ReadOnly,
        Mode::Suggest => PartitionMode::Plan,
        Mode::AskFirst => PartitionMode::Ask,
        Mode::GoAhead => PartitionMode::Auto,
    }
}

impl AgentDraft {
    /// A draft named `display_name` in `area`, asking first, using nothing, in the colour the
    /// name gives it.
    pub fn new(display_name: impl Into<String>, area: impl Into<String>) -> Self {
        let display_name = display_name.into();
        Self {
            color: AvatarColor::for_name(&display_name).into(),
            display_name,
            description: String::new(),
            instructions: String::new(),
            area: area.into(),
            mode: Mode::AskFirst,
            model: None,
            uses: UsesDraft::default(),
            daily_limit_micro_usd: None,
        }
    }

    /// Sets how much it asks first.
    #[must_use]
    pub fn with_mode(mut self, mode: Mode) -> Self {
        self.mode = mode;
        self
    }

    /// Sets what it can use.
    #[must_use]
    pub fn with_uses(mut self, uses: UsesDraft) -> Self {
        self.uses = uses;
        self
    }

    /// The kernel's definition of this draft.
    pub fn into_definition(self) -> AgentDefinition {
        let mut uses = AgentUses::default()
            .with_files(match self.uses.files {
                FileUse::None => FileAccess::None,
                FileUse::Read => FileAccess::Read,
                FileUse::ReadWrite => FileAccess::ReadWrite,
            })
            .with_shell(match self.uses.shell {
                ShellUse::None => ShellAccess::None,
                ShellUse::Sandboxed => ShellAccess::Sandboxed,
                ShellUse::Host => ShellAccess::Host,
            })
            .with_web(match self.uses.web {
                WebUse::None => WebAccess::None,
                WebUse::Listed { hosts } => WebAccess::Listed { hosts },
                WebUse::Any => WebAccess::Any,
            });
        if let Some(folder) = self.uses.folder.filter(|folder| !folder.trim().is_empty()) {
            uses = uses.with_folder(folder);
        }
        for pack in self.uses.packs {
            uses = uses.with_pack(pack);
        }
        for driver in self.uses.drivers {
            uses = uses.with_driver(driver);
        }
        let mut definition = AgentDefinition::new(self.display_name, self.area.as_str())
            .with_color(self.color.into())
            .with_description(self.description)
            .with_instructions(self.instructions)
            .with_mode(partition_mode(self.mode))
            .with_uses(uses);
        if let Some(model) = self.model {
            definition = definition.with_model(ModelChoice::new(model.provider, model.model));
        }
        if let Some(limit) = self.daily_limit_micro_usd {
            definition = definition.with_daily_limit(limit);
        }
        definition
    }

    /// The draft of a kernel definition.
    pub fn from_definition(definition: &AgentDefinition) -> Self {
        let uses = &definition.uses;
        Self {
            display_name: definition.display_name.clone(),
            color: definition.color.into(),
            description: definition.description.clone(),
            instructions: definition.instructions.clone(),
            area: definition.area.as_str().to_string(),
            mode: mode_of(definition.mode),
            model: definition.model.as_ref().map(|model| ModelView {
                provider: model.provider.clone(),
                model: model.model.clone(),
            }),
            uses: UsesDraft {
                files: match uses.files {
                    FileAccess::None => FileUse::None,
                    FileAccess::Read => FileUse::Read,
                    FileAccess::ReadWrite => FileUse::ReadWrite,
                },
                folder: uses.folder.clone(),
                shell: match uses.shell {
                    ShellAccess::None => ShellUse::None,
                    ShellAccess::Sandboxed => ShellUse::Sandboxed,
                    ShellAccess::Host => ShellUse::Host,
                },
                web: match &uses.web {
                    WebAccess::None => WebUse::None,
                    WebAccess::Listed { hosts } => WebUse::Listed { hosts: hosts.clone() },
                    WebAccess::Any => WebUse::Any,
                },
                packs: uses.packs.clone(),
                drivers: uses.drivers.clone(),
            },
            daily_limit_micro_usd: definition.daily_limit_micro_usd,
        }
    }
}

/// Where an agent is in its life, as a surface shows it (spec 3.3 §5.7, §8.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub enum AgentLife {
    /// Suggested by an agent and waiting for a person.
    Suggested,
    /// Added: **Ready** until it runs.
    Active,
    /// **Paused** by hand.
    Paused,
    /// Being removed.
    Removing,
    /// Removed; its threads stay.
    Removed,
    /// A suggestion the kernel refused.
    Refused,
}

impl From<AgentRecordState> for AgentLife {
    fn from(state: AgentRecordState) -> Self {
        match state {
            AgentRecordState::Proposed => Self::Suggested,
            AgentRecordState::Paused => Self::Paused,
            AgentRecordState::Removing => Self::Removing,
            AgentRecordState::Removed => Self::Removed,
            AgentRecordState::Refused => Self::Refused,
            _ => Self::Active,
        }
    }
}

/// One agent a person added (spec 3.3 §5.7): what **Settings** shows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentDetail {
    /// Its kernel target, for commands. Never shown.
    pub id: String,
    /// The agent as threads and decisions name it.
    pub agent: AgentRef,
    /// Its definition.
    pub draft: AgentDraft,
    /// The version a change is made against. Never shown.
    pub version: u64,
    /// Where it is in its life.
    pub state: AgentLife,
    /// "Added by you on 25 Oct", or "Suggested by ADK-Rust, added by you on 25 Oct".
    pub origin_text: String,
    /// How much it asks first, with its words.
    pub mode: ModeView,
    /// Why the kernel cannot build it: "No key for Anthropic".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cant_start: Option<String>,
    /// When it was last changed.
    pub changed_at: DateTime<Utc>,
    /// The surface it was last changed on — `web`, `terminal`, `phone` — when the kernel
    /// knows it; a change refused as out of date names it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed_on: Option<String>,
    /// What the home lets it do beyond its definition, "On this home it can also:", from the
    /// uses the host granted every agent it runs; empty for an agent that does not run, and
    /// absent when empty (spec 3.3 §5.7, S-I12, S-I13).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub granted: Vec<GrantedUse>,
}

/// Something the home lets every agent on it do beyond its definition, because the host
/// gives each agent it runs the tools for it (spec 3.3 §5.7, S-I12, S-I13): shown under
/// "Here is what Finance can do" as "On this home it can also:". Hosts register each with
/// [`SurfaceEngineBuilder::grant`](crate::SurfaceEngineBuilder::grant).
///
/// # Example
///
/// ```rust
/// use adk_surface::GrantedUse;
///
/// let draws = GrantedUse::new("genui", "Show forms and tables in your threads — sending asks you first");
/// assert_eq!(draws.id, "genui");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct GrantedUse {
    /// The feature that grants it, such as `genui`: one line per id. Never shown.
    pub id: String,
    /// What it can do, in plain words: "Ask to change things on your screens — always asks
    /// you first".
    pub text: String,
    /// The modes in which an agent can use it; empty for every mode. A surface lists it for an
    /// agent only in one of them, so what an agent's settings say it can do is true (S-I13).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modes: Vec<Mode>,
}

impl GrantedUse {
    /// The use `text`, granted by the feature `id`, in every mode.
    pub fn new(id: impl Into<String>, text: impl Into<String>) -> Self {
        Self { id: id.into(), text: text.into(), modes: Vec::new() }
    }

    /// Granted only to an agent in one of `modes`: one that asks, for a use that asks the
    /// person, as the modes that only look or suggest refuse every such call (spec 3.3 §5.7).
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_surface::{GrantedUse, Mode};
    ///
    /// let asks = GrantedUse::new("verb-ui", "Ask to change things on your screens")
    ///     .only_in([Mode::AskFirst, Mode::GoAhead]);
    /// assert!(asks.holds_in(Mode::GoAhead));
    /// assert!(!asks.holds_in(Mode::Suggest));
    /// ```
    #[must_use]
    pub fn only_in(mut self, modes: impl IntoIterator<Item = Mode>) -> Self {
        self.modes = modes.into_iter().collect();
        self
    }

    /// Whether an agent in `mode` can use it.
    pub fn holds_in(&self, mode: Mode) -> bool {
        self.modes.is_empty() || self.modes.contains(&mode)
    }
}

/// An agent the person removed, whose threads stay readable (spec 3.3 §5.7, §13 decision 18;
/// owner, at the wave 3 gate: "Removed agents" at the roster's foot).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RemovedAgent {
    /// The agent as its threads name it.
    pub agent: AgentRef,
    /// "Removed on 25 Oct".
    pub removed_text: String,
    /// Its threads, newest first.
    pub threads: Vec<RemovedThread>,
}

/// One thread of a removed agent, read only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct RemovedThread {
    /// The session to open.
    pub session_id: String,
    /// When it last changed.
    pub at: DateTime<Utc>,
    /// "25 Oct 10:02".
    pub when: String,
}

/// One of an agent's threads (spec 3.3 §5.1 "Thread history"): its session and when it last
/// changed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ThreadSummary {
    /// The session to open.
    pub session_id: String,
    /// When it last changed.
    pub at: DateTime<Utc>,
    /// "25 Oct 10:02".
    pub when: String,
}

/// An agent's threads, newest first: `GET /surface/agents/{id}/threads`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentThreads {
    /// The agent, by its roster name.
    pub agent: String,
    /// Its threads, newest first.
    pub threads: Vec<ThreadSummary>,
}

/// What removing an agent ends, counted (spec 3.3 §5.7 "Pausing and removing").
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct EndedWork {
    /// Pieces of work stopped.
    pub work: u32,
    /// Routines ended.
    pub routines: u32,
    /// Decisions waiting for you that end without an answer.
    pub decisions: u32,
    /// Follow-ups withdrawn.
    pub follow_ups: u32,
    /// "Allowed without asking" rules removed.
    pub rules: u32,
    /// "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1
    /// routine. Its threads stay."
    pub text: String,
}

impl EndedWork {
    /// The counts of the kernel's `ended`, worded for `name`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_surface::EndedWork;
    ///
    /// let mut ended = adk_kernel::agents::EndedWork::default();
    /// ended.work = vec!["p1".into()];
    /// ended.decisions = vec!["d1".into(), "d2".into()];
    /// ended.routines = vec!["r1".into()];
    /// assert_eq!(
    ///     EndedWork::of(&ended, "Finance").text,
    ///     "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1 routine. Its threads stay."
    /// );
    /// ```
    pub fn of(ended: &adk_kernel::agents::EndedWork, name: &str) -> Self {
        let count = |items: &[String]| u32::try_from(items.len()).unwrap_or(u32::MAX);
        let mut out = Self {
            work: count(&ended.work),
            routines: count(&ended.routines),
            decisions: count(&ended.decisions),
            follow_ups: count(&ended.follow_ups),
            rules: u32::try_from(ended.rules).unwrap_or(u32::MAX),
            text: String::new(),
        };
        out.text = words::removing_ends(name, &out);
        out
    }
}

/// **Here is what Finance can do** (spec 3.3 §5.7): what a change lets an agent do, its risk,
/// and the digest the change is confirmed with.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentPreview {
    /// The agent's kernel target; for an agent not added yet, the id it would get. Never shown.
    pub id: String,
    /// The change: `create`, `change`, `pause`, `resume` or `remove`.
    pub action: String,
    /// "Here is what Finance can do".
    pub heading: String,
    /// What it can do, one plain sentence each.
    pub abilities: Vec<String>,
    /// The risk of the result.
    pub risk: Risk,
    /// "Medium risk".
    pub risk_text: String,
    /// It can spend money.
    pub money: bool,
    /// The change lets the agent do more: it needs what adding it at that risk needs, and it
    /// first ends the agent's waiting decisions.
    pub widens: bool,
    /// Confirming needs presence: "Confirm it's you" in the home, or a paired local terminal.
    pub needs_presence: bool,
    /// The fields a change changes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<String>,
    /// "Was": the definition before a change.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub was: Option<AgentDraft>,
    /// "Now": the definition after it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub now: Option<AgentDraft>,
    /// What removing it ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended: Option<EndedWork>,
    /// The digest the change applies with. Never shown.
    pub digest: String,
    /// The first six characters of the digest: the terminal's `--confirm` code.
    pub code: String,
}

impl AgentPreview {
    /// The kernel's preview of a change to the agent named `name`, in the surfaces' words.
    pub fn of(preview: &adk_kernel::agents::AgentPreview, name: &str) -> Self {
        let risk = Risk::from(preview.risk);
        Self {
            id: preview.id.clone(),
            action: preview.action.clone(),
            heading: words::here_is_what_can_do(name),
            abilities: preview.abilities.clone(),
            risk,
            risk_text: risk.words().to_string(),
            money: preview.money,
            widens: preview.widens,
            needs_presence: preview.needs_presence(),
            fields: preview.fields.clone(),
            was: preview.was.as_ref().map(AgentDraft::from_definition),
            now: preview.now.as_ref().map(AgentDraft::from_definition),
            ended: preview.ended.as_ref().map(|ended| EndedWork::of(ended, name)),
            digest: preview.digest.clone(),
            code: preview.code().to_string(),
        }
    }
}

/// What `POST /surface/agents/preview` previews (spec 3.3 §5.7 "Show, then confirm").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "action", rename_all = "camelCase")]
pub enum AgentPreviewRequest {
    /// Adding an agent: **Set it up yourself**, or **Change it first** on a suggestion.
    #[serde(rename_all = "camelCase")]
    Create {
        /// The definition.
        draft: AgentDraft,
        /// The suggestion it replaces, when it came from **Change it first**.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        replaces: Option<String>,
    },
    /// Changing an agent at the version seen.
    #[serde(rename_all = "camelCase")]
    Change {
        /// The agent.
        agent: String,
        /// The version seen.
        version: u64,
        /// The definition after the change.
        draft: AgentDraft,
    },
    /// Removing an agent at the version seen.
    #[serde(rename_all = "camelCase")]
    Remove {
        /// The agent.
        agent: String,
        /// The version seen.
        version: u64,
    },
}

impl AgentPreviewRequest {
    /// The kernel's action of this request.
    pub fn into_action(self) -> adk_kernel::agents::AgentAction {
        match self {
            Self::Create { draft, replaces } => adk_kernel::agents::AgentAction::Create {
                definition: draft.into_definition(),
                replaces,
            },
            Self::Change { agent, version, draft } => adk_kernel::agents::AgentAction::Change {
                id: agent,
                expected_version: version,
                definition: draft.into_definition(),
            },
            Self::Remove { agent, version } => {
                adk_kernel::agents::AgentAction::Remove { id: agent, expected_version: version }
            }
        }
    }
}

/// An area a person may put an agent in.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AreaChoice {
    /// The area's id.
    pub id: String,
    /// Its name: "Home".
    pub name: String,
    /// Its mode: an agent there asks at least this much.
    pub mode: ModeView,
    /// The drivers mounted for it.
    #[serde(default)]
    pub drivers: Vec<String>,
}

/// A colour a person may choose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct ColorChoice {
    /// The colour.
    pub color: AgentColor,
    /// Its name: "Green".
    pub label: String,
    /// What is drawn, `#RRGGBB`.
    pub hex: String,
}

/// What a person may choose for an agent on this kernel (spec 3.3 §5.7, decision 21): the
/// models of the providers whose key the kernel has, the packs, the areas and the colours.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentChoices {
    /// The models, the primary agent's first.
    pub models: Vec<ModelView>,
    /// The packs.
    pub packs: Vec<String>,
    /// The areas.
    pub areas: Vec<AreaChoice>,
    /// The eight colours.
    pub colors: Vec<ColorChoice>,
}

impl AgentChoices {
    /// The kernel's choices, with `areas`.
    pub fn of(choices: &adk_kernel::agents::AgentChoices, areas: Vec<AreaChoice>) -> Self {
        Self {
            models: choices
                .models
                .iter()
                .map(|model| ModelView {
                    provider: model.provider.clone(),
                    model: model.model.clone(),
                })
                .collect(),
            packs: choices.packs.clone(),
            areas,
            colors: AvatarColor::ALL
                .iter()
                .map(|color| {
                    let color = AgentColor::from(*color);
                    ColorChoice {
                        color,
                        label: color.label().to_string(),
                        hex: color.hex().to_string(),
                    }
                })
                .collect(),
        }
    }
}

/// One line of an agent's definition on a card: "Area · Home".
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CardLine {
    /// "Runs on".
    pub label: String,
    /// "claude-sonnet-5-5".
    pub value: String,
    /// The value is a technical name, shown in mono. Absent when false.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub mono: bool,
}

/// The definition on the decision that adds a suggested agent (spec 3.3 §5.7 "The decision
/// that adds an agent", S-I13): every field, from the inbox entry the kernel wrote, never from
/// the model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentCardView {
    /// The id the suggested agent would get: what **Change it first** replaces. Never shown.
    pub id: String,
    /// The agent it would add.
    pub agent: AgentRef,
    /// "What it does", in one line.
    pub description: String,
    /// The definition, one line per field: area, how much it asks first, what it runs on,
    /// files, shell, web, packs, drivers, the daily limit.
    pub lines: Vec<CardLine>,
    /// The instructions, quoted, cut short past the call limit.
    pub instructions: String,
    /// The instructions are cut short: they must be expanded before the agent can be added.
    pub instructions_truncated: bool,
    /// What it can do, in plain words.
    pub abilities: Vec<String>,
    /// "It can do no more than ADK-Rust, and has no shell or web."
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compared: Option<String>,
    /// What it would start with: "Nothing yet".
    pub allowed_without_asking: String,
    /// The suggestion, for **Change it first**.
    pub draft: AgentDraft,
}

/// The avatar of an agent named `display_name` in `color`.
pub(crate) fn avatar_of(display_name: &str, color: AgentColor) -> Avatar {
    let monogram: String = display_name
        .chars()
        .find(|c| c.is_alphanumeric())
        .map(|c| c.to_uppercase().collect())
        .unwrap_or_default();
    Avatar { monogram, color: color.hex().to_string() }
}

/// The agent a record names, with its own colour (spec 3.3 §5.7: kept across a rename).
pub(crate) fn agent_ref(record: &AgentRecord) -> AgentRef {
    AgentRef {
        name: record.id.clone(),
        display_name: record.display_name.clone(),
        avatar: avatar_of(&record.display_name, record.color.into()),
    }
}

/// The mode with its words.
pub(crate) fn mode_view(mode: PartitionMode) -> ModeView {
    crate::project::mode_view(adk_harness::HarnessMode::from(mode))
}

/// "25 Oct".
fn day(at: DateTime<Utc>, offset: FixedOffset) -> String {
    at.with_timezone(&offset).format("%-d %b").to_string()
}

impl AgentDetail {
    /// The detail of `record` for `user`, with the kernel's reason it cannot start, when it
    /// cannot; `primary` names the suggesting agent ("ADK-Rust").
    pub fn of(
        record: &AgentRecord,
        cant_start: Option<String>,
        user: &str,
        primary: &str,
        offset: FixedOffset,
    ) -> Self {
        let you = |subject: &adk_core::principal::SubjectRef| {
            if subject.id == user { "you".to_string() } else { subject.id.clone() }
        };
        let added_by = record.approved_by.as_ref().unwrap_or(&record.created_by);
        let on = day(record.created_at, offset);
        let origin_text = match &record.origin {
            AgentOrigin::ByHand => format!("Added by {} on {on}", you(&record.created_by)),
            AgentOrigin::Suggested { .. } => {
                format!(
                    "{}, added by {} on {on}",
                    words::suggested_agent_by(primary),
                    you(added_by)
                )
            }
        };
        Self {
            id: record.id.clone(),
            agent: agent_ref(record),
            draft: AgentDraft::from_definition(&record.definition()),
            version: record.version,
            state: record.state.into(),
            origin_text,
            mode: mode_view(record.mode),
            cant_start,
            changed_at: record.updated_at,
            changed_on: record.changed_on.clone(),
            granted: Vec::new(),
        }
    }
}

impl RemovedAgent {
    /// The removed agent `detail` with its threads: each session and when it last changed,
    /// newest first.
    pub(crate) fn of(
        detail: &AgentDetail,
        threads: Vec<(String, DateTime<Utc>)>,
        offset: FixedOffset,
    ) -> Self {
        let mut threads: Vec<RemovedThread> = threads
            .into_iter()
            .map(|(session_id, at)| RemovedThread {
                session_id,
                at,
                when: at.with_timezone(&offset).format("%-d %b %H:%M").to_string(),
            })
            .collect();
        threads.sort_by_key(|thread| std::cmp::Reverse(thread.at));
        Self {
            agent: detail.agent.clone(),
            removed_text: words::removed_on(&day(detail.changed_at, offset)),
            threads,
        }
    }
}

/// What a definition's files, shell and web are, in the card's words.
fn uses_lines(uses: &AgentUses) -> Vec<CardLine> {
    let line =
        |label: &str, value: String| CardLine { label: label.to_string(), value, mono: false };
    let place = uses.folder.clone().unwrap_or_else(|| "the workspace".to_string());
    let mut lines = vec![
        line(
            "Files",
            match uses.files {
                FileAccess::None => "No files".to_string(),
                FileAccess::Read => format!("Reads files in {place}"),
                FileAccess::ReadWrite => format!("Reads and changes files in {place}"),
            },
        ),
        line(
            "Shell",
            match uses.shell {
                ShellAccess::None => "No shell",
                ShellAccess::Sandboxed => "In the sandbox",
                ShellAccess::Host => "On this computer",
            }
            .to_string(),
        ),
        line(
            "Web",
            match &uses.web {
                WebAccess::None => "No web".to_string(),
                WebAccess::Listed { hosts } => format!("Listed sites only: {}", hosts.join(", ")),
                WebAccess::Any => "Any site".to_string(),
            },
        ),
    ];
    if !uses.packs.is_empty() {
        lines.push(line("Packs", uses.packs.join(", ")));
    }
    if !uses.drivers.is_empty() {
        lines.push(line("Drivers", uses.drivers.join(", ")));
    }
    lines
}

/// What an agent has none of, in plain words.
fn lacks(uses: &AgentUses) -> Vec<&'static str> {
    let mut lacks = Vec::new();
    if uses.files == FileAccess::None {
        lacks.push("files");
    }
    if uses.shell == ShellAccess::None {
        lacks.push("shell");
    }
    if uses.web == WebAccess::None {
        lacks.push("web");
    }
    lacks
}

impl AgentCardView {
    /// The card of the suggestion `request` (`kernel:agent.create`), whose arguments are the
    /// definition; `None` when they are not one. `suggester` is the suggesting agent's display
    /// name, `area` its area's name.
    pub fn of_request(request: &ApprovalRequest, suggester: &str, area: &str) -> Option<Self> {
        let definition: AgentDefinition =
            serde_json::from_value(request.args_redacted.clone()).ok()?;
        let record = AgentRecord::new(
            String::new(),
            definition.clone(),
            AgentRecordState::Proposed,
            AgentOrigin::ByHand,
            request
                .requester
                .clone()
                .unwrap_or_else(|| adk_core::principal::SubjectRef::human(&request.scope.user_id)),
            request.created_at,
        );
        let assessment = adk_harness::assess_agent(&record);
        let mut lines = vec![
            CardLine { label: "Area".into(), value: area.to_string(), mono: false },
            CardLine {
                label: "How much it asks first".into(),
                value: mode_view(definition.mode).status,
                mono: false,
            },
        ];
        lines.push(match &definition.model {
            Some(model) => {
                CardLine { label: "Runs on".into(), value: model.model.clone(), mono: true }
            }
            None => CardLine {
                label: "Runs on".into(),
                value: format!("{suggester}'s model"),
                mono: false,
            },
        });
        lines.extend(uses_lines(&definition.uses));
        if let Some(limit) = definition.daily_limit_micro_usd {
            lines.push(CardLine {
                label: "Daily spending limit".into(),
                value: crate::words::dollars(limit),
                mono: false,
            });
        }
        let truncated = definition.instructions.chars().count() > CALL_TEXT_LIMIT;
        let instructions = if truncated {
            definition.instructions.chars().take(CALL_TEXT_LIMIT).collect::<String>() + "…"
        } else {
            definition.instructions.clone()
        };
        // The kernel let the suggestion through only within its suggester's limits, so it
        // can do no more; what it has none of is said as the card knows it, not as a
        // difference from the suggester, whose limits the card does not hold.
        let compared = Some(words::no_more_than(suggester, &lacks(&definition.uses)));
        // The kernel names a suggestion's request `agent-<id>-<digest[..12]>`.
        let id = request
            .id
            .strip_prefix("agent-")
            .and_then(|rest| rest.rsplit_once('-'))
            .map(|(id, _)| id.to_string())
            .unwrap_or_default();
        Some(Self {
            agent: AgentRef {
                name: id.clone(),
                display_name: definition.display_name.clone(),
                avatar: avatar_of(&definition.display_name, definition.color.into()),
            },
            description: definition.description.clone(),
            lines,
            instructions,
            instructions_truncated: truncated,
            abilities: assessment.abilities,
            compared,
            allowed_without_asking: words::NOTHING_YET.to_string(),
            draft: AgentDraft::from_definition(&definition),
            id,
        })
    }
}

/// An area's name on screen: "Home" for the kernel's default area, else its id capitalised.
pub(crate) fn area_name(area: &str) -> String {
    if area == adk_kernel::PartitionId::DEFAULT {
        return "Home".to_string();
    }
    let mut chars = area.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => String::new(),
    }
}

/// The kernel's caller for a surface's `caller` (spec 3.3 §5.7, S-I18): who, from which
/// surface and how, the paired device, whether the person is present, and the transport: the
/// web home, the phone and the tray reach the engine over HTTP only; a terminal's own
/// transport is recorded by the kernel's command routes.
pub(crate) fn agent_caller(caller: &crate::origin::Caller) -> adk_kernel::agents::AgentCaller {
    use crate::origin::SurfaceKind;
    let surface = serde_json::to_value(caller.surface)
        .ok()
        .and_then(|value| value.as_str().map(str::to_string))
        .unwrap_or_default();
    let mut agent =
        adk_kernel::agents::AgentCaller::new(caller.subject.clone(), surface, caller.origin.kind());
    match caller.surface {
        SurfaceKind::Web | SurfaceKind::Phone | SurfaceKind::Tray => {
            agent = agent.with_transport(adk_kernel::control::ControlTransport::Http);
        }
        SurfaceKind::Terminal | SurfaceKind::Chat | SurfaceKind::Voice => {}
    }
    if let Some(device) = &caller.device {
        agent = agent.with_device(device.clone());
    }
    if caller.presence_confirmed {
        agent = agent.with_presence(adk_kernel::agents::Presence::Confirmed);
    } else if caller.paired_local {
        agent = agent.with_presence(adk_kernel::agents::Presence::PairedLocal);
    }
    agent
}

/// The agents a person added and the changes to them, over a kernel's agent table (spec 3.3
/// §5.7): what `LocalSource` reads and does.
pub(crate) mod local {
    use adk_kernel::agents::{AgentAction, AgentRecordState, Agents};
    use chrono::FixedOffset;

    use super::{
        AgentChoices, AgentDetail, AgentPreview, AgentPreviewRequest, AreaChoice, EndedWork,
        agent_caller, area_name, mode_view,
    };
    use crate::error::{Result, SurfaceError};
    use crate::origin::Caller;

    /// The agents of `user` the kernel keeps: active, paused and suggested ones.
    pub(crate) async fn definitions(
        agents: &Agents,
        user: &str,
        primary: &str,
        offset: FixedOffset,
    ) -> Result<Vec<AgentDetail>> {
        Ok(agents
            .list()
            .await?
            .into_iter()
            .map(|view| AgentDetail::of(&view.agent, view.cant_start, user, primary, offset))
            .collect())
    }

    /// One agent of `user`.
    pub(crate) async fn agent(
        agents: &Agents,
        id: &str,
        user: &str,
        primary: &str,
        offset: FixedOffset,
    ) -> Result<AgentDetail> {
        agents
            .get(id)
            .await?
            .filter(|view| {
                !matches!(view.agent.state, AgentRecordState::Removed | AgentRecordState::Refused)
            })
            .map(|view| AgentDetail::of(&view.agent, view.cant_start, user, primary, offset))
            .ok_or_else(|| SurfaceError::not_found(format!("agent '{id}'")))
    }

    /// What a person may choose, with the kernel's areas.
    pub(crate) async fn choices(
        agents: &Agents,
        partitions: &adk_kernel::Partitions,
    ) -> Result<AgentChoices> {
        let choices = agents.choices().await?;
        let mut areas: Vec<AreaChoice> = partitions
            .store()
            .list()
            .await?
            .into_iter()
            .map(|area| AreaChoice {
                name: area_name(area.id.as_str()),
                id: area.id.as_str().to_string(),
                mode: mode_view(area.default_mode),
                drivers: area.drivers.clone(),
            })
            .collect();
        if areas.is_empty() {
            areas.push(AreaChoice {
                id: adk_kernel::PartitionId::DEFAULT.to_string(),
                name: area_name(adk_kernel::PartitionId::DEFAULT),
                mode: mode_view(adk_kernel::PartitionMode::Ask),
                drivers: Vec::new(),
            });
        }
        Ok(AgentChoices::of(&choices, areas))
    }

    /// The preview of `request` for `caller`.
    pub(crate) async fn preview(
        agents: &Agents,
        caller: &Caller,
        request: AgentPreviewRequest,
    ) -> Result<AgentPreview> {
        let action = request.into_action();
        let name = name_of(agents, &action).await;
        let preview = agents.preview(&agent_caller(caller), &action).await?;
        Ok(AgentPreview::of(&preview, &name))
    }

    /// The name the change is about: the definition's, or the agent's now.
    async fn name_of(agents: &Agents, action: &AgentAction) -> String {
        match action {
            AgentAction::Create { definition, .. } | AgentAction::Change { definition, .. } => {
                definition.display_name.clone()
            }
            other => match other.id() {
                Some(id) => agents
                    .get(id)
                    .await
                    .ok()
                    .flatten()
                    .map(|view| view.agent.display_name)
                    .unwrap_or_else(|| id.to_string()),
                None => String::new(),
            },
        }
    }

    /// What a change applied, in the surfaces' words.
    pub(crate) enum Applied {
        Agent(Box<AgentDetail>),
        Removed(EndedWork),
    }

    /// Applies `action` for `caller` with the digest its preview showed.
    pub(crate) async fn apply(
        agents: &Agents,
        caller: &Caller,
        action: AgentAction,
        digest: &str,
        primary: &str,
        offset: FixedOffset,
    ) -> Result<Applied> {
        let name = name_of(agents, &action).await;
        let outcome = agents.apply(&agent_caller(caller), action, digest).await?;
        let user = caller.user_id();
        Ok(match outcome {
            adk_kernel::agents::AgentOutcome::Removed { ended, .. } => {
                Applied::Removed(EndedWork::of(&ended, &name))
            }
            adk_kernel::agents::AgentOutcome::Created { agent }
            | adk_kernel::agents::AgentOutcome::Changed { agent }
            | adk_kernel::agents::AgentOutcome::Paused { agent }
            | adk_kernel::agents::AgentOutcome::Resumed { agent } => {
                Applied::Agent(Box::new(AgentDetail::of(&agent, None, user, primary, offset)))
            }
            other => {
                return Err(SurfaceError::Invalid(format!("the kernel answered {other:?}")));
            }
        })
    }

    /// Whether `error` says the agent changed since the version the surface showed.
    pub(crate) fn out_of_date(error: &SurfaceError) -> bool {
        error.code() == adk_kernel::error::AGENT_OUT_OF_DATE_CODE
    }
}

/// The roster with the person's own agents (spec 3.3 §5.7 "The roster"): each process row of
/// an added agent takes its name, colour, area and mode from its definition; an agent that has
/// not run is listed as **Ready**, a paused one as **Paused**, one the kernel cannot build as
/// **Can't start**. The primary agent comes first, then the person's agents by name.
pub(crate) fn roster(
    rows: Vec<crate::model::AgentRow>,
    definitions: &[AgentDetail],
    can_change: bool,
) -> Vec<crate::model::AgentRow> {
    use crate::model::{AgentRow, AgentStatus};
    let (mut primary, mut added): (Vec<AgentRow>, Vec<AgentRow>) = rows
        .into_iter()
        .partition(|row| !definitions.iter().any(|detail| detail.id == row.agent.name));
    for detail in definitions {
        if !matches!(detail.state, AgentLife::Active | AgentLife::Paused) {
            continue;
        }
        // Paused by hand says what the person did: an agent that also cannot start shows
        // Paused, so Resume is what is offered (wave 3 finding 40).
        let status = if detail.state == AgentLife::Paused {
            Some((AgentStatus::Paused, words::PAUSED))
        } else if detail.cant_start.is_some() {
            Some((AgentStatus::CantStart, words::CANT_START))
        } else {
            None
        };
        let area = Some(area_name(&detail.draft.area));
        match added.iter_mut().find(|row| row.agent.name == detail.id) {
            Some(row) => {
                row.agent = detail.agent.clone();
                if let Some((status, text)) = status {
                    row.status = status;
                    row.status_text = text.to_string();
                    row.wake_at = None;
                }
                row.area = area;
                row.mode = Some(detail.mode.clone());
                row.added = true;
                row.can_change = can_change;
            }
            None => {
                let (status, text) = status.unwrap_or((AgentStatus::Ready, words::READY));
                added.push(AgentRow {
                    agent: detail.agent.clone(),
                    status,
                    status_text: text.to_string(),
                    wake_at: None,
                    session_id: None,
                    area,
                    mode: Some(detail.mode.clone()),
                    added: true,
                    can_change,
                    shell: None,
                });
            }
        }
    }
    // Added agents follow the primary, under their area, by name (spec 3.3 §5.7 "The
    // roster"); without areas every one is in Home.
    added.sort_by(|a, b| {
        (!a.added, &a.area, a.agent.display_name.to_lowercase()).cmp(&(
            !b.added,
            &b.area,
            b.agent.display_name.to_lowercase(),
        ))
    });
    primary.extend(added.into_iter().filter(|row| row.added));
    primary
}

/// The first steps of "How it got here" for a suggested agent (spec 3.3 §5.7): when the person
/// asked, what the suggesting agent read in that turn — file names and sites only — and that it
/// suggested the agent. `events` is the suggesting session's history.
pub(crate) fn suggestion_steps(
    events: &[adk_core::Event],
    suggester: &str,
    suggested_at: DateTime<Utc>,
    hh_mm: impl Fn(DateTime<Utc>) -> String,
) -> Vec<String> {
    let before: Vec<&adk_core::Event> =
        events.iter().filter(|event| event.timestamp <= suggested_at).collect();
    let asked = before.iter().rposition(|event| event.author == "user");
    let mut steps = Vec::new();
    if let Some(at) = asked {
        steps.push(format!("You asked at {}", hh_mm(before[at].timestamp)));
    }
    let turn = &before[asked.map_or(0, |at| at + 1)..];
    let mut files: Vec<String> = Vec::new();
    let mut sites: Vec<String> = Vec::new();
    for event in turn {
        let Some(content) = &event.llm_response.content else { continue };
        for part in &content.parts {
            let adk_core::Part::FunctionCall { name, args, .. } = part else { continue };
            match name.as_str() {
                "read_file" | "grep" | "glob" | "list_dir" => {
                    if let Some(path) = args.get("path").and_then(serde_json::Value::as_str) {
                        let file = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
                        if !files.contains(&file) {
                            files.push(file);
                        }
                    }
                }
                "web_fetch" => {
                    let host = args
                        .get("url")
                        .and_then(serde_json::Value::as_str)
                        .and_then(|url| url.split("://").nth(1))
                        .and_then(|rest| rest.split(['/', '?', '#', ':']).next())
                        .map(str::to_string);
                    if let Some(host) = host.filter(|host| !sites.contains(host)) {
                        sites.push(host);
                    }
                }
                _ => {}
            }
        }
    }
    match files.len() {
        0 => {}
        1 => steps.push(format!("{suggester} read {}", files[0])),
        n => steps.push(format!("{suggester} read {n} files")),
    }
    if !sites.is_empty() {
        steps.push(format!("{suggester} read {}", sites.join(", ")));
    }
    steps.push(format!("{suggester} suggested this agent"));
    steps
}

/// The words of agents a person adds live in [`words`](crate::words) (spec 3.3 §8).
pub(crate) use crate::words;

#[cfg(test)]
mod tests {
    use adk_core::principal::SubjectRef;

    use super::words::*;
    use super::*;

    #[test]
    fn a_draft_round_trips_through_the_kernels_definition() {
        let draft = AgentDraft {
            display_name: "Finance".into(),
            color: AgentColor::Teal,
            description: "Reads invoices".into(),
            instructions: "Draft reminders.".into(),
            area: "home".into(),
            mode: Mode::Suggest,
            model: Some(ModelView {
                provider: "anthropic".into(),
                model: "claude-sonnet-5-5".into(),
            }),
            uses: UsesDraft {
                files: FileUse::Read,
                folder: Some("Invoices".into()),
                shell: ShellUse::Sandboxed,
                web: WebUse::Listed { hosts: vec!["bank.example".into()] },
                packs: vec!["browser".into()],
                drivers: vec!["calendar".into()],
            },
            daily_limit_micro_usd: Some(2_000_000),
        };
        let definition = draft.clone().into_definition();
        assert!(definition.validate().is_ok());
        assert_eq!(AgentDraft::from_definition(&definition), draft);
        let wire = serde_json::to_value(&draft).unwrap();
        assert_eq!(
            wire["uses"]["web"],
            serde_json::json!({ "access": "listed", "hosts": ["bank.example"] })
        );
        assert_eq!(wire["color"], "teal");
    }

    #[test]
    fn the_roster_puts_the_primary_first_and_the_persons_agents_by_name() {
        use crate::model::{AgentRow, AgentStatus};
        let detail = |id: &str, name: &str, state: AgentRecordState| {
            let record = AgentRecord::new(
                id,
                AgentDefinition::new(name, "default"),
                state,
                AgentOrigin::ByHand,
                SubjectRef::human("ana"),
                chrono::Utc::now(),
            );
            AgentDetail::of(&record, None, "ana", "ADK-Rust", FixedOffset::east_opt(0).unwrap())
        };
        let row = |name: &str| AgentRow {
            agent: AgentRef {
                name: name.into(),
                display_name: name.into(),
                avatar: avatar_of(name, AgentColor::Slate),
            },
            status: AgentStatus::Working,
            status_text: "Working".into(),
            wake_at: None,
            session_id: Some(format!("s-{name}")),
            area: None,
            mode: None,
            added: false,
            can_change: false,
            shell: None,
        };
        let definitions = [
            detail("zeta", "Zeta", AgentRecordState::Active),
            detail("bills", "Bills", AgentRecordState::Paused),
            detail("waiting", "Waiting", AgentRecordState::Proposed),
        ];
        let rows = roster(vec![row("zeta"), row("adk-rust")], &definitions, true);
        let names: Vec<(&str, AgentStatus)> =
            rows.iter().map(|row| (row.agent.display_name.as_str(), row.status)).collect();
        assert_eq!(
            names,
            [
                ("adk-rust", AgentStatus::Working),
                ("Bills", AgentStatus::Paused),
                ("Zeta", AgentStatus::Working)
            ]
        );
        assert!(rows[1].added && rows[1].can_change && !rows[0].added);
        assert_eq!(rows[2].session_id.as_deref(), Some("s-zeta"));
    }

    /// Wave 3 findings 40 and 43: an agent paused by hand shows Paused even when it cannot
    /// start; added agents are listed under their area, then by name.
    #[test]
    fn paused_wins_over_cant_start_and_agents_sit_under_their_area() {
        let detail = |id: &str, name: &str, area: &str, state: AgentRecordState| {
            let record = AgentRecord::new(
                id,
                AgentDefinition::new(name, area),
                state,
                AgentOrigin::ByHand,
                SubjectRef::human("ana"),
                chrono::Utc::now(),
            );
            AgentDetail::of(
                &record,
                Some("No key for OpenAI".into()),
                "ana",
                "ADK-Rust",
                FixedOffset::east_opt(0).unwrap(),
            )
        };
        let definitions = [
            detail("builder", "Builder", "work", AgentRecordState::Active),
            detail("bills", "Bills", "home", AgentRecordState::Paused),
            detail("archive", "Archive", "work", AgentRecordState::Active),
        ];
        let rows = roster(Vec::new(), &definitions, true);
        let shown: Vec<(&str, Option<&str>, AgentStatus)> = rows
            .iter()
            .map(|row| (row.agent.display_name.as_str(), row.area.as_deref(), row.status))
            .collect();
        use crate::model::AgentStatus;
        assert_eq!(
            shown,
            [
                ("Bills", Some("Home"), AgentStatus::Paused),
                ("Archive", Some("Work"), AgentStatus::CantStart),
                ("Builder", Some("Work"), AgentStatus::CantStart),
            ]
        );
    }

    #[test]
    fn colours_follow_the_palette() {
        for (index, color) in AvatarColor::ALL.iter().enumerate() {
            assert_eq!(AgentColor::from(*color).hex(), PALETTE[index]);
            assert_eq!(AvatarColor::from(AgentColor::from(*color)), *color);
        }
    }

    #[test]
    fn removing_names_what_ends() {
        let ended = |work, decisions, routines| EndedWork {
            work,
            decisions,
            routines,
            ..EndedWork::default()
        };
        assert_eq!(
            removing_ends("Finance", &ended(1, 2, 1)),
            "Removing Finance stops 1 piece of work, ends 2 decisions waiting for you and 1 routine. Its threads stay."
        );
        assert_eq!(
            removing_ends("Bills", &ended(0, 1, 1)),
            "Removing Bills ends 1 decision waiting for you and 1 routine. Its threads stay."
        );
        assert_eq!(
            removing_ends("Bills", &ended(0, 0, 0)),
            "Removing Bills ends nothing that is running. Its threads stay."
        );
    }

    #[test]
    fn the_detail_says_how_the_agent_was_added() {
        let record = AgentRecord::new(
            "finance",
            AgentDefinition::new("Finance", "default"),
            AgentRecordState::Active,
            AgentOrigin::Suggested {
                agent: adk_core::AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap(),
                session: "s1".into(),
                run: None,
                unattended: false,
            },
            SubjectRef::agent(&adk_core::AgentId::new("urn:adk:agent:adk-rust/adk-rust").unwrap()),
            "2026-10-25T09:12:00Z".parse().unwrap(),
        )
        .with_approved_by(SubjectRef::human("ana"));
        let detail =
            AgentDetail::of(&record, None, "ana", "ADK-Rust", FixedOffset::east_opt(0).unwrap());
        assert_eq!(detail.origin_text, "Suggested by ADK-Rust, added by you on 25 Oct");
        assert_eq!(detail.state, AgentLife::Active);
        assert_eq!(detail.agent.avatar.color, AgentColor::from(record.color).hex());
    }

    #[test]
    fn the_card_shows_the_definition_in_full_from_the_inbox_entry() {
        let definition = AgentDefinition::new("Finance", "default")
            .with_mode(PartitionMode::Ask)
            .with_instructions("Read invoices.\nDraft reminders.")
            .with_uses(AgentUses::default().with_files(FileAccess::Read).with_folder("Invoices"));
        let call = adk_core::ToolConfirmationRequest::new(
            "kernel:agent.create",
            serde_json::to_value(&definition).unwrap(),
        );
        let request = adk_core::ApprovalRequest::new(
            "agent-finance-0123",
            adk_core::ApprovalScope::new("adk-rust", "ana", "s1"),
            &call,
            adk_core::ApprovalPolicy::new([adk_core::ApproverSelector::human("ana")]),
        );
        let card = AgentCardView::of_request(&request, "ADK-Rust", "Home").unwrap();
        let line =
            |label: &str| card.lines.iter().find(|line| line.label == label).unwrap().value.clone();
        assert_eq!(line("Area"), "Home");
        assert_eq!(line("How much it asks first"), "Asks first");
        assert_eq!(line("Files"), "Reads files in Invoices");
        assert_eq!(line("Shell"), "No shell");
        // Wave 3 finding 36: the card never claims a difference from the suggester it cannot
        // check; the kernel kept the suggestion within the suggester's limits.
        assert_eq!(
            card.compared.as_deref(),
            Some("It can do no more than ADK-Rust, and has no shell or web.")
        );
        assert_eq!(card.allowed_without_asking, NOTHING_YET);
        assert!(!card.instructions_truncated);
    }
}