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
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
//! Projection: inbox entries, session events, process states and ledger rows become cards,
//! thread items, agent rows, status and briefing lines, once, in Rust (spec 3.3 ยง6, ยง7.1, ยง8).

use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::sync::Arc;

use adk_core::{
    ApprovalAction, ApprovalRequest, ApprovalState, Event, Part, RunState, ToolConfirmationRequest,
};
use adk_harness::HarnessMode;
use adk_harness::take_over::TAKE_OVER_TOOL;
use adk_kernel::control::api::{AwayKind, AwayLine};
use adk_kernel::proc::{KERNEL_AGENT, LedgerEntry};
use adk_kernel::{AGENDA_TOOL_NAME, AgendaItem, AgendaOrigin, QuietHours, Wake};
use chrono::{DateTime, FixedOffset, TimeZone, Utc};
use serde_json::Value;

use crate::answers::AnswerRecord;
use crate::hints::CardHint;
use crate::model::{
    AgentRef, AgentRow, AgentStatus, Avatar, BriefingLine, CallView, CardStatus, CommandRun,
    Decided, DecidedAnswer, DecisionCard, ElicitationView, ElicitedField, ElicitedKind,
    ElicitedOption, FeedEntry, Mode, ModeView, OutputLine, Pill, QuietView, Reversibility, RunStop,
    ShellView, Speaker, SpendView, ThreadItem, TimelineStep,
};
use crate::origin::{Caller, SurfaceKind};
use crate::rules::{self, Answer, DecisionFacts};
use crate::source::{AgentState, SpendToday, TurnFailure};
use crate::words::{self, SaidWhat};

/// How long a call's text may be before it is shown truncated (spec 3.3 ยง7.1).
pub const CALL_TEXT_LIMIT: usize = 2_000;

/// The most lines of a run's output a thread shows: its last ones (spec 3.3 ยง5.1).
pub const RUN_LINES: usize = 40;

/// The most characters of one output line a thread shows.
const RUN_LINE_CHARS: usize = 400;

/// The most characters of a failed turn's reason a thread shows.
const REASON_CHARS: usize = 500;

/// The longest agent name a decision card shows, in characters.
pub const CARD_NAME_LIMIT: usize = 64;
/// The longest heading a decision card shows, in characters.
pub const CARD_HEADING_LIMIT: usize = 160;
/// The longest summary, step, detail or "also shown" line a decision card shows.
pub const CARD_LINE_LIMIT: usize = 280;

/// The most fields of an MCP elicitation form a card draws; a longer form is refused there.
const ELICITED_FIELDS_LIMIT: usize = 24;
/// The most options of an elicitation field a card draws.
const ELICITED_OPTIONS_LIMIT: usize = 50;

/// The server of a decision a harness parked for an MCP elicitation
/// (`mcp:{server}/elicitation`).
pub(crate) fn elicitation_server(tool: &str) -> Option<&str> {
    tool.strip_prefix("mcp:")?.strip_suffix("/elicitation")
}

/// What an MCP server asks in `request`, for the home to draw in its own controls: a form
/// when every field is one the home draws (text, email, web address, date, number, yes or no,
/// a choice), the page of a URL elicitation, `None` otherwise (the card then offers Deny).
pub(crate) fn elicitation_of(request: &ApprovalRequest) -> Option<ElicitationView> {
    let server = capped(elicitation_server(&request.tool_name)?, CARD_NAME_LIMIT);
    let shown = &request.args_redacted;
    let message = capped(shown.get("message").and_then(Value::as_str)?, CARD_LINE_LIMIT);
    if let Some(url) = shown.get("url").and_then(Value::as_str) {
        let (host, warning) = address_parts(url)?;
        return Some(ElicitationView::Url {
            server,
            message,
            url: url.to_string(),
            host,
            warning: warning.map(str::to_string),
        });
    }
    let schema = shown.get("schema")?;
    let properties = schema.get("properties")?.as_object()?;
    if properties.len() > ELICITED_FIELDS_LIMIT {
        return None;
    }
    let required: Vec<&str> = schema
        .get("required")
        .and_then(Value::as_array)
        .map(|names| names.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let fields = properties
        .iter()
        .map(|(name, property)| elicited_field(name, property, required.contains(&name.as_str())))
        .collect::<Option<Vec<_>>>()?;
    Some(ElicitationView::Form { server, message, fields })
}

/// One field of an elicitation schema, or `None` for a kind the home does not draw.
fn elicited_field(name: &str, property: &Value, required: bool) -> Option<ElicitedField> {
    let text = |key: &str| property.get(key).and_then(Value::as_str);
    let mut options = Vec::new();
    if let Some(values) = property.get("enum").and_then(Value::as_array) {
        let names = property.get("enumNames").and_then(Value::as_array);
        for (index, value) in values.iter().enumerate() {
            let value = value.as_str()?;
            let label = names.and_then(|names| names.get(index)).and_then(Value::as_str);
            options.push((value, label.unwrap_or(value)));
        }
    } else if let Some(choices) =
        property.get("oneOf").or_else(|| property.get("anyOf")).and_then(Value::as_array)
    {
        for choice in choices {
            let value = choice.get("const").and_then(Value::as_str)?;
            let label = choice.get("title").and_then(Value::as_str).unwrap_or(value);
            options.push((value, label));
        }
    }
    if options.len() > ELICITED_OPTIONS_LIMIT {
        return None;
    }
    let kind = if options.is_empty() {
        match text("type")? {
            "string" => match text("format") {
                Some("email") => ElicitedKind::Email,
                Some("uri") => ElicitedKind::Url,
                Some("date") => ElicitedKind::Date,
                Some("date-time") => ElicitedKind::DateTime,
                _ => ElicitedKind::Text,
            },
            "number" => ElicitedKind::Number,
            "integer" => ElicitedKind::Integer,
            "boolean" => ElicitedKind::Boolean,
            _ => return None,
        }
    } else {
        ElicitedKind::Choice
    };
    let default = property.get("default").filter(|value| !value.is_object() && !value.is_array());
    Some(ElicitedField {
        name: name.to_string(),
        label: capped(text("title").unwrap_or(name), CARD_NAME_LIMIT),
        description: text("description").map(|description| capped(description, CARD_LINE_LIMIT)),
        kind,
        required,
        default: default.cloned(),
        options: options
            .into_iter()
            .map(|(value, label)| ElicitedOption {
                value: value.to_string(),
                label: capped(label, CARD_NAME_LIMIT),
            })
            .collect(),
        minimum: property.get("minimum").and_then(Value::as_f64),
        maximum: property.get("maximum").and_then(Value::as_f64),
        min_length: property.get("minLength").and_then(Value::as_u64),
        max_length: property.get("maxLength").and_then(Value::as_u64),
    })
}

/// Checks the person's answer to an elicitation form against the fields the card drew: an
/// object of those fields only, every required one present, each of its kind, a choice one of
/// its options, numbers and lengths within bounds. The harness checks it again against the
/// server's schema before the server sees it.
pub(crate) fn check_answer(fields: &[ElicitedField], content: &Value) -> Result<(), String> {
    let answer = content.as_object().ok_or("the answer is an object of the form's fields")?;
    if let Some(unknown) = answer.keys().find(|key| !fields.iter().any(|f| &f.name == *key)) {
        return Err(format!("{unknown} is not a field of the form"));
    }
    for field in fields {
        let Some(value) = answer.get(&field.name) else {
            if field.required {
                return Err(format!("{} is required", field.label));
            }
            continue;
        };
        let fits = match field.kind {
            ElicitedKind::Number => value.is_number(),
            ElicitedKind::Integer => value.is_i64() || value.is_u64(),
            ElicitedKind::Boolean => value.is_boolean(),
            ElicitedKind::Choice => value
                .as_str()
                .is_some_and(|picked| field.options.iter().any(|option| option.value == picked)),
            _ => value.is_string(),
        };
        if !fits {
            return Err(format!("{} does not take {value}", field.label));
        }
        if let Some(number) = value.as_f64()
            && (field.minimum.is_some_and(|min| number < min)
                || field.maximum.is_some_and(|max| number > max))
        {
            return Err(format!("{} is out of its range", field.label));
        }
        if let Some(text) = value.as_str() {
            let length = text.chars().count() as u64;
            if field.min_length.is_some_and(|min| length < min)
                || field.max_length.is_some_and(|max| length > max)
            {
                return Err(format!("{} is too short or too long", field.label));
            }
        }
    }
    Ok(())
}

/// The host of `url`, lowercased, and why to look twice at it: look-alike characters
/// (punycode or non-ASCII), a name hidden before an `@`, or no encryption.
fn address_parts(url: &str) -> Option<(String, Option<&'static str>)> {
    let (scheme, rest) = url.split_once("://")?;
    let authority = rest.split(['/', '?', '#']).next()?;
    let (userinfo, host_port) = match authority.rsplit_once('@') {
        Some((userinfo, host_port)) => (Some(userinfo), host_port),
        None => (None, authority),
    };
    let host = match host_port.strip_prefix('[') {
        Some(bracketed) => bracketed.split(']').next()?,
        None => host_port.split(':').next()?,
    }
    .to_lowercase();
    if host.is_empty() {
        return None;
    }
    let warning = if !host.is_ascii() || host.split('.').any(|label| label.starts_with("xn--")) {
        Some(words::LOOK_ALIKE_ADDRESS)
    } else if userinfo.is_some() {
        Some(words::HIDDEN_HOST_ADDRESS)
    } else if scheme.eq_ignore_ascii_case("http") {
        Some(words::UNENCRYPTED_ADDRESS)
    } else {
        None
    };
    Some((host, warning))
}

/// `text` cut to `limit` characters, with an ellipsis when cut.
pub(crate) fn capped(text: &str, limit: usize) -> String {
    if text.chars().count() <= limit {
        return text.to_string();
    }
    let mut cut: String = text.chars().take(limit.saturating_sub(1)).collect();
    cut.push('โ€ฆ');
    cut
}

/// Somewhere a decision is also shown, for "Also on your phone and in Telegram"
/// (spec 3.3 ยง7.1).
///
/// # Example
///
/// ```rust
/// use adk_surface::Place;
///
/// assert_eq!(Place::chat("Telegram").phrase, "in Telegram");
/// assert_eq!(Place::phone().phrase, "on your phone");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Place {
    /// The surface.
    pub surface: SurfaceKind,
    /// The place in words: "on your phone", "in Telegram".
    pub phrase: String,
}

impl Place {
    /// The web home.
    pub fn web() -> Self {
        Self { surface: SurfaceKind::Web, phrase: words::IN_THE_HOME_APP.to_string() }
    }

    /// The phone.
    pub fn phone() -> Self {
        Self { surface: SurfaceKind::Phone, phrase: words::ON_YOUR_PHONE.to_string() }
    }

    /// The terminal.
    pub fn terminal() -> Self {
        Self { surface: SurfaceKind::Terminal, phrase: words::IN_THE_TERMINAL.to_string() }
    }

    /// The desktop tray.
    pub fn tray() -> Self {
        Self { surface: SurfaceKind::Tray, phrase: words::FROM_THE_TRAY.to_string() }
    }

    /// A chat channel.
    pub fn chat(channel: &str) -> Self {
        Self { surface: SurfaceKind::Chat, phrase: words::in_channel(channel) }
    }
}

type Classify<T> = Arc<dyn Fn(&ApprovalRequest) -> T + Send + Sync>;

/// What the engine needs to project: the person's time zone, quiet time, where decisions are
/// shown, and how calls are read.
#[derive(Clone)]
pub(crate) struct Projector {
    pub(crate) offset: FixedOffset,
    pub(crate) quiet: Option<QuietHours>,
    pub(crate) places: Vec<Place>,
    pub(crate) names: BTreeMap<String, String>,
    pub(crate) heading: Classify<String>,
    pub(crate) money: Classify<bool>,
    /// Whether the source rates a call high risk whatever the request says (spec 3.2 K-I9).
    pub(crate) rates_high: Classify<bool>,
    pub(crate) reversibility: Classify<Reversibility>,
    /// The engine's cancel window for a spoken "allow once", in whole seconds, which a voice
    /// card advertises.
    pub(crate) voice_window_secs: u32,
    /// The catalogs drawings are shown in: `forms` and every registered extension catalog
    /// (spec 3.3 ยง6.1 `genui`).
    #[cfg(feature = "genui")]
    pub(crate) catalogs: crate::genui::Catalogs,
}

impl fmt::Debug for Projector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Projector")
            .field("offset", &self.offset)
            .field("quiet", &self.quiet)
            .field("places", &self.places)
            .finish_non_exhaustive()
    }
}

impl Projector {
    pub(crate) fn new(offset: FixedOffset) -> Self {
        Self {
            offset,
            quiet: None,
            places: Vec::new(),
            names: BTreeMap::new(),
            heading: Arc::new(heading),
            money: Arc::new(spends_money),
            rates_high: Arc::new(|_| false),
            reversibility: Arc::new(reversibility),
            voice_window_secs: rules::VOICE_CANCEL_WINDOW_SECS,
            #[cfg(feature = "genui")]
            catalogs: crate::genui::Catalogs::forms(),
        }
    }

    /// `at` as local `HH:MM`.
    pub(crate) fn hh_mm(&self, at: DateTime<Utc>) -> String {
        at.with_timezone(&self.offset).format("%H:%M").to_string()
    }

    pub(crate) fn agent(&self, name: &str) -> AgentRef {
        let display_name = self.names.get(name).cloned().unwrap_or_else(|| humanize(name));
        AgentRef { name: name.to_string(), avatar: avatar(&display_name), display_name }
    }

    /// The agent a suggestion would add, as its card shows it (spec 3.3 ยง5.7): `None` for
    /// every other request.
    pub(crate) fn adds_agent(
        &self,
        request: &ApprovalRequest,
    ) -> Option<crate::agents::AgentCardView> {
        if request.tool_name != adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
            return None;
        }
        let suggester = self.agent(&agent_name(request)).display_name;
        let area = request.args_redacted.get("area").and_then(Value::as_str).unwrap_or_default();
        crate::agents::AgentCardView::of_request(
            request,
            &suggester,
            &crate::agents::area_name(area),
        )
    }

    /// The facts the ยง7.2 rules read. A feature's `hint` may only make them stricter: mark
    /// money or take **Always allow** away, never add an answer or change the risk
    /// (spec 3.3 ยง7.1, ยง7.2).
    pub(crate) fn facts(
        &self,
        request: &ApprovalRequest,
        always_label: Option<String>,
        hint: &CardHint,
    ) -> DecisionFacts {
        // A suggested agent is added or not, never always or edited (spec 3.3 ยง7.2); long
        // instructions are expanded before it is added, as a long call is (S-I13).
        if let Some(agent) = self.adds_agent(request) {
            let assessed = adk_kernel::agents::AgentRecord::new(
                String::new(),
                agent.draft.clone().into_definition(),
                adk_kernel::agents::AgentRecordState::Proposed,
                adk_kernel::agents::AgentOrigin::ByHand,
                adk_core::principal::SubjectRef::human(&request.scope.user_id),
                request.created_at,
            );
            return DecisionFacts {
                risk: request.risk.into(),
                money: adk_harness::assess_agent(&assessed).money || hint.marks_money(),
                truncated: agent.instructions_truncated,
                allows: request
                    .allowed_actions
                    .iter()
                    .copied()
                    .filter(|action| {
                        matches!(action, ApprovalAction::Approve | ApprovalAction::Reject)
                    })
                    .collect(),
                always_label: None,
                adds_agent: true,
                image: None,
                plan: false,
            };
        }
        // Edit replaces the call's arguments with what the surface sends back, so it is
        // offered only where the card shows those arguments (spec 3.3 ยง7.2): never over a
        // redacted view or an elicitation's form, which would be submitted as written. A take
        // over is answered with the secret the person types, or refused (ยง8.2, ยง10 H2).
        let own_args = shows_own_arguments(request);
        let take_over = request.tool_name == TAKE_OVER_TOOL;
        let answers_a_form = matches!(elicitation_of(request), Some(ElicitationView::Form { .. }));
        let risk = if (self.rates_high)(request) {
            request.risk.max(adk_core::ApprovalRisk::High)
        } else {
            request.risk
        };
        DecisionFacts {
            risk: risk.into(),
            money: (self.money)(request) || hint.marks_money(),
            truncated: call_view(request).truncated,
            allows: request
                .allowed_actions
                .iter()
                .copied()
                .filter(|action| match action {
                    ApprovalAction::Reject => true,
                    // An elicitation form is answered with the person's own values, drawn
                    // in the home's fields and checked against the server's schema.
                    ApprovalAction::Edit => (own_args || answers_a_form) && !take_over,
                    ApprovalAction::Approve | ApprovalAction::Respond => !take_over,
                })
                .collect(),
            always_label: always_label.filter(|_| !take_over && !hint.removes_always()),
            adds_agent: false,
            image: None,
            plan: false,
        }
    }

    pub(crate) fn decided(
        &self,
        request: &ApprovalRequest,
        caller: &Caller,
        answer: Option<&AnswerRecord>,
    ) -> Option<Decided> {
        if request.state == ApprovalState::Pending {
            return None;
        }
        let last = request.decisions.last();
        let answer_kind = match request.state {
            ApprovalState::Approved => match last.map(|decision| decision.kind) {
                Some(ApprovalAction::Edit) => DecidedAnswer::Edited,
                _ => DecidedAnswer::Yes,
            },
            ApprovalState::Rejected => DecidedAnswer::No,
            ApprovalState::Responded => DecidedAnswer::Replied,
            ApprovalState::Pending | ApprovalState::Expired | ApprovalState::Cancelled => {
                DecidedAnswer::Ended
            }
        };
        let at = last
            .map(|decision| decision.decided_at)
            .or(request.resolved_at)
            .unwrap_or(request.created_at);
        let at_text = self.hh_mm(at);
        let approver = last.filter(|_| answer_kind != DecidedAnswer::Ended);
        let by_you = approver.is_some_and(|decision| decision.approver.id == caller.user_id());
        let by = match approver {
            Some(_) if by_you => "You".to_string(),
            Some(decision) => decision.approver.id.clone(),
            None => String::new(),
        };
        let via = answer
            .filter(|record| {
                record.approval_id == request.id
                    && approver.is_some_and(|decision| decision.approver == record.by)
            })
            .map(|record| record.via.clone());
        let said = match answer_kind {
            DecidedAnswer::Yes => Some(SaidWhat::Yes),
            DecidedAnswer::No => Some(SaidWhat::No),
            DecidedAnswer::Edited => Some(SaidWhat::Edited),
            DecidedAnswer::Replied => Some(SaidWhat::Replied),
            DecidedAnswer::Ended | DecidedAnswer::Unknown => None,
        };
        let text = match said {
            Some(what) => {
                let phrase = via.as_ref().map(crate::origin::Via::phrase);
                words::said((!by_you).then_some(by.as_str()), what, phrase.as_deref(), &at_text)
            }
            None => words::ENDED_WITHOUT_AN_ANSWER.to_string(),
        };
        Some(Decided { by, by_you, via, at, at_text, answer: answer_kind, text, scope_text: None })
    }

    /// The card of `request` as `caller` sees it (spec 3.3 ยง7.1), with a feature's `hint`
    /// ahead of the engine's own headings and reversibility.
    pub(crate) fn card(
        &self,
        request: &ApprovalRequest,
        caller: &Caller,
        always_label: Option<String>,
        answer: Option<&AnswerRecord>,
        now: DateTime<Utc>,
        hint: &CardHint,
    ) -> DecisionCard {
        let facts = self.facts(request, always_label, hint);
        let chat = rules::row(caller) == rules::Row::Chat;
        // A chat card leaves the machine through someone else's servers: it carries the
        // agent, the risk and a short summary, never the call's arguments (S-I5).
        let (heading, summary, call) = if chat {
            let full = call_view(request);
            let call = CallView {
                tool: full.tool.clone(),
                args: Value::Null,
                text: full.tool,
                truncated: full.truncated,
            };
            let heading = hint.chat_heading.clone().unwrap_or_else(|| chat_heading(request));
            (heading, None, call)
        } else {
            // What an MCP server asks reads as its question ("MCP server billing asks: โ€ฆ"),
            // the summary the harness wrote, not as the tool name it was parked under.
            let asked = elicitation_server(&request.tool_name)
                .map(|_| request.summary.trim())
                .filter(|summary| !summary.is_empty())
                .map(str::to_string);
            let heading = hint.heading.clone().or(asked).unwrap_or_else(|| (self.heading)(request));
            (heading, self.kernel_summary(request, now), call_view(request))
        };
        let decided = self.decided(request, caller, answer);
        let mut allowed = rules::allowed_answers(caller, &facts);
        // The window the engine waits, not the default, so a voice renderer counts down the
        // time the answer can really still be cancelled.
        if allowed.cancel_window_secs.is_some() {
            allowed.cancel_window_secs = Some(self.voice_window_secs);
        }
        // A suggestion is done or left for now, a question confirmed or forgotten (ยง8.1).
        if let Some((yes, no)) = kernel_answer_words(request) {
            for option in &mut allowed.options {
                match option.answer {
                    Answer::AllowOnce if !option.needs_presence => option.label = yes.to_string(),
                    Answer::Deny => option.label = no.to_string(),
                    Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit => {}
                }
            }
        }
        // What an MCP server asks is drawn in the home's own fields; Edit sends the answer.
        let elicitation = if chat { None } else { elicitation_of(request) };
        if matches!(elicitation, Some(ElicitationView::Form { .. })) {
            for option in &mut allowed.options {
                if option.answer == Answer::Edit {
                    option.label = words::ANSWER.to_string();
                }
            }
        }
        if decided.is_some() {
            allowed.options.clear();
            allowed.open_in_home = false;
            allowed.cancel_window_secs = None;
            allowed.note = None;
        }
        let since = self.hh_mm(request.created_at);
        let mut timeline: Vec<String> = hint.first_step.iter().cloned().collect();
        timeline.push(words::asked_at(&since));
        let until = decided.as_ref().map_or(now, |decided| decided.at);
        if self.waited_through_quiet(request.created_at, until) {
            timeline.push(words::WAITED_THROUGH_QUIET_TIME.to_string());
        }
        timeline.push(match &decided {
            Some(decided) => decided.text.clone(),
            None => words::WAITING_FOR_YOU.to_string(),
        });
        let last = timeline.len() - 1;
        let timeline = timeline
            .into_iter()
            .enumerate()
            .map(|(index, text)| TimelineStep { text, current: index == last })
            .collect();
        let adds_agent = self.adds_agent(request);
        let reversibility = match adds_agent {
            Some(_) => Reversibility::CanBeRemoved,
            None => hint.reversibility.unwrap_or_else(|| (self.reversibility)(request)),
        };
        let also: Vec<String> = self
            .places
            .iter()
            .filter(|place| place.surface != caller.surface)
            .map(|place| place.phrase.clone())
            .collect();
        let (status, status_text) = match decided {
            Some(_) => (CardStatus::Decided, words::DECIDED),
            None => (CardStatus::Waiting, words::WAITING_FOR_YOU),
        };
        let mut card = DecisionCard {
            id: request.id.clone(),
            version: request.version,
            session_id: request.scope.session_id.clone(),
            agent: self.agent(&agent_name(request)),
            waiting_since: request.created_at,
            since_text: words::since(&since),
            status,
            status_text: status_text.to_string(),
            heading,
            summary,
            call,
            timeline,
            allowed,
            risk: facts.risk,
            risk_text: facts.risk.words().to_string(),
            reversibility,
            reversibility_text: match reversibility {
                Reversibility::CantBeUnsent => words::CANT_BE_UNSENT,
                Reversibility::CantBeUndone => words::CANT_BE_UNDONE,
                Reversibility::CanBeRemoved => crate::agents::words::YOU_CAN_REMOVE_IT_LATER,
                Reversibility::CanBeChangedBack => words::YOU_CAN_CHANGE_IT_BACK,
            }
            .to_string(),
            money: facts.money,
            also_shown: words::also_shown(&also),
            decided,
            adds_agent,
            // Like the summary, never on a chat card (S-I5).
            detail: hint.detail.clone().filter(|_| !chat),
            elicitation,
            media: None,
            parked: None,
            plan: None,
        };
        // Every line of the card fits: nothing a name or a hint carries can push the call and
        // its answers out of sight, or pass a long text off as the home's own words.
        card.agent.display_name = capped(&card.agent.display_name, CARD_NAME_LIMIT);
        card.heading = capped(&card.heading, CARD_HEADING_LIMIT);
        card.summary = card.summary.map(|summary| capped(&summary, CARD_LINE_LIMIT));
        for step in &mut card.timeline {
            step.text = capped(&step.text, CARD_LINE_LIMIT);
        }
        card.also_shown = card.also_shown.map(|also| capped(&also, CARD_LINE_LIMIT));
        if let Some(detail) = &mut card.detail {
            detail.text = capped(&detail.text, CARD_LINE_LIMIT);
        }
        card
    }

    /// What a decision the kernel itself asks means for the person, beyond its heading: who
    /// suggests an agenda item and when it runs once allowed, what a driver mount starts
    /// (spec 3.3 ยง7.1, ยง8.1). `None` for every other call, whose heading says it all.
    pub(crate) fn kernel_summary(
        &self,
        request: &ApprovalRequest,
        now: DateTime<Utc>,
    ) -> Option<String> {
        let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
        if request.tool_name == AGENDA_TOOL_NAME {
            let Some(item) = agenda_item(request) else {
                return Some(words::AGENTS_SUGGEST.to_string());
            };
            if item.origin.is_question() {
                return Some(words::NOTICED_SOMETHING.to_string());
            }
            let who = match &item.origin {
                AgendaOrigin::User => words::YOU_SUGGESTED_THIS.to_string(),
                AgendaOrigin::Agent { .. } => {
                    words::suggested_by(Some(&self.agent(&agent_name(request)).display_name))
                }
                // Consolidation, and any origin a later kernel adds: the kernel's own work.
                _ => words::suggested_by(None),
            };
            let when = match &item.when {
                Some(wake) => self.wake_words(wake, now),
                None => words::RIGHT_AWAY.to_string(),
            };
            let mut text = format!("{who} {}", words::once_you_say_yes(&when));
            if let Some(steps) = item.plan.as_ref().map(|plan| plan.steps.len()).filter(|n| *n > 0)
            {
                text.push(' ');
                text.push_str(&words::plan_of(steps));
            }
            if let Some(cap) = item.budget.as_ref().and_then(|budget| budget.max_cost_micro_usd) {
                text.push(' ');
                text.push_str(&words::may_spend(cap));
            }
            return Some(text);
        }
        if operation != DRIVER_MOUNT_OPERATION {
            return None;
        }
        request.args_redacted.get("commandLine").and_then(Value::as_str).map(words::driver_starts)
    }

    /// When a wake fires, in words, after "it runs": "every 5 minutes", "at 07:30".
    fn wake_words(&self, wake: &Wake, now: DateTime<Utc>) -> String {
        match wake {
            Wake::At(at) if *at <= now => words::RIGHT_AWAY.to_string(),
            Wake::At(at) => {
                let local = at.with_timezone(&self.offset);
                let today = now.with_timezone(&self.offset).date_naive();
                let time = local.format("%H:%M");
                if local.date_naive() == today {
                    format!("at {time}")
                } else if today.succ_opt() == Some(local.date_naive()) {
                    format!("tomorrow at {time}")
                } else {
                    format!("on {} at {time}", local.format("%a %-d %b"))
                }
            }
            Wake::Cron { expr, .. } => self.cron_words(expr, now),
            Wake::FileChange { root, glob, .. } => {
                format!("when a file matching {glob} changes in {}", root.display())
            }
            Wake::Webhook { hook } => format!("when {hook} calls in"),
            Wake::Queue { source } => format!("when a message arrives from {source}"),
            Wake::Approval { .. } => "once a decision it waits on is answered".to_string(),
            Wake::RunFinished { .. } => "after another of your agents' tasks finishes".to_string(),
            Wake::BudgetReplenished { .. } => "once the day's budget allows it".to_string(),
            Wake::Manual => "when you start it".to_string(),
            // A wake a later kernel adds.
            _ => "later".to_string(),
        }
    }

    /// A cron schedule (UTC, five fields, or six or seven from the second) in words, in the
    /// person's time zone: "every 5 minutes", "every weekday at 07:00"; any other schedule
    /// as it is written.
    fn cron_words(&self, expr: &str, now: DateTime<Utc>) -> String {
        let written = || format!("on the schedule {expr}");
        let all: Vec<&str> = expr.split_whitespace().collect();
        let fields = match all.len() {
            5 => &all[..],
            6 | 7 if all[0] == "0" && all.get(6).is_none_or(|year| *year == "*") => &all[1..6],
            _ => return written(),
        };
        let &[minute, hour, day, month, weekday] = fields else {
            return written();
        };
        let every = |field: &str| match field {
            "*" => Some(1),
            _ => field.strip_prefix("*/").and_then(|step| step.parse::<u32>().ok()),
        };
        let number = |field: &str| field.parse::<u32>().ok();
        if day != "*" || month != "*" {
            return written();
        }
        match (every(minute), number(minute), every(hour), number(hour)) {
            (Some(1), _, Some(1), _) if weekday == "*" => "every minute".to_string(),
            (Some(step), _, Some(1), _) if weekday == "*" => format!("every {step} minutes"),
            (_, Some(_), Some(1), _) if weekday == "*" => "every hour".to_string(),
            (_, Some(_), Some(step), _) if weekday == "*" => format!("every {step} hours"),
            (_, Some(minute), _, Some(hour)) => {
                let Some(at) = now.date_naive().and_hms_opt(hour, minute, 0) else {
                    return written();
                };
                let at = Utc.from_utc_datetime(&at);
                let local = at.with_timezone(&self.offset);
                let time = local.format("%H:%M");
                let days = match weekday.to_ascii_uppercase().as_str() {
                    "*" => "every day".to_string(),
                    // Another day where the person lives: the days would read wrong.
                    _ if local.date_naive() != at.date_naive() => return written(),
                    // Six and seven fields number the days as the `cron` crate does (1 is
                    // Sunday); only five follow Unix cron (`adk_core::schedule`).
                    other if all.len() != 5 && other.bytes().any(|b| b.is_ascii_digit()) => {
                        return written();
                    }
                    "1-5" | "MON-FRI" => "every weekday".to_string(),
                    other => match WEEKDAYS.iter().find(|(number, name, _)| {
                        *number == other || name.eq_ignore_ascii_case(other)
                    }) {
                        Some((_, _, day)) => format!("every {day}"),
                        None => return written(),
                    },
                };
                format!("{days} at {time}")
            }
            _ => written(),
        }
    }

    /// Whether `[from, until]` overlaps quiet time.
    pub(crate) fn waited_through_quiet(&self, from: DateTime<Utc>, until: DateTime<Utc>) -> bool {
        let Some(quiet) = self.quiet else {
            return false;
        };
        if quiet.contains(from) || quiet.contains(until) {
            return true;
        }
        let offset = self.quiet_offset(&quiet);
        let first = from.with_timezone(&offset).date_naive();
        let last = until.with_timezone(&offset).date_naive();
        let mut day = first;
        while day <= last {
            if let Some(start) = offset.from_local_datetime(&day.and_time(quiet.start)).earliest()
                && start > from
                && start <= until
            {
                return true;
            }
            day = match day.succ_opt() {
                Some(next) => next,
                None => break,
            };
        }
        false
    }

    fn quiet_offset(&self, quiet: &QuietHours) -> FixedOffset {
        quiet
            .utc_offset_minutes
            .and_then(|minutes| FixedOffset::east_opt(minutes * 60))
            .unwrap_or(self.offset)
    }

    pub(crate) fn quiet_view(&self, now: DateTime<Utc>) -> Option<QuietView> {
        let quiet = self.quiet?;
        if quiet.start == quiet.end {
            return None;
        }
        let start = quiet.start.format("%H:%M").to_string();
        let end = quiet.end.format("%H:%M").to_string();
        let active = quiet.contains(now);
        let text = if active { words::quiet_until(&end) } else { words::quiet_from(&start) };
        Some(QuietView { active, start, end, text })
    }

    /// The event at `seq`, its held call linked to the decision [`links`] gives that `seq`;
    /// `answered` holds the calls the session's later events answer ([`answered_calls`]).
    pub(crate) fn entry(
        &self,
        seq: u64,
        event: &Event,
        links: &HashMap<u64, Link>,
        answered: &HashSet<String>,
    ) -> FeedEntry {
        FeedEntry {
            seq,
            at: event.timestamp,
            at_text: self.hh_mm(event.timestamp),
            items: self.items(event, links.get(&seq), answered),
        }
    }

    /// The thread item of a turn that ended in an error: who could not answer and why. The
    /// runtime records an error as `component.category: message`; the message is the reason
    /// and the rest its code.
    pub(crate) fn turn_failed(&self, failure: &TurnFailure) -> ThreadItem {
        let error = failure.error.as_deref().map(str::trim).filter(|error| !error.is_empty());
        let (code, reason) = match error.map(|error| (error, error.split_once(": "))) {
            Some((_, Some((code, message))))
                if code.split('.').count() == 2
                    && code.chars().all(|c| c.is_ascii_lowercase() || c == '_' || c == '.') =>
            {
                (Some(code.to_string()), Some(message.trim()))
            }
            Some((error, _)) => (None, Some(error)),
            None => (None, None),
        };
        let reason = reason.map(|reason| match reason.char_indices().nth(REASON_CHARS) {
            Some((cut, _)) => format!("{}โ€ฆ", &reason[..cut]),
            None => reason.to_string(),
        });
        ThreadItem::TurnFailed {
            text: words::couldnt_answer(&self.agent(&failure.agent).display_name),
            reason,
            code,
        }
    }

    fn items(
        &self,
        event: &Event,
        link: Option<&Link>,
        answered: &HashSet<String>,
    ) -> Vec<ThreadItem> {
        let mut items = Vec::new();
        let from_person = event.author == "user";
        // A call a person asked for through a drawn form (spec 3.3 ยง7.4 rule 5).
        let requested = crate::genui::requested_via(event);
        if let Some(content) = &event.llm_response.content {
            let mut text = String::new();
            // The images a person sent with the message (spec 3.3 ยง5.1).
            let mut images = Vec::new();
            for part in &content.parts {
                match part {
                    Part::Text { text: chunk } if !event.llm_response.partial => {
                        text.push_str(chunk);
                    }
                    Part::InlineData { mime_type, data, .. } if from_person => {
                        images.extend(crate::images::shown(mime_type, data));
                    }
                    // The person's own call: its DrawnSent item shows it, not the agent's work.
                    Part::FunctionCall { id, .. }
                        if requested.is_some() && crate::genui::is_requested(id.as_ref()) => {}
                    // Replies an agent suggests: shown under its message, never as its work.
                    Part::FunctionCall { name, args, id, .. }
                        if name == crate::suggest::SUGGEST_REPLIES_TOOL =>
                    {
                        if let Ok(replies) = crate::suggest::replies_of(args) {
                            items.push(ThreadItem::Suggestions { replies, call_id: id.clone() });
                        }
                    }
                    Part::FunctionCall { name, args, id, .. } => {
                        items.push(ThreadItem::Activity {
                            tool: name.clone(),
                            text: describe_call(name, args),
                            call_id: id.clone(),
                        });
                    }
                    // A held call's placeholder answer: its Decision item shows it.
                    Part::FunctionResponse { function_response, .. }
                        if adk_core::is_confirmation_pending(&function_response.response) => {}
                    // The suggestions' own answer says nothing to the person.
                    Part::FunctionResponse { function_response, .. }
                        if function_response.name == crate::suggest::SUGGEST_REPLIES_TOOL => {}
                    // A call a person asked for that the agent's rules refused before holding it.
                    Part::FunctionResponse { function_response, id: Some(id), .. }
                        if requested.is_some() && crate::genui::is_requested(Some(id)) =>
                    {
                        if let Some(via) = &requested {
                            items.push(crate::genui::sent(
                                via,
                                &function_response.name,
                                id,
                                event,
                                &self.hh_mm(event.timestamp),
                                Some(&self.agent(&event.author).display_name),
                                None,
                            ));
                        }
                    }
                    Part::FunctionResponse { function_response, id, .. } => {
                        // A drawing, or a refused one, when the event proves a render tool
                        // made it (spec 3.3 ยง7.4 rule 5).
                        #[cfg(feature = "genui")]
                        {
                            if let Some(item) = crate::genui::project(
                                self,
                                event,
                                &function_response.name,
                                &function_response.response,
                                id.as_ref(),
                            ) {
                                items.push(item);
                                continue;
                            }
                        }
                        let ok = !response_failed(&function_response.response);
                        let text = if !ok
                            && crate::genui::is_requested(id.as_ref())
                            && crate::genui::refused_on_resume(
                                &function_response.name,
                                &function_response.response,
                            ) {
                            words::cant_use_any_more(
                                &self.agent(&event.author).display_name,
                                &function_response.name,
                            )
                        } else if ok {
                            words::DONE.to_string()
                        } else {
                            words::FAILED.to_string()
                        };
                        // A perception call's answer opens in the annotated viewer.
                        let image = (ok
                            && crate::viewer::answers_about_image(&function_response.name))
                        .then(|| function_response.response.get("image").and_then(Value::as_str))
                        .flatten()
                        .filter(|digest| digest.starts_with("sha256:"))
                        .map(str::to_string);
                        // A command or code that ran: what it wrote, and how it exited.
                        match command_run(&function_response.name, &function_response.response) {
                            Some(run) => {
                                let ok = ok
                                    && run.exit_code.is_none_or(|code| code == 0)
                                    && run.stopped.is_none();
                                let text = if ok { words::DONE } else { words::FAILED };
                                items.push(ThreadItem::Run {
                                    tool: function_response.name.clone(),
                                    call_id: id.clone(),
                                    ok,
                                    text: text.to_string(),
                                    run,
                                });
                            }
                            None => items.push(ThreadItem::Result {
                                tool: function_response.name.clone(),
                                call_id: id.clone(),
                                ok,
                                text,
                                image,
                            }),
                        }
                    }
                    _ => {}
                }
            }
            let text = text.trim();
            // The event that holds a call carries the runtime's own notice, not the agent's
            // words: its Decision item says it plainly (ยง8). A requested call's line is for
            // the model; its DrawnSent item says it to the person.
            if (!text.is_empty() || !images.is_empty())
                && event.actions.tool_confirmation.is_none()
                && requested.is_none()
            {
                let message = if from_person {
                    ThreadItem::Message {
                        from: Speaker::You,
                        author: "You".to_string(),
                        // An app's suggestion the person sent reads as its words and label.
                        text: crate::genui::suggested_message(text)
                            .unwrap_or_else(|| text.to_string()),
                        images,
                    }
                } else {
                    ThreadItem::Message {
                        from: Speaker::Agent,
                        author: self.agent(&event.author).display_name,
                        text: text.to_string(),
                        images: Vec::new(),
                    }
                };
                items.insert(0, message);
            }
        }
        if let Some(held) = &event.actions.tool_confirmation {
            // "Waiting for you" only while the caller's own decision is open (ยง8.1); a call
            // routed to other approvers, or to no one, waits for an answer; one answered since
            // is decided.
            let ran = held.function_call_id.as_ref().is_some_and(|id| answered.contains(id));
            let text = match link {
                Some(link) if link.pending && !ran => words::WAITING_FOR_YOU,
                Some(_) => words::DECIDED,
                None if ran => words::DECIDED,
                None => words::WAITING_FOR_AN_ANSWER,
            };
            if let (Some(via), Some(call_id)) = (&requested, &held.function_call_id) {
                items.push(crate::genui::sent(
                    via,
                    &held.tool_name,
                    call_id,
                    event,
                    &self.hh_mm(event.timestamp),
                    None,
                    link.map(|link| link.id.clone()),
                ));
            }
            items.push(ThreadItem::Decision {
                decision_id: link.map(|link| link.id.clone()),
                tool: held.tool_name.clone(),
                text: text.to_string(),
            });
        }
        items
    }

    pub(crate) fn agent_row(&self, state: &AgentState) -> AgentRow {
        let (status, status_text) = match state.state {
            RunState::Running | RunState::Queued => {
                (AgentStatus::Working, words::WORKING.to_string())
            }
            RunState::Waiting if state.waiting_on_decision && !state.suspended => {
                (AgentStatus::WaitingForYou, words::WAITING_FOR_YOU.to_string())
            }
            RunState::Waiting => match state.wake_at.filter(|_| !state.suspended) {
                Some(at) => (AgentStatus::Asleep, words::asleep_until(&self.hh_mm(at))),
                None => (AgentStatus::Asleep, words::ASLEEP.to_string()),
            },
            RunState::Completed | RunState::Cancelled => {
                (AgentStatus::Done, words::DONE.to_string())
            }
            RunState::Failed => (AgentStatus::Failed, words::FAILED.to_string()),
            // A state a later runtime adds shows as idle, never as working or done.
            _ => (AgentStatus::Asleep, words::ASLEEP.to_string()),
        };
        // A background sub-agent's row says whose work it is (its name, from its parent).
        let status_text = match &state.subagent {
            Some(name) => format!("{status_text} ยท sub-agent {name}"),
            None => status_text,
        };
        AgentRow {
            agent: self.agent(&state.name),
            status,
            status_text,
            wake_at: state.wake_at.filter(|_| status == AgentStatus::Asleep && !state.suspended),
            session_id: state.session_id.clone(),
            area: None,
            mode: None,
            added: false,
            can_change: false,
            shell: state
                .shell
                .clone()
                .map(|place| ShellView { text: words::commands_run(&place), place }),
        }
    }

    /// The line of "While you were away" a ledger row makes, or `None` for a row that is no
    /// event of its own (spec 3.3 ยง5.1, ยง10 K4): the line the kernel's `GET /kernel/away`
    /// lists for it ([`AwayLine`]), so every surface shows the same lines and the kernel's
    /// own housekeeping (wakes, its processes' state changes) is never one.
    pub(crate) fn briefing_line(&self, entry: &LedgerEntry) -> Option<BriefingLine> {
        let line = AwayLine::of(entry)?;
        // A decision says which answer it was, whether its row is the harness's or the kernel's.
        let denied = line.effect.as_deref() == Some("deny");
        let at = entry.utc();
        let agent = self.ledger_agent(&entry.agent);
        let who = agent.clone().unwrap_or_else(|| words::YOUR_AGENTS.to_string());
        // The `/proc` ledger writes the state a process entered as the row's effect (spec 3.2
        // ยง7.10); the loop guard's row carries none.
        let failed = entry.effect.as_deref() == Some("failed");
        // Mid-sentence, as the object of the decision.
        let whom = agent.as_deref().unwrap_or("your agents");
        let (pill, text) = match line.kind {
            AwayKind::Done => (Some(Pill::Done), words::briefing_sentence("turn", &who)),
            AwayKind::Failed if failed => (Some(Pill::Failed), format!("{who} failed.")),
            AwayKind::Failed => (Some(Pill::Failed), words::briefing_sentence("loop_guard", &who)),
            AwayKind::Stopped => (None, format!("{who} was stopped.")),
            AwayKind::Suggestion => match &agent {
                Some(agent) => {
                    (Some(Pill::Suggestion), words::briefing_sentence("proposal", agent))
                }
                None => (Some(Pill::Suggestion), words::AGENTS_SUGGEST.to_string()),
            },
            AwayKind::Question => (Some(Pill::Question), words::NOTICED_SOMETHING.to_string()),
            AwayKind::Decided if denied => {
                (Some(Pill::YouDecided), words::briefing_sentence("rejection", whom))
            }
            AwayKind::Decided => {
                (Some(Pill::YouDecided), words::briefing_sentence("approval", whom))
            }
            AwayKind::StoppedAll => (None, format!("{}.", words::ALL_AGENTS_STOPPED)),
            AwayKind::ResumedAll => (None, words::ALL_AGENTS_RESUMED.to_string()),
            // A kind a later kernel adds says what kind of thing happened, never more.
            _ => (None, words::briefing_sentence("", &who)),
        };
        Some(BriefingLine {
            seq: entry.seq,
            at,
            at_text: self.hh_mm(at),
            agent: who,
            pill,
            pill_text: pill.map(|pill| pill_words(pill).to_string()),
            text,
        })
    }

    /// The display name of the agent a ledger row names: its acting identity
    /// (`urn:adk:agent:{app}/{agent}`) or its target, as the roster names it; `None` for the
    /// kernel's own work, which no agent did.
    fn ledger_agent(&self, label: &str) -> Option<String> {
        if label == KERNEL_AGENT || label.is_empty() {
            return None;
        }
        let name = label.rsplit(['/', ':']).next().filter(|name| !name.is_empty()).unwrap_or(label);
        Some(self.agent(name).display_name)
    }
}

fn pill_words(pill: Pill) -> &'static str {
    match pill {
        Pill::Done => words::DONE,
        Pill::Failed => words::FAILED,
        Pill::WaitingForYou => words::WAITING_FOR_YOU,
        Pill::YouDecided => words::YOU_DECIDED,
        Pill::Suggestion => words::SUGGESTION,
        Pill::Question => words::QUESTION,
    }
}

/// The mode with its ยง8.1 words.
pub(crate) fn mode_view(mode: HarnessMode) -> ModeView {
    let (mode, label) = match mode {
        HarnessMode::ReadOnly => (Mode::JustLook, words::JUST_LOOK),
        HarnessMode::Plan => (Mode::Suggest, words::SUGGEST),
        HarnessMode::Auto => (Mode::GoAhead, words::GO_AHEAD),
        // Ask, and any mode a later harness adds, reads as the default.
        _ => (Mode::AskFirst, words::ASK_FIRST),
    };
    ModeView { mode, label: label.to_string(), status: words::mode_status(label) }
}

/// The harness mode a ยง8.1 mode word sets.
pub(crate) fn harness_mode(mode: Mode) -> HarnessMode {
    match mode {
        Mode::JustLook => HarnessMode::ReadOnly,
        Mode::Suggest => HarnessMode::Plan,
        Mode::AskFirst => HarnessMode::Ask,
        Mode::GoAhead => HarnessMode::Auto,
    }
}

pub(crate) fn spend_view(spend: SpendToday) -> SpendView {
    let text = match spend.limit {
        Some(limit) => words::spent_of(spend.spent, limit),
        None => words::spent_today(spend.spent),
    };
    SpendView { spent_micro_usd: spend.spent, limit_micro_usd: spend.limit, text }
}

/// The agent a request is from: the acting agent's name, else the application.
pub(crate) fn agent_name(request: &ApprovalRequest) -> String {
    request
        .acting
        .as_ref()
        .map(|acting| {
            let id = acting.agent.id.as_str();
            id.rsplit(['/', ':']).next().unwrap_or(id).to_string()
        })
        .filter(|name| !name.is_empty())
        .unwrap_or_else(|| request.scope.app_name.clone())
}

/// The decision a held call links to in a thread.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Link {
    /// The request's id.
    pub(crate) id: String,
    /// The request is still open.
    pub(crate) pending: bool,
}

/// How far apart a request's creation and the event that held its call may be and still be
/// one moment: the inbox writes the request just before or after the session writes the event.
const HOLD_SLACK_MS: i64 = 1_000;

/// Calls held closer together than this were held in one model turn and link in event order.
const ONE_TURN_MS: i64 = 500;

/// The calls `events` answer: every function response that is not a held call's placeholder,
/// by call ID.
pub(crate) fn answered_calls(events: &[Event]) -> HashSet<String> {
    events
        .iter()
        .filter_map(|event| event.llm_response.content.as_ref())
        .flat_map(|content| &content.parts)
        .filter_map(|part| match part {
            Part::FunctionResponse { function_response, id, .. }
                if !adk_core::is_confirmation_pending(&function_response.response) =>
            {
                id.clone()
            }
            _ => None,
        })
        .collect()
}

/// The decision of each held call in a session's `events`, by the event's `seq` (its position
/// from 1), out of the session's `requests` (spec 3.3 ยง7.1).
///
/// A request with a fingerprint decides the calls held with that fingerprint. A request
/// served without one, as a kernel's approvals inbox serves them, decides a call of the same
/// tool by the same acting agent. Calls link in two passes over the session: first each call
/// to the request showing its exact arguments, then each call still unlinked to the earliest
/// request still free, since a route may show approvers redacted arguments โ€” unless a later
/// call, held in another turn by the time that request was written, is the one it belongs to.
/// No request decides two calls, so a call whose own request is missing (unrouted, or not the
/// caller's to decide) links to none rather than to another call's, whether that call's
/// arguments are shown or redacted. A call held again keeps its request unless that request
/// was resolved before the call was held again.
pub(crate) fn links(events: &[Event], requests: &[ApprovalRequest]) -> HashMap<u64, Link> {
    let mut order: Vec<&ApprovalRequest> = requests.iter().collect();
    order.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
    let holds: Vec<(u64, &ToolConfirmationRequest, chrono::DateTime<Utc>, String)> = events
        .iter()
        .enumerate()
        .filter_map(|(index, event)| {
            let held = event.actions.tool_confirmation.as_ref()?;
            Some((index as u64 + 1, held, event.timestamp, held.fingerprint()))
        })
        .collect();
    let decides = |request: &ApprovalRequest,
                   held: &ToolConfirmationRequest,
                   fingerprint: &str,
                   exact: bool| {
        match request.fingerprint.is_empty() {
            false => exact && request.fingerprint == fingerprint,
            true => {
                let agent = held.acting.as_deref().map(|acting| &acting.agent.id);
                request.tool_name == held.tool_name
                    && match (agent, &request.acting) {
                        (Some(agent), Some(acting)) => *agent == acting.agent.id,
                        _ => true,
                    }
                    && (!exact || request.args_redacted == held.args)
            }
        }
    };
    let mut taken = vec![false; order.len()];
    let mut linked: HashMap<u64, usize> = HashMap::new();
    for exact in [true, false] {
        let mut held_by: HashMap<&str, usize> = HashMap::new();
        for (hold, (seq, held, at, fingerprint)) in holds.iter().enumerate() {
            if let Some(&position) = linked.get(seq) {
                held_by.insert(fingerprint, position);
                continue;
            }
            // Whether `request` belongs to a later call of another turn: one still unlinked,
            // not a call held again under its open request, held by the time the request was
            // written.
            let later_owner = |request: &ApprovalRequest| {
                holds[hold + 1..].iter().enumerate().any(|(offset, (other, call, when, print))| {
                    let inherits = holds[..hold + 1 + offset].iter().any(|(earlier, _, _, p)| {
                        p == print
                            && linked.get(earlier).is_some_and(|&position| {
                                order[position].resolved_at.is_none_or(|at| at > *when)
                            })
                    });
                    !linked.contains_key(other)
                        && print != fingerprint
                        && !inherits
                        && *when > *at + chrono::Duration::milliseconds(ONE_TURN_MS)
                        && *when
                            <= request.created_at + chrono::Duration::milliseconds(HOLD_SLACK_MS)
                        && decides(request, call, print, false)
                })
            };
            let kept = held_by.get(fingerprint.as_str()).copied();
            let next = match kept {
                // Held again while its request was still open, as the event's time shows,
                // not the request's state now.
                Some(position)
                    if order[position].resolved_at.is_none_or(|resolved| resolved > *at) =>
                {
                    Some(position)
                }
                _ => (0..order.len())
                    .find(|&position| {
                        !taken[position]
                            && decides(order[position], held, fingerprint, exact)
                            && (exact || !later_owner(order[position]))
                    })
                    .or(kept),
            };
            if let Some(position) = next {
                taken[position] = true;
                held_by.insert(fingerprint, position);
                linked.insert(*seq, position);
            }
        }
    }
    linked
        .into_iter()
        .map(|(seq, position)| {
            let request = order[position];
            (seq, Link { id: request.id.clone(), pending: request.state == ApprovalState::Pending })
        })
        .collect()
}

/// `full`, cut short past [`CALL_TEXT_LIMIT`] characters, and whether it was.
pub(crate) fn cut_call_text(full: String) -> (String, bool) {
    if full.chars().count() <= CALL_TEXT_LIMIT {
        return (full, false);
    }
    let mut cut: String = full.chars().take(CALL_TEXT_LIMIT).collect();
    cut.push('โ€ฆ');
    (cut, true)
}

/// The exact call, cut short past [`CALL_TEXT_LIMIT`] characters.
pub(crate) fn call_view(request: &ApprovalRequest) -> CallView {
    let (text, truncated) = cut_call_text(call_text(&request.tool_name, &request.args_redacted));
    CallView {
        tool: request.tool_name.clone(),
        args: request.args_redacted.clone(),
        text,
        truncated,
    }
}

/// The arguments the inbox shows are the call's own (`ApprovalRequest::shows_call_args`). A
/// source that serves no fingerprints, the approvals API, removes Edit itself where they are
/// not (`inbox::request_of`).
fn shows_own_arguments(request: &ApprovalRequest) -> bool {
    request.fingerprint.is_empty() || request.shows_call_args()
}

/// `tool(key: value, โ€ฆ)`, each value as JSON, keys in sorted order.
fn call_text(tool: &str, args: &Value) -> String {
    match args {
        Value::Object(map) => {
            // Sorted, so the text is the same whether serde_json keeps insertion order
            // (`preserve_order`, which a workspace build turns on) or not.
            let mut entries: Vec<(&String, &Value)> = map.iter().collect();
            entries.sort_by(|a, b| a.0.cmp(b.0));
            let fields: Vec<String> =
                entries.into_iter().map(|(key, value)| format!("{key}: {value}")).collect();
            format!("{tool}({})", fields.join(", "))
        }
        Value::Null => format!("{tool}()"),
        other => format!("{tool}({other})"),
    }
}

/// What will happen, in plain words, from the call: "Write file note.txt",
/// "Send email to [client email]" (spec 3.3 ยง7.1, ยง8 "Name the outcome"). A decision the
/// kernel itself asks is named by what it is about, never by the kernel's tool or its JSON:
/// an agenda item by its title.
pub(crate) fn heading(request: &ApprovalRequest) -> String {
    // A take over says what to type, in the words of the tool that asks (spec 3.3 ยง8.2).
    if request.tool_name == TAKE_OVER_TOOL && !request.summary.trim().is_empty() {
        return request.summary.clone();
    }
    if let Some(operation) = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX) {
        // The kernel's heading of a suggested agent, never the model's (spec 3.3 S-I13).
        if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
            let name = request
                .args_redacted
                .get("displayName")
                .and_then(Value::as_str)
                .unwrap_or_default();
            return crate::agents::words::add_an_agent_called(name);
        }
        if request.tool_name == AGENDA_TOOL_NAME {
            return match agenda_item(request) {
                Some(item) if !item.title.trim().is_empty() => sentence(&item.title),
                Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
                Some(_) | None => words::SUGGESTION.to_string(),
            };
        }
        if operation == DRIVER_MOUNT_OPERATION
            && let Some(id) = request.args_redacted.get("id").and_then(Value::as_str)
        {
            return words::start_driver(id);
        }
        return humanize(operation);
    }
    describe_call(&request.tool_name, &request.args_redacted)
}

/// What a chat card says will happen: the tool in plain words, "Write file", "Send email" โ€”
/// never its arguments, since a chat card leaves the machine (spec 3.3 ยง7.1, S-I5). The
/// kernel's own decisions say what kind they are: "Suggestion", "Question".
pub(crate) fn chat_heading(request: &ApprovalRequest) -> String {
    if request.tool_name == AGENDA_TOOL_NAME {
        return match agenda_item(request) {
            Some(item) if item.origin.is_question() => words::QUESTION.to_string(),
            Some(_) | None => words::SUGGESTION.to_string(),
        };
    }
    humanize(request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX).unwrap_or(&request.tool_name))
}

/// What a decision the kernel itself asks is about, as the person knows it โ€” the agent a
/// suggestion adds, the agenda item's title, the driver a mount starts โ€” for the record of an
/// answer to it, which never names the kernel's tool (spec 3.3 ยง8, ยง11).
pub(crate) fn kernel_name(request: &ApprovalRequest) -> Option<String> {
    let operation = request.tool_name.strip_prefix(KERNEL_TOOL_PREFIX)?;
    let name = if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
        request.args_redacted.get("displayName").and_then(Value::as_str).map(str::to_string)
    } else if request.tool_name == AGENDA_TOOL_NAME {
        agenda_item(request).map(|item| item.title)
    } else if operation == DRIVER_MOUNT_OPERATION {
        request.args_redacted.get("id").and_then(Value::as_str).map(str::to_string)
    } else {
        None
    };
    name.map(|name| name.trim().to_string()).filter(|name| !name.is_empty())
}

/// The prefix of the inbox tools of decisions the kernel itself asks, not an agent's call:
/// `kernel:agenda`, `kernel:driver.mount`.
const KERNEL_TOOL_PREFIX: &str = "kernel:";

/// The operation of a driver mount a hosted definition asks for
/// (`adk_kernel::managed::DRIVER_MOUNT_TOOL_NAME`, behind the kernel's `managed` feature).
const DRIVER_MOUNT_OPERATION: &str = "driver.mount";

/// Cron weekdays: their number, their name, and their name in words.
const WEEKDAYS: [(&str, &str, &str); 8] = [
    ("0", "SUN", "Sunday"),
    ("1", "MON", "Monday"),
    ("2", "TUE", "Tuesday"),
    ("3", "WED", "Wednesday"),
    ("4", "THU", "Thursday"),
    ("5", "FRI", "Friday"),
    ("6", "SAT", "Saturday"),
    ("7", "SUN", "Sunday"),
];

/// The agenda item an agenda proposal carries (`adk_kernel::AGENDA_TOOL_NAME`): the item is
/// its arguments.
fn agenda_item(request: &ApprovalRequest) -> Option<AgendaItem> {
    (request.tool_name == AGENDA_TOOL_NAME)
        .then(|| serde_json::from_value(request.args_redacted.clone()).ok())
        .flatten()
}

/// The words of "allow once" and "deny" on a decision the kernel asks: a suggestion is done
/// or left for now, a question is right or forgotten (spec 3.3 ยง8.1, ยง8.2).
fn kernel_answer_words(request: &ApprovalRequest) -> Option<(&'static str, &'static str)> {
    if request.tool_name != AGENDA_TOOL_NAME {
        return None;
    }
    match agenda_item(request) {
        Some(item) if item.origin.is_question() => Some((words::THATS_RIGHT, words::FORGET_IT)),
        Some(_) | None => Some((words::DO_IT, words::NOT_NOW)),
    }
}

/// `text` on one line, starting with a capital: a title in sentence case (spec 3.3 ยง8).
fn sentence(text: &str) -> String {
    let line = text.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut chars = line.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().chain(chars).collect(),
        None => line,
    }
}

/// The argument a heading names, short enough for one line.
fn primary_argument(args: &Value) -> Option<(&'static str, String)> {
    const KEYS: [&str; 9] =
        ["to", "path", "file", "url", "command", "recipient", "name", "query", "title"];
    let map = args.as_object()?;
    KEYS.iter().find_map(|key| {
        let value = map.get(*key)?.as_str()?.trim();
        if value.is_empty() {
            return None;
        }
        let mut short: String = value.chars().take(60).collect();
        if value.chars().count() > 60 {
            short.push('โ€ฆ');
        }
        Some((*key, short))
    })
}

/// Whether a call spends money: the payment tools `adk-payments` publishes, all named
/// `payments_*` (spec 3.1 ยง7.16), or a request whose route marks it.
pub(crate) fn spends_money(request: &ApprovalRequest) -> bool {
    request.tool_name.starts_with("payments_")
}

/// Whether a call can be taken back, from its name: messages can't be unsent; everything
/// else is shown as not undoable, since a surface cannot know better (spec 3.3 ยง7.1).
pub(crate) fn reversibility(request: &ApprovalRequest) -> Reversibility {
    let name = request.tool_name.to_lowercase();
    let sends = ["send", "email", "mail", "message", "sms", "post", "reply", "notify", "publish"];
    if sends.iter().any(|word| name.contains(word)) {
        Reversibility::CantBeUnsent
    } else {
        Reversibility::CantBeUndone
    }
}

/// A short line for a tool call in a thread: "Read file timesheet-october.csv".
fn describe_call(tool: &str, args: &Value) -> String {
    let mut text = humanize(tool);
    if let Some((key, value)) = primary_argument(args) {
        text.push(' ');
        if key == "to" {
            text.push_str("to ");
        }
        text.push_str(&value);
    }
    text
}

fn response_failed(response: &Value) -> bool {
    response.get("error").is_some()
        || response
            .get("status")
            .and_then(Value::as_str)
            .is_some_and(|status| matches!(status, "error" | "failed" | "denied" | "not_run"))
}

/// `send_email` โ†’ "Send email"; `chiefOfStaff` โ†’ "Chief of staff".
pub(crate) fn humanize(name: &str) -> String {
    let mut words: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut previous_lower = false;
    for c in name.chars() {
        if matches!(c, '_' | '-' | ' ' | '.' | ':' | '/') {
            if !current.is_empty() {
                words.push(std::mem::take(&mut current));
            }
            previous_lower = false;
            continue;
        }
        if c.is_uppercase() && previous_lower && !current.is_empty() {
            words.push(std::mem::take(&mut current));
        }
        previous_lower = c.is_lowercase() || c.is_ascii_digit();
        current.extend(c.to_lowercase());
    }
    if !current.is_empty() {
        words.push(current);
    }
    let mut text = words.join(" ");
    if let Some(first) = text.get(..1) {
        let upper = first.to_uppercase();
        text.replace_range(..1, &upper);
    }
    if text.is_empty() { name.to_string() } else { text }
}

/// A monogram in the agent's own colour (spec 3.3 ยง9).
fn avatar(display_name: &str) -> Avatar {
    const COLORS: [&str; 8] =
        ["#C03A00", "#15803D", "#1D4ED8", "#7C3AED", "#475569", "#B45309", "#0E7490", "#BE185D"];
    let monogram: String = display_name
        .chars()
        .find(|c| c.is_alphanumeric())
        .map(|c| c.to_uppercase().collect())
        .unwrap_or_default();
    let hash = display_name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
        (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
    });
    let index = usize::try_from(hash % COLORS.len() as u64).unwrap_or(0);
    Avatar { monogram, color: COLORS[index].to_string() }
}

/// The run a tool's result describes, for a shell's `bash` (`command`, `exit_code`, `stdout`,
/// `stderr`, `truncated`) and the sandbox's `sandbox_exec` (`status`, `stdout`, `stderr`,
/// `exit_code`, `duration_ms`); `None` for any other result (spec 3.3 ยง5.1). The call's own
/// command comes from the result where the tool repeats it.
fn command_run(tool: &str, response: &serde_json::Value) -> Option<CommandRun> {
    let object = response.as_object()?;
    let has_output = object.contains_key("stdout") || object.contains_key("stderr");
    let shell = object.contains_key("command") && object.contains_key("exit_code");
    let sandbox = tool == "sandbox_exec" && (has_output || object.contains_key("status"));
    if !(sandbox || shell && has_output) {
        return None;
    }
    let string = |key: &str| object.get(key).and_then(serde_json::Value::as_str).unwrap_or("");
    let stopped = match string("status") {
        "timeout" => Some(RunStop::Timeout),
        "memory_exceeded" => Some(RunStop::MemoryExceeded),
        "policy_violation" => Some(RunStop::PolicyViolation),
        "error" => Some(RunStop::Error),
        _ => None,
    };
    let line = |text: &str, stderr: bool| OutputLine {
        text: if text.chars().count() > RUN_LINE_CHARS {
            format!("{}โ€ฆ", text.chars().take(RUN_LINE_CHARS).collect::<String>())
        } else {
            text.to_string()
        },
        stderr,
    };
    let mut all: Vec<OutputLine> = string("stdout").lines().map(|text| line(text, false)).collect();
    all.extend(string("stderr").lines().map(|text| line(text, true)));
    let lines = u32::try_from(all.len()).unwrap_or(u32::MAX);
    let output = all.split_off(all.len().saturating_sub(RUN_LINES));
    let command = Some(string("command")).filter(|command| !command.is_empty());
    Some(CommandRun {
        command: command.map(|command| command.chars().take(CALL_TEXT_LIMIT).collect()),
        language: object.get("language").and_then(serde_json::Value::as_str).map(str::to_string),
        exit_code: object
            .get("exit_code")
            .and_then(serde_json::Value::as_i64)
            .and_then(|code| i32::try_from(code).ok()),
        duration_ms: object.get("duration_ms").and_then(serde_json::Value::as_u64),
        output,
        lines,
        truncated: object.get("truncated").and_then(serde_json::Value::as_bool).unwrap_or(false),
        stopped,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_long_line_is_cut_with_an_ellipsis_and_a_short_one_kept() {
        assert_eq!(capped("Finance", CARD_NAME_LIMIT), "Finance");
        let long = "x".repeat(CARD_NAME_LIMIT + 50);
        let cut = capped(&long, CARD_NAME_LIMIT);
        assert_eq!(cut.chars().count(), CARD_NAME_LIMIT);
        assert!(cut.ends_with('โ€ฆ'));
    }
    use adk_core::{ApprovalPolicy, ApprovalScope, ToolConfirmationRequest};
    use chrono::{Duration, NaiveTime};
    use serde_json::json;

    fn time(hh: u32, mm: u32) -> NaiveTime {
        NaiveTime::from_hms_opt(hh, mm, 0).unwrap()
    }

    fn minutes(minutes: i64) -> Duration {
        Duration::minutes(minutes)
    }

    fn request(tool: &str, args: Value) -> ApprovalRequest {
        let call = ToolConfirmationRequest {
            tool_name: tool.into(),
            function_call_id: Some("c1".into()),
            args,
            origin: None,
            acting: None,
            evidence: Vec::new(),
        };
        ApprovalRequest::new(
            "apr_1",
            ApprovalScope::new("app", "ana", "s1"),
            &call,
            ApprovalPolicy::new([]),
        )
    }

    #[test]
    fn headings_name_the_outcome() {
        assert_eq!(
            heading(&request("send_email", json!({ "to": "[client email]" }))),
            "Send email to [client email]"
        );
        assert_eq!(
            heading(&request("write_file", json!({ "path": "note.txt", "content": "x" }))),
            "Write file note.txt"
        );
        assert_eq!(humanize("chiefOfStaff"), "Chief of staff");
    }

    /// A proposal of the kernel's agenda, as `Agenda::submit` puts it to the inbox.
    fn agenda(item: &AgendaItem) -> ApprovalRequest {
        let args = serde_json::to_value(item).unwrap();
        let request = request(AGENDA_TOOL_NAME, args.clone())
            .with_redacted_args(args)
            .with_summary(format!("Agenda follow-up: {}", item.title));
        if item.origin.is_question() {
            request.with_allowed_actions([ApprovalAction::Approve, ApprovalAction::Reject])
        } else {
            request.with_allowed_actions([
                ApprovalAction::Approve,
                ApprovalAction::Edit,
                ApprovalAction::Reject,
            ])
        }
    }

    fn item(title: &str, origin: AgendaOrigin) -> AgendaItem {
        AgendaItem::new(
            "item-1",
            adk_core::principal::SubjectRef::human("ana"),
            title,
            "worth doing",
            origin,
            Utc.with_ymd_and_hms(2026, 10, 25, 7, 3, 0).unwrap(),
        )
    }

    /// The owner's 07:03 demo: a decision the kernel asks reads in plain words โ€” who suggests
    /// it, what it does, when it runs โ€” and never as the kernel's tool or its JSON (spec 3.3
    /// ยง7.1, ยง8).
    #[test]
    fn kernel_decisions_read_in_plain_words() {
        let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
        projector.names.insert("app".into(), "Finance".into());
        let now = Utc.with_ymd_and_hms(2026, 10, 25, 4, 3, 0).unwrap();
        let agent = AgendaOrigin::Agent { pid: "run-7".into(), confidence: 1.0 };
        let cron =
            |expr: &str| Wake::Cron { expr: expr.into(), missed: adk_core::MissedFirePolicy::Skip };
        let cases = [
            (
                item("check the news every 5 minutes", agent.clone())
                    .with_when(cron("*/5 * * * *")),
                "Check the news every 5 minutes",
                "Finance suggests this. Once you say yes, it runs every 5 minutes.",
            ),
            // 04:00 UTC is 07:00 for a person at UTC+3.
            (
                item("Read the overnight mail", agent.clone()).with_when(cron("0 0 4 * * MON-FRI")),
                "Read the overnight mail",
                "Finance suggests this. Once you say yes, it runs every weekday at 07:00.",
            ),
            // Five fields number the days as Unix cron does, so 1-5 is Monday to Friday and
            // 0 is Sunday; six number them as the `cron` crate does, where 1-5 starts on
            // Sunday, so its numbers are not read.
            (
                item("Send the standup", agent.clone()).with_when(cron("0 6 * * 1-5")),
                "Send the standup",
                "Finance suggests this. Once you say yes, it runs every weekday at 09:00.",
            ),
            (
                item("Plan the week", agent.clone()).with_when(cron("0 6 * * 0")),
                "Plan the week",
                "Finance suggests this. Once you say yes, it runs every Sunday at 09:00.",
            ),
            (
                item("Sum the week", agent.clone()).with_when(cron("0 0 6 * * 1-5")),
                "Sum the week",
                "Finance suggests this. Once you say yes, it runs on the schedule 0 0 6 * * 1-5.",
            ),
            (
                item("Book the dentist", agent.clone())
                    .with_when(Wake::At(Utc.with_ymd_and_hms(2026, 10, 26, 6, 30, 0).unwrap())),
                "Book the dentist",
                "Finance suggests this. Once you say yes, it runs tomorrow at 09:30.",
            ),
            (
                item("Tidy the notes", AgendaOrigin::Consolidation),
                "Tidy the notes",
                "Your agents suggest this. Once you say yes, it runs right away.",
            ),
            (
                item(
                    "You prefer morning meetings",
                    AgendaOrigin::Observation { id: "obs-1".into() },
                ),
                "You prefer morning meetings",
                "Your agents noticed something. Is that right?",
            ),
            (
                item("Archive", agent).with_when(cron("15 3 1 * *")),
                "Archive",
                "Finance suggests this. Once you say yes, it runs on the schedule 15 3 1 * *.",
            ),
        ];
        let me = Caller::human("ana", SurfaceKind::Web, crate::origin::Origin::Pointer);
        for (item, heading, summary) in cases {
            let card = projector.card(&agenda(&item), &me, None, None, now, &CardHint::new());
            assert_eq!((card.heading.as_str(), card.summary.as_deref()), (heading, Some(summary)));
            for text in [card.heading.as_str(), summary] {
                assert!(!text.contains("kernel") && !text.contains('{'), "{text}");
            }
            let labels: Vec<&str> = card.allowed.options.iter().map(|o| o.label.as_str()).collect();
            let expected: &[&str] = if item.origin.is_question() {
                &["That's right", "Forget it"]
            } else {
                &["Do it", "Edit", "Not now"]
            };
            assert_eq!(labels, expected, "{heading}");
        }

        // A driver mount names what it starts; any other kernel decision its operation.
        let mount = request(
            "kernel:driver.mount",
            json!({ "id": "email", "commandLine": "mcp-email --inbox", "partitions": ["default"] }),
        );
        assert_eq!(heading(&mount), "Start email for your agents");
        assert_eq!(
            projector.kernel_summary(&mount, now).as_deref(),
            Some("It runs mcp-email --inbox on the computer your agents run on.")
        );
        let other = request("kernel:quota.raise", json!({ "partition": "default" }));
        assert_eq!(
            (heading(&other), projector.kernel_summary(&other, now)),
            ("Quota raise".to_string(), None)
        );
        // An agenda request whose item cannot be read still names no internals.
        let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
        assert_eq!(heading(&unreadable), "Suggestion");
        assert_eq!(chat_heading(&unreadable), "Suggestion");
    }

    /// The record of an answer names a kernel decision by what it is about, never by the
    /// kernel's tool (spec 3.3 ยง8, ยง11).
    #[test]
    fn a_kernel_decision_is_named_by_what_it_is_about() {
        let added = request(
            adk_kernel::agents::AGENT_CREATE_TOOL_NAME,
            json!({ "name": "finance", "displayName": "Finance" }),
        );
        let mount = request("kernel:driver.mount", json!({ "id": "email" }));
        let unreadable = request(AGENDA_TOOL_NAME, json!({ "planHash": "sha256:00" }));
        let other = request("kernel:quota.raise", json!({ "partition": "default" }));
        let call = request("write_file", json!({ "path": "notes.md" }));
        assert_eq!(
            [&added, &mount, &unreadable, &other, &call].map(kernel_name),
            [Some("Finance".to_string()), Some("email".to_string()), None, None, None]
        );
    }

    #[test]
    fn long_calls_are_truncated_and_flagged() {
        let long = request("write_file", json!({ "content": "x".repeat(5_000) }));
        let view = call_view(&long);
        assert!(view.truncated);
        assert!(view.text.chars().count() <= CALL_TEXT_LIMIT + 1);
        assert!(!call_view(&request("write_file", json!({ "path": "a" }))).truncated);
    }

    #[test]
    fn quiet_time_in_the_timeline() {
        let mut projector = Projector::new(FixedOffset::east_opt(0).unwrap());
        projector.quiet = Some(QuietHours::new(time(22, 0), time(7, 0)).with_utc_offset_minutes(0));
        let asked = Utc.with_ymd_and_hms(2026, 10, 23, 18, 0, 0).unwrap();
        assert!(!projector.waited_through_quiet(asked, asked + minutes(60)));
        assert!(projector.waited_through_quiet(asked, asked + minutes(13 * 60 + 30)));
        let view = projector.quiet_view(asked).unwrap();
        assert_eq!(view.text, "Quiet from 22:00");
        assert_eq!(
            projector.quiet_view(asked + minutes(6 * 60)).unwrap().text,
            "Quiet until 07:00"
        );
    }

    #[test]
    fn a_failed_turn_says_who_could_not_answer_and_why() {
        let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
        let failed = |error: Option<&str>| {
            projector.turn_failed(&TurnFailure {
                agent: "claims_desk".into(),
                at: Utc::now(),
                error: error.map(str::to_string),
            })
        };
        let item = |reason: Option<&str>, code: Option<&str>| ThreadItem::TurnFailed {
            text: "Claims desk couldn't answer".into(),
            reason: reason.map(str::to_string),
            code: code.map(str::to_string),
        };
        assert_eq!(
            failed(Some("model.internal: no recorded answer for turn 3")),
            item(Some("no recorded answer for turn 3"), Some("model.internal"))
        );
        // Text that does not start with a code is the reason whole.
        assert_eq!(
            failed(Some("Upstream said: try later")),
            item(Some("Upstream said: try later"), None)
        );
        assert_eq!(failed(Some("  ")), item(None, None));
        assert_eq!(failed(None), item(None, None));
        let long = format!("model.unavailable: {}", "x".repeat(REASON_CHARS + 20));
        let ThreadItem::TurnFailed { reason: Some(reason), .. } = failed(Some(&long)) else {
            panic!("a reason");
        };
        assert_eq!(reason.chars().count(), REASON_CHARS + 1);
        assert!(reason.ends_with('โ€ฆ'));
    }

    #[test]
    fn agent_rows_say_what_each_agent_is_doing() {
        let projector = Projector::new(FixedOffset::east_opt(0).unwrap());
        let state = |state, waiting_on_decision, wake_at, suspended| AgentState {
            name: "chief_of_staff".into(),
            session_id: None,
            state,
            waiting_on_decision,
            wake_at,
            suspended,
            subagent: None,
            shell: None,
        };
        let seven = Some(Utc.with_ymd_and_hms(2026, 10, 24, 7, 0, 0).unwrap());
        let words = |row: AgentRow| (row.agent.display_name, row.status_text);
        assert_eq!(
            words(projector.agent_row(&state(RunState::Running, false, None, false))),
            ("Chief of staff".into(), "Working".into())
        );
        assert_eq!(
            projector.agent_row(&state(RunState::Waiting, true, None, false)).status_text,
            "Waiting for you"
        );
        assert_eq!(
            projector.agent_row(&state(RunState::Waiting, false, seven, false)).status_text,
            "Asleep until 07:00"
        );
        assert_eq!(
            projector.agent_row(&state(RunState::Waiting, false, seven, true)).status_text,
            "Asleep"
        );
        assert_eq!(
            projector.agent_row(&state(RunState::Completed, false, None, false)).status_text,
            "Done"
        );
        assert_eq!(
            projector.agent_row(&state(RunState::Failed, false, None, false)).status_text,
            "Failed"
        );
        let mut alpha = state(RunState::Waiting, true, None, false);
        alpha.subagent = Some("alpha".into());
        assert_eq!(
            projector.agent_row(&alpha).status_text,
            "Waiting for you ยท sub-agent alpha",
            "a background sub-agent's row names it"
        );
    }

    #[test]
    fn briefing_lines_come_from_ledger_rows() {
        let mut projector = Projector::new(FixedOffset::east_opt(3 * 3600).unwrap());
        projector.names.insert("adk-rust".into(), "ADK-Rust".into());
        let row = |kind: &str, agent: &str, effect: Option<&str>| -> LedgerEntry {
            serde_json::from_value(json!({
                "seq": 7,
                "ts": "2026-10-23T23:05:00+03:00",
                "partition": "default",
                "agent": agent,
                "kind": kind,
                "effect": effect,
            }))
            .unwrap()
        };
        let line = projector.briefing_line(&row("proposal", "kernel", Some("proposed"))).unwrap();
        assert_eq!(
            (line.at_text.as_str(), line.pill_text.as_deref(), line.seq),
            ("23:05", Some("Suggestion"), 7)
        );
        assert_eq!(line.text, "Your agents suggest something. Nothing happens until you say so.");
        let agent = "urn:adk:agent:adk-rust/adk-rust";
        let decided = projector.briefing_line(&row("decided", agent, Some("approve"))).unwrap();
        assert_eq!(
            (decided.pill_text.as_deref(), decided.text.as_str()),
            (Some("You decided"), "You allowed ADK-Rust to go ahead.")
        );
        // The person's answer recorded by the harness is the decision's row.
        let said_no = projector.briefing_line(&row("rejection", agent, None)).unwrap();
        assert_eq!(said_no.text, "You said no to ADK-Rust.");
        let question = projector.briefing_line(&row("observation", "kernel", None)).unwrap();
        assert_eq!(question.text, "Your agents noticed something. Is that right?");
        // The kernel's housekeeping and an agent's steps that are no event of their own make no
        // line.
        for (kind, agent, effect) in [
            ("wake", "kernel", Some("woke")),
            ("process", "kernel", Some("completed")),
            ("process", agent, Some("running")),
            ("spend", agent, None),
            ("intent", agent, None),
            ("tool_call", agent, None),
            ("proposal", "kernel", Some("running")),
        ] {
            assert_eq!(
                projector.briefing_line(&row(kind, agent, effect)),
                None,
                "{kind} {effect:?}"
            );
        }
    }
}