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
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
//! The in-process source (spec 3.3 §6): a kernel, a harness or a runner in the same process
//! as the surfaces, with the session store and the approval service they write.

use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use adk_artifact::{ArtifactService, VersionsRequest};
use adk_core::audit_log::AuditActor;
use adk_core::{
    ApprovalAction, ApprovalDecision, ApprovalRequest, ApprovalResolution, ApprovalService,
    ApprovalState, Content, DurableRunStore, ErrorCategory, Event, GovernanceControl,
    ImageEvidence, InboxQuery, NewRun, RequestContext, RequestedCall, RequestedVia,
    RunCheckpointRef, RunState, SessionId, UserId,
};
use adk_harness::{
    ArgSpec, Harness, HarnessMode, RuleOwner, RulePredicate, RuleSuggestion, StandingDecision,
    StandingRule, SuggestedScope,
};
use adk_kernel::proc::LedgerQuery;
use adk_kernel::{Kernel, ProcessFilter, ProcessKind, ProcessSpec, QueueClass, QuietHours};
use adk_runner::Runner;
use adk_session::{CreateRequest, GetRequest, SessionService};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::StreamExt;

use crate::error::{Result, SurfaceError};
use crate::evidence::{EvidenceBytes, EvidenceKept};
use crate::origin::Caller;
use crate::source::{
    AgentState, AlwaysAllowOffer, RuleCommit, Source, SpendToday, Steered, Steering, TurnFailure,
};
use crate::words;

/// How many inbox entries one page reads.
const INBOX_PAGE: usize = 200;

/// The action a call held again names as how the person asked for it.
const HELD_AGAIN_ACTION: &str = "held-again";

/// What the agent is told of a call whose image a person changed before it left.
#[cfg(feature = "web")]
const IMAGE_CHANGED_REASON: &str = "The person cut the image smaller or covered more of it \
    before it left. The call is held again with the new image for their answer.";

/// The engine's source for surfaces in the same process as the agents (spec 3.3 §6): the
/// session store the feed numbers events from, the approval service decisions go through,
/// and whichever of an in-process [`Kernel`], a [`Harness`] and a [`Runner`] runs the turns.
///
/// | Part | Gives the engine |
/// |---|---|
/// | [`sessions`](LocalSourceBuilder::sessions) | the feed (required; a harness or runner brings its own) |
/// | [`approvals`](LocalSourceBuilder::approvals) | decisions: the inbox and `decide` (S-I2) |
/// | [`kernel`](LocalSourceBuilder::kernel) | agents from the process table, turns as processes, a message for the turn this replica runs (`Kernel::steer`), stop and resume through the kernel's freeze, spend and its daily cap, quiet time, the `/proc` ledger |
/// | [`harness`](LocalSourceBuilder::harness) | the mode and `set_mode`, "Always allow" as a standing rule, turns, a message for a running turn and resuming decided calls without a kernel |
/// | [`runner`](LocalSourceBuilder::runner) | turns, a message for a running turn (`Runner::steer`), resuming decided calls, and the runner's kill switch, for apps without a harness |
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
/// use adk_session::InMemorySessionService;
/// use adk_surface::LocalSource;
///
/// let source = LocalSource::builder("adk-rust")
///     .sessions(Arc::new(InMemorySessionService::new()))
///     .approvals(Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))))
///     .build()
///     .unwrap();
/// # let _ = source;
/// ```
#[derive(Clone)]
pub struct LocalSource {
    app: String,
    sessions: Arc<dyn SessionService>,
    approvals: Option<Arc<dyn ApprovalService>>,
    kernel: Option<(Kernel, String)>,
    harness: Option<Arc<Harness>>,
    runner: Option<Arc<Runner>>,
    governance: Option<GovernanceControl>,
    daily_limit: Option<u64>,
    agents: Option<adk_kernel::agents::AgentsHandle>,
    artifacts: Option<Arc<dyn ArtifactService>>,
    runs: Option<Arc<dyn DurableRunStore>>,
    eval_fixtures: Option<std::path::PathBuf>,
    /// The rules "Always allow" prepared, granted as their decisions resolve.
    prepared: Arc<PreparedRules>,
    /// The turns a harness or runner ran here that ended in an error; a kernel keeps its own.
    failed: Arc<FailedTurnLog>,
}

impl fmt::Debug for LocalSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("LocalSource")
            .field("app", &self.app)
            .field("approvals", &self.approvals.is_some())
            .field("kernel", &self.kernel.as_ref().map(|(_, target)| target))
            .field("harness", &self.harness.is_some())
            .field("runner", &self.runner.is_some())
            .finish_non_exhaustive()
    }
}

/// Builds a [`LocalSource`].
#[derive(Default)]
pub struct LocalSourceBuilder {
    app: String,
    sessions: Option<Arc<dyn SessionService>>,
    approvals: Option<Arc<dyn ApprovalService>>,
    kernel: Option<(Kernel, String)>,
    harness: Option<Arc<Harness>>,
    runner: Option<Arc<Runner>>,
    governance: Option<GovernanceControl>,
    daily_limit: Option<u64>,
    agents: Option<adk_kernel::agents::AgentsHandle>,
    artifacts: Option<Arc<dyn ArtifactService>>,
    runs: Option<Arc<dyn DurableRunStore>>,
    eval_fixtures: Option<std::path::PathBuf>,
}

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

impl LocalSourceBuilder {
    /// The session store the agents write.
    #[must_use]
    pub fn sessions(mut self, sessions: Arc<dyn SessionService>) -> Self {
        self.sessions = Some(sessions);
        self
    }

    /// The approval service held calls are submitted to.
    #[must_use]
    pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
        self.approvals = Some(approvals);
        self
    }

    /// An in-process kernel, whose processes of `target` run the turns surfaces send.
    #[must_use]
    pub fn kernel(mut self, kernel: Kernel, target: impl Into<String>) -> Self {
        self.kernel = Some((kernel, target.into()));
        self
    }

    /// A harness: its runner's sessions and kill switch unless set, its modes and standing
    /// rules.
    #[must_use]
    pub fn harness(mut self, harness: Arc<Harness>) -> Self {
        self.harness = Some(harness);
        self
    }

    /// A runner for apps without a harness: its sessions and kill switch unless set.
    #[must_use]
    pub fn runner(mut self, runner: Arc<Runner>) -> Self {
        self.runner = Some(runner);
        self
    }

    /// The kill switch "Stop all" freezes when there is no kernel.
    #[must_use]
    pub fn governance(mut self, governance: GovernanceControl) -> Self {
        self.governance = Some(governance);
        self
    }

    /// The daily spending limit in micro-USD, over the one in force in the kernel's area of
    /// this source's turns.
    #[must_use]
    pub fn daily_limit(mut self, micro_usd: u64) -> Self {
        self.daily_limit = Some(micro_usd);
        self
    }

    /// The agent table of a kernel this source does not run turns on — a kernel built after
    /// the source, such as the one `adk-rust up` serves the terminal's commands for — so
    /// "Always allow" on an added agent's card makes a rule for that agent alone (spec 3.3
    /// S-I19). A [`kernel`](Self::kernel) brings its own.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_kernel::agents::AgentsHandle;
    /// use adk_session::InMemorySessionService;
    ///
    /// let source = adk_surface::LocalSource::builder("adk-rust")
    ///     .sessions(std::sync::Arc::new(InMemorySessionService::new()))
    ///     .agents(AgentsHandle::new())
    ///     .build()
    ///     .unwrap();
    /// # let _ = source;
    /// ```
    #[must_use]
    pub fn agents(mut self, agents: adk_kernel::agents::AgentsHandle) -> Self {
        self.agents = Some(agents);
        self
    }

    /// The artifact service a held call's evidence images live in (spec 3.7 §8.2): cards show
    /// them, each checked against its digest, and a person may cut one smaller or cover more
    /// of it before it leaves.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_artifact::InMemoryArtifactService;
    /// use adk_session::InMemorySessionService;
    ///
    /// let source = adk_surface::LocalSource::builder("desk")
    ///     .sessions(Arc::new(InMemorySessionService::new()))
    ///     .artifacts(Arc::new(InMemoryArtifactService::new()))
    ///     .build()
    ///     .unwrap();
    /// # let _ = source;
    /// ```
    #[must_use]
    pub fn artifacts(mut self, artifacts: Arc<dyn ArtifactService>) -> Self {
        self.artifacts = Some(artifacts);
        self
    }

    /// The durable run store whose runs wait on decisions: a decision whose run ended while it
    /// waits says its answer is used when the agent picks the thread up again (spec 3.7 §8.2,
    /// board choice A12).
    #[must_use]
    pub fn runs(mut self, runs: Arc<dyn DurableRunStore>) -> Self {
        self.runs = Some(runs);
        self
    }

    /// The folder labelled examples are saved under (spec 3.7 §8.2, board choice V13): the
    /// annotated viewer writes `adk-eval` cases to the `.test.json` files in it, and each
    /// case's image beside its file, so `cargo adk eval` reads them. Without it, the viewer
    /// shows answers and exports them but saves no examples.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use adk_artifact::InMemoryArtifactService;
    /// use adk_session::InMemorySessionService;
    ///
    /// let source = adk_surface::LocalSource::builder("desk")
    ///     .sessions(Arc::new(InMemorySessionService::new()))
    ///     .artifacts(Arc::new(InMemoryArtifactService::new()))
    ///     .eval_fixtures(std::env::temp_dir().join("evals"))
    ///     .build()
    ///     .unwrap();
    /// # let _ = source;
    /// ```
    #[must_use]
    pub fn eval_fixtures(mut self, root: impl Into<std::path::PathBuf>) -> Self {
        self.eval_fixtures = Some(root.into());
        self
    }

    /// The source.
    ///
    /// # Errors
    ///
    /// Returns `surface.invalid` when no session store was given and no harness or runner
    /// brings one.
    pub fn build(self) -> Result<LocalSource> {
        let runner_sessions = self
            .harness
            .as_ref()
            .map(|harness| harness.runner().session_service().clone())
            .or_else(|| self.runner.as_ref().map(|runner| runner.session_service().clone()));
        let sessions = self.sessions.or(runner_sessions).ok_or_else(|| {
            SurfaceError::Invalid(
                "a local source needs the session store the agents write: pass sessions(), a \
                 harness or a runner"
                    .into(),
            )
        })?;
        let governance = self.governance.or_else(|| {
            self.harness
                .as_ref()
                .map(|harness| harness.runner().governance().clone())
                .or_else(|| self.runner.as_ref().map(|runner| runner.governance().clone()))
        });
        // A rule "Always allow" prepared is granted as its author's yes resolves the decision,
        // before the call it allowed resumes: on a kernel the decision itself wakes the run
        // (spec 3.3 §7.2).
        let prepared = Arc::new(PreparedRules::default());
        if let Some(harness) = &self.harness {
            let decided_by = self
                .approvals
                .clone()
                .or_else(|| harness.agent().runtime().approval_service().cloned());
            if let Some(service) = decided_by {
                service.add_resolution(prepared.clone());
            }
        }
        Ok(LocalSource {
            app: self.app,
            sessions,
            approvals: self.approvals,
            kernel: self.kernel,
            harness: self.harness,
            runner: self.runner,
            governance,
            daily_limit: self.daily_limit,
            agents: self.agents,
            artifacts: self.artifacts,
            runs: self.runs,
            eval_fixtures: self.eval_fixtures,
            prepared,
            failed: Arc::default(),
        })
    }
}

impl LocalSource {
    /// A builder for the sessions of `app_name`.
    pub fn builder(app_name: impl Into<String>) -> LocalSourceBuilder {
        LocalSourceBuilder { app: app_name.into(), ..LocalSourceBuilder::default() }
    }

    /// The kernel's agent table: the kernel's own, else the handle's while its kernel lives.
    fn agent_table(&self) -> Option<adk_kernel::agents::Agents> {
        match &self.kernel {
            Some((kernel, _)) => Some(kernel.agents().clone()),
            None => self.agents.as_ref().and_then(adk_kernel::agents::AgentsHandle::get),
        }
    }

    /// The bytes of an evidence image, read at its exact version and checked against its
    /// digest; `None` when it is no longer kept.
    async fn evidence_bytes(&self, image: &ImageEvidence) -> Result<Option<Vec<u8>>> {
        let artifacts = self
            .artifacts
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("showing a decision's images"))?;
        crate::evidence::load_image(artifacts.as_ref(), image).await
    }

    fn approvals(&self) -> Result<&Arc<dyn ApprovalService>> {
        self.approvals
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("decisions without an approval service"))
    }

    fn ids(user: &str, session: &str) -> Result<(UserId, SessionId)> {
        let user = UserId::new(user).map_err(|error| SurfaceError::Invalid(error.to_string()))?;
        let session =
            SessionId::new(session).map_err(|error| SurfaceError::Invalid(error.to_string()))?;
        Ok((user, session))
    }

    /// The user's processes on the kernel, newest change first.
    async fn processes(&self, user: &str) -> Result<Vec<adk_kernel::Process>> {
        let Some((kernel, _)) = &self.kernel else {
            return Ok(Vec::new());
        };
        let mut processes: Vec<_> = kernel
            .processes()
            .ps(ProcessFilter::default())
            .await?
            .into_iter()
            .filter(|process| process.run.user_id == user && process.run.app_name == self.app)
            .collect();
        processes.sort_by_key(|process| std::cmp::Reverse(process.run.updated_at));
        Ok(processes)
    }

    /// The classes the kernel's mounted drivers declare `tool` of; a name two drivers share
    /// has both (spec 3.2 K-I9).
    fn driver_classes(&self, tool: &str) -> Vec<adk_kernel::drivers::EffectClass> {
        let Some(drivers) = self.kernel.as_ref().and_then(|(kernel, _)| kernel.drivers()) else {
            return Vec::new();
        };
        drivers
            .mounted()
            .iter()
            .filter_map(|id| drivers.record(id))
            .map(|record| record.manifest.class_of(tool))
            .collect()
    }

    async fn ensure_session(&self, user: &str, session: &str) -> Result<()> {
        if self.transcript(user, session).await?.is_some() {
            return Ok(());
        }
        let created = self
            .sessions
            .create(CreateRequest {
                app_name: self.app.clone(),
                user_id: user.to_string(),
                session_id: Some(session.to_string()),
                state: Default::default(),
            })
            .await;
        match created {
            Ok(_) => Ok(()),
            Err(error) if error.category == ErrorCategory::Conflict => Ok(()),
            Err(error) => Err(SurfaceError::Source(error)),
        }
    }

    /// Starts a turn of the session through the harness or the runner and runs it in the
    /// background; `text` empty resumes the session's decided calls. With `caller`, the turn
    /// carries the caller's identity, so the harness applies the session's mode and standing
    /// rules as it does to a request a server admitted (spec 3.3 §6).
    ///
    /// Returns once the turn is registered as running, so [`busy`](Source::busy) sees it and
    /// input queued behind it waits for it (S-I4).
    async fn run_turn(
        &self,
        user: &str,
        session: &str,
        text: &str,
        caller: Option<&Caller>,
    ) -> Result<()> {
        let (user_id, session_id) = Self::ids(user, session)?;
        let text = text.to_string();
        let context =
            caller.filter(|caller| caller.user_id() == user).map(|caller| RequestContext {
                user_id: caller.user_id().to_string(),
                scopes: caller.groups.clone(),
                metadata: Default::default(),
            });
        let stream = if let Some(harness) = &self.harness {
            match (text.is_empty(), context) {
                (true, None) => harness.resume(&user_id, &session_id).await,
                (true, Some(context)) => harness.resume_as(&user_id, &session_id, context).await,
                (false, None) => harness.send(&user_id, &session_id, text).await,
                (false, Some(context)) => {
                    harness.send_as(&user_id, &session_id, text, context).await
                }
            }
        } else if let Some(runner) = &self.runner {
            let content = if text.is_empty() {
                Content::new("user")
            } else {
                Content::new("user").with_text(text)
            };
            let config = context.map(|context| adk_core::RunConfig {
                request_context: Some(context),
                ..runner.run_config().clone()
            });
            runner.run_with_config(user_id, session_id.clone(), content, config).await
        } else {
            return Err(SurfaceError::unsupported(
                "sending a message without a kernel, harness or runner",
            ));
        };
        let stream = stream?;
        let turn = self.turn_of(user, session);
        tokio::spawn(drain(stream, self.failed.clone(), turn));
        Ok(())
    }

    /// Whose turn a stream started here runs: the harness's agent, else the app's runner.
    fn turn_of(&self, user: &str, session: &str) -> TurnOf {
        TurnOf {
            user: user.to_string(),
            session: session.to_string(),
            agent: match &self.harness {
                Some(harness) => harness.agent().info().name.clone(),
                None => self.app.clone(),
            },
        }
    }

    /// The harness's pending call for `request`, with the standing rule "Always allow" makes
    /// and the words that say what it covers.
    async fn always_allow_rule(
        &self,
        caller: Option<&Caller>,
        request: &ApprovalRequest,
    ) -> Option<(String, StandingRule, adk_core::ToolConfirmationRequest)> {
        let harness = self.harness.as_ref()?;
        let runtime = harness.agent().runtime();
        let pending = runtime.approval_store().pending(&request.scope).await.ok()?;
        let held = pending.into_iter().find(|entry| entry.fingerprint == request.fingerprint)?;
        // A call a person asked for through a drawn form is never made a standing rule
        // (spec 3.3 §7.4 rule 5, wave 4 decision 12).
        if held
            .request
            .function_call_id
            .as_deref()
            .is_some_and(adk_core::RequestedCall::is_requested_id)
        {
            return None;
        }
        // A file write: every file write in its folder (spec 3.3 §8.2). A file change no
        // folder rule covers — a delete or a move — is asked about every time.
        let suggestion = match harness.agent().folder_suggestion(&held.request) {
            Some(folder) => folder,
            None => StandingRule::suggestions(&held.request).into_iter().find(|suggestion| {
                !suggestion
                    .predicates
                    .iter()
                    .any(|predicate| matches!(predicate, RulePredicate::PathWithin { .. }))
            })?,
        };
        let label = always_allow_label(&suggestion);
        let created_by = caller.map_or_else(
            || adk_core::principal::SubjectRef::human(request.scope.user_id.clone()),
            |caller| caller.subject.clone(),
        );
        let owner = RuleOwner {
            app_name: request.scope.app_name.clone(),
            user_id: request.scope.user_id.clone(),
            subject_kind: adk_core::SubjectKind::Human,
            session_id: request.scope.session_id.clone(),
            created_by,
        };
        let mut rule = harness
            .agent()
            .rule_for_held_call(&held.request, suggestion, StandingDecision::Allow, &owner)
            .ok()?;
        // "Always allow" on an added agent's card makes a rule for that agent alone (spec 3.3
        // S-I19). When the agent table cannot be read, no rule is made: one for every agent
        // would let the others do what the person allowed this one.
        if let (Some(table), Some(acting)) = (self.agent_table(), &request.acting) {
            match table.get(&crate::project::agent_name(request)).await {
                Ok(Some(_)) => rule.agent = Some(acting.agent.id.as_str().to_string()),
                Ok(None) => {}
                Err(error) => {
                    tracing::warn!(approval.id = %request.id, error = %error, "could not tell whose rule \"Always allow\" makes; none is offered");
                    return None;
                }
            }
        }
        Some((label, rule, held.request))
    }
}

impl LocalSource {
    /// The kernel target of `agent`: the source's own for the primary agent, else the added
    /// agent's id.
    fn target_of(&self, agent: &str) -> Option<String> {
        let (_, own) = self.kernel.as_ref()?;
        Some(if agent == adk_harness::PRIMARY_AGENT_STAMP || agent == own || agent == self.app {
            own.clone()
        } else {
            agent.to_string()
        })
    }

    /// The target a message to `session` goes to (spec 3.3 §5.7 "Threads"): the agent its
    /// stamp names, before the first run the agent of its latest run, else the primary agent.
    async fn target_for(&self, user: &str, session: &str) -> Result<String> {
        let own = self.kernel.as_ref().map(|(_, target)| target.clone()).unwrap_or_default();
        Ok(match self.agent_of_session(user, session).await? {
            Some(agent) => self.target_of(&agent).unwrap_or(own),
            None => own,
        })
    }
}

/// The primary agent's name on screen, as the suggesting agent of an added one.
const PRIMARY_NAME: &str = "ADK-Rust";

/// The host's offset from UTC now: dates on screen are the host's.
fn local_offset() -> chrono::FixedOffset {
    *chrono::Local::now().offset()
}

impl LocalSource {
    /// Applies `action` with the digest its preview showed, through the kernel's agent table.
    async fn apply_agent(
        &self,
        caller: &Caller,
        action: adk_kernel::agents::AgentAction,
        digest: &str,
    ) -> Result<crate::agents::AgentDetail> {
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
        match crate::agents::local::apply(
            kernel.agents(),
            caller,
            action,
            digest,
            PRIMARY_NAME,
            local_offset(),
        )
        .await?
        {
            crate::agents::local::Applied::Agent(detail) => Ok(*detail),
            crate::agents::local::Applied::Removed(_) => {
                Err(SurfaceError::Invalid("the agent was removed".into()))
            }
        }
    }
}

/// "Always allow …" for the rule `suggestion` makes, saying all it covers: the command
/// prefix, the file writes in the folder or the whole workspace, the site, or the tool with
/// any arguments, in every session or this one, and that commands running project scripts
/// allow whatever they do (spec 3.3 §8.2, spec 3.1 §7.5).
fn always_allow_label(suggestion: &RuleSuggestion) -> String {
    let (label, covers) = match suggestion.predicates.first() {
        Some(RulePredicate::ShellPrefix { tokens, .. }) => {
            (words::ALWAYS_ALLOW_FOR_THIS_COMMAND, format!("{} …", tokens.join(" ")))
        }
        Some(RulePredicate::WritesWithin { dir }) if dir == "." => (
            words::ALWAYS_ALLOW_FOR_THIS_FOLDER,
            "file writes anywhere in the workspace".to_string(),
        ),
        Some(RulePredicate::WritesWithin { dir }) => {
            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, format!("file writes anywhere in {dir}/"))
        }
        Some(RulePredicate::PathWithin { dir, .. }) if dir == "." => {
            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, "anywhere in the workspace".to_string())
        }
        Some(RulePredicate::PathWithin { dir, .. }) => {
            (words::ALWAYS_ALLOW_FOR_THIS_FOLDER, format!("anywhere in {dir}/"))
        }
        Some(RulePredicate::Arg(ArgSpec::DomainIn { domains, .. })) => {
            (words::ALWAYS_ALLOW_FOR_THIS_SITE, format!("any page on {}", domains.join(", ")))
        }
        Some(RulePredicate::Arg(ArgSpec::Equals { value, .. })) => (
            words::ALWAYS_ALLOW_FOR_THIS_SITE,
            format!("{} on {}", suggestion.tool, value.as_str().unwrap_or_default()),
        ),
        // Any other condition on the arguments, and none: the tool, with any arguments.
        Some(RulePredicate::Arg(_)) | None => {
            (words::ALWAYS_ALLOW_FOR_THIS_PERSON, format!("{} with any arguments", suggestion.tool))
        }
    };
    words::always_allow_covering(
        label,
        &covers,
        suggestion.scope == SuggestedScope::User,
        suggestion.runs_scripts,
    )
}

/// What `events`, a session's, say became of the steering message `steer_id`: delivered as
/// the event whose marker carries the id, else handed back.
pub(crate) fn taken(events: &[Event], steer_id: &str) -> Steered {
    let event = events.iter().find(|event| {
        event.actions.steering.as_ref().is_some_and(|marker| marker.steer_id == steer_id)
    });
    match event {
        Some(event) => Steered::Delivered { event_id: event.id.clone() },
        None => Steered::Returned,
    }
}

/// Runs a turn's stream to its end, so its events reach the session store; a turn that ends
/// in an error is recorded in `failed` for the thread to show.
async fn drain(mut stream: adk_core::EventStream, failed: Arc<FailedTurnLog>, turn: TurnOf) {
    while let Some(event) = stream.next().await {
        if let Err(error) = event {
            tracing::warn!(session.id = %turn.session, error = %error, "a turn a surface started failed");
            failed.record(turn, error.to_string());
            break;
        }
    }
}

/// Whose turn a drained stream runs: the user, the session and the agent.
struct TurnOf {
    user: String,
    session: String,
    agent: String,
}

/// The most sessions whose failed turns are kept in memory; past it the record starts again.
const FAILED_SESSIONS: usize = 1_024;

/// The most failed turns kept for one session: its latest.
const FAILED_PER_SESSION: usize = 16;

/// The turns a harness or runner ran in this process that ended in an error, by user and
/// session. The session holds no event for a failed model call, so this is what the thread
/// reads; it lasts as long as the process.
#[derive(Default)]
struct FailedTurnLog {
    by_session: std::sync::Mutex<std::collections::HashMap<(String, String), Vec<TurnFailure>>>,
}

impl FailedTurnLog {
    fn record(&self, turn: TurnOf, error: String) {
        let mut by_session = self.by_session.lock().unwrap_or_else(|e| e.into_inner());
        let key = (turn.user, turn.session);
        if by_session.len() >= FAILED_SESSIONS && !by_session.contains_key(&key) {
            by_session.clear();
        }
        let failures = by_session.entry(key).or_default();
        if failures.len() >= FAILED_PER_SESSION {
            failures.remove(0);
        }
        failures.push(TurnFailure { agent: turn.agent, at: Utc::now(), error: Some(error) });
    }

    fn of(&self, user: &str, session: &str) -> Vec<TurnFailure> {
        self.by_session
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&(user.to_string(), session.to_string()))
            .cloned()
            .unwrap_or_default()
    }
}

/// A standing rule granted once the decision it was made for approved the call, through the
/// harness, so `harness.rule.created` is recorded before the rule is stored (spec 3.1 §7.5,
/// §9.3).
struct GrantRule {
    harness: Arc<Harness>,
    rule: StandingRule,
    /// The held call the rule was made from.
    from: adk_core::ToolConfirmationRequest,
    /// The surface it was made on, such as `web`.
    surface: String,
}

impl GrantRule {
    async fn grant(self) -> Result<()> {
        self.harness.agent().grant_rule(self.rule, &self.surface, Some(&self.from)).await?;
        Ok(())
    }
}

/// The rules "Always allow" prepared, by the decision each waits for. The approval service
/// grants one as its author's yes resolves the decision ([`ApprovalResolution`]), before the
/// outcome reaches the call, so the turn the call resumes already runs under the rule.
#[derive(Default)]
struct PreparedRules {
    by_decision: std::sync::Mutex<std::collections::HashMap<String, Arc<PreparedRule>>>,
}

impl fmt::Debug for PreparedRules {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let waiting = self.by_decision.lock().unwrap_or_else(|e| e.into_inner()).len();
        f.debug_struct("PreparedRules").field("waiting", &waiting).finish()
    }
}

/// One prepared rule: who answered, the decision's version then, and the grant, which the
/// decision's resolution or the engine's commit takes, whichever comes first.
struct PreparedRule {
    author: String,
    version: u64,
    grant: tokio::sync::Mutex<Option<GrantRule>>,
}

impl PreparedRules {
    /// Forgets `rule` as the one prepared for `decision`, unless another replaced it.
    fn forget(&self, decision: &str, rule: &Arc<PreparedRule>) {
        let mut by_decision = self.by_decision.lock().unwrap_or_else(|e| e.into_inner());
        if by_decision.get(decision).is_some_and(|prepared| Arc::ptr_eq(prepared, rule)) {
            by_decision.remove(decision);
        }
    }
}

#[async_trait]
impl ApprovalResolution for PreparedRules {
    async fn resolving(&self, request: &ApprovalRequest, decision: &ApprovalDecision) {
        let prepared =
            self.by_decision.lock().unwrap_or_else(|e| e.into_inner()).get(&request.id).cloned();
        let Some(prepared) = prepared else { return };
        // Only the author's own yes, at the version it was prepared for, grants the rule: an
        // answer that lost, someone else's yes or a later "Allow once" grants nothing.
        if request.state != ApprovalState::Approved
            || decision.kind != ApprovalAction::Approve
            || decision.approver.id != prepared.author
            || request.version != prepared.version + 1
        {
            return;
        }
        self.forget(&request.id, &prepared);
        let grant = prepared.grant.lock().await.take();
        if let Some(grant) = grant
            && let Err(error) = grant.grant().await
        {
            tracing::warn!(error = %error, decision.id = %request.id, "the call was allowed once; its standing rule could not be created");
        }
    }
}

/// The engine's hold on a prepared rule: its commit grants the rule unless the decision's
/// resolution did; dropped uncommitted, the rule is no longer prepared.
struct PreparedCommit {
    rules: Arc<PreparedRules>,
    decision: String,
    rule: Arc<PreparedRule>,
}

#[async_trait]
impl RuleCommit for PreparedCommit {
    async fn commit(self: Box<Self>) -> Result<()> {
        let grant = self.rule.grant.lock().await.take();
        match grant {
            Some(grant) => grant.grant().await,
            None => Ok(()),
        }
    }
}

impl Drop for PreparedCommit {
    fn drop(&mut self) {
        self.rules.forget(&self.decision, &self.rule);
    }
}

#[async_trait]
impl Source for LocalSource {
    fn app_name(&self) -> &str {
        &self.app
    }

    async fn transcript(&self, user: &str, session: &str) -> Result<Option<Vec<Event>>> {
        let found = self
            .sessions
            .get(GetRequest {
                app_name: self.app.clone(),
                user_id: user.to_string(),
                session_id: session.to_string(),
                num_recent_events: None,
                after: None,
            })
            .await;
        match found {
            Ok(session) => Ok(Some(session.events().all())),
            Err(error) if error.category == ErrorCategory::NotFound => Ok(None),
            Err(error) if error.category == ErrorCategory::InvalidInput => Ok(None),
            Err(error) => Err(SurfaceError::Source(error)),
        }
    }

    async fn changed(&self, max: Duration) {
        match &self.kernel {
            Some((kernel, _)) => {
                let mut events = kernel.events();
                tokio::select! {
                    _ = tokio::time::sleep(max) => {}
                    _ = events.recv() => {}
                }
            }
            None => tokio::time::sleep(max).await,
        }
    }

    async fn requests(
        &self,
        caller: &Caller,
        session: Option<&str>,
        open_only: bool,
    ) -> Result<Vec<ApprovalRequest>> {
        let Some(approvals) = &self.approvals else {
            return Ok(Vec::new());
        };
        let states =
            if open_only { vec![ApprovalState::Pending] } else { ApprovalState::ALL.to_vec() };
        let mut query = InboxQuery::for_approver(caller.subject.clone(), caller.groups.clone())
            .with_states(states)
            .with_app_name(self.app.clone())
            .with_limit(INBOX_PAGE);
        // A session is the caller's: another user's session with the same ID stays out.
        if let Some(session) = session {
            query = query.with_user_id(caller.user_id()).with_session_id(session);
        }
        let mut requests = Vec::new();
        loop {
            let page = approvals.inbox(query.clone()).await?;
            requests.extend(page.items);
            match page.next_cursor {
                Some(cursor) => query = query.with_cursor(Some(cursor)),
                None => break,
            }
        }
        Ok(requests)
    }

    async fn request(&self, id: &str) -> Result<Option<ApprovalRequest>> {
        Ok(self.approvals()?.get(id).await?)
    }

    async fn decide(
        &self,
        id: &str,
        expected_version: u64,
        decision: ApprovalDecision,
    ) -> Result<ApprovalRequest> {
        Ok(self.approvals()?.decide(id, expected_version, decision).await?)
    }

    async fn resolved(&self, request: &ApprovalRequest) -> Result<()> {
        self.resume_decided(request, None).await
    }

    async fn evidence_kept(&self, request: &ApprovalRequest) -> Vec<EvidenceKept> {
        let images = crate::evidence::images(request);
        let Some(artifacts) = &self.artifacts else {
            return vec![EvidenceKept::Unknown; images.len()];
        };
        let mut kept = Vec::with_capacity(images.len());
        for image in images {
            let at = &image.artifact;
            let versions = artifacts
                .versions(VersionsRequest {
                    app_name: at.app_name.clone(),
                    user_id: at.user_id.clone(),
                    session_id: at.session_id.clone(),
                    file_name: at.file_name.clone(),
                })
                .await;
            kept.push(match versions {
                Ok(found) if found.versions.contains(&at.version) => EvidenceKept::Kept,
                Ok(_) => EvidenceKept::Deleted,
                Err(error) if error.is_not_found() => EvidenceKept::Deleted,
                Err(error) => {
                    tracing::warn!(error = %error, decision.id = %request.id, "an evidence image's state could not be read");
                    EvidenceKept::Unknown
                }
            });
        }
        kept
    }

    async fn vision_answers(&self, user: &str, session: &str) -> Result<Vec<serde_json::Value>> {
        let Some(artifacts) = &self.artifacts else { return Ok(Vec::new()) };
        let names = artifacts
            .list(adk_artifact::ListRequest {
                app_name: self.app.clone(),
                user_id: user.to_string(),
                session_id: session.to_string(),
            })
            .await?
            .file_names;
        let mut records = Vec::new();
        for name in names.iter().filter(|name| {
            name.starts_with(crate::viewer::VISION_ANSWER_PREFIX) && name.ends_with(".json")
        }) {
            let loaded = artifacts
                .load(adk_artifact::LoadRequest {
                    app_name: self.app.clone(),
                    user_id: user.to_string(),
                    session_id: session.to_string(),
                    file_name: name.clone(),
                    version: None,
                })
                .await?;
            let data = match loaded.part {
                adk_core::Part::InlineData { data, .. } => data,
                adk_core::Part::Text { text } => text.into_bytes(),
                _ => continue,
            };
            match serde_json::from_slice::<serde_json::Value>(&data) {
                Ok(record) => records.push(record),
                Err(error) => {
                    tracing::warn!(error = %error, artifact.name = %name, "an answer record is not JSON; it is not shown");
                }
            }
        }
        records.sort_by(|a, b| {
            let at = |record: &serde_json::Value| {
                record.get("at").and_then(serde_json::Value::as_str).unwrap_or_default().to_string()
            };
            at(a).cmp(&at(b))
        });
        Ok(records)
    }

    fn keeps_vision_answers(&self) -> bool {
        self.artifacts.is_some()
    }

    async fn vision_image(
        &self,
        user: &str,
        session: &str,
        digest: &str,
    ) -> Result<Option<EvidenceBytes>> {
        let artifacts = self
            .artifacts
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("showing a session's images"))?;
        let Some(hex) = digest.strip_prefix("sha256:") else {
            // An image the session holds by name, as a vision tool was called with it.
            let loaded = artifacts
                .load(adk_artifact::LoadRequest {
                    app_name: self.app.clone(),
                    user_id: user.to_string(),
                    session_id: session.to_string(),
                    file_name: digest.to_string(),
                    version: None,
                })
                .await;
            return match loaded {
                Ok(loaded) => Ok(match loaded.part {
                    adk_core::Part::InlineData { mime_type, data, .. }
                        if mime_type.starts_with("image/") =>
                    {
                        Some(EvidenceBytes { mime_type, bytes: data })
                    }
                    _ => None,
                }),
                Err(error) if error.is_not_found() => Ok(None),
                Err(error) => Err(error.into()),
            };
        };
        if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Ok(None);
        }
        for (extension, mime) in [
            ("png", "image/png"),
            ("jpeg", "image/jpeg"),
            ("webp", "image/webp"),
            ("gif", "image/gif"),
        ] {
            let loaded = artifacts
                .load(adk_artifact::LoadRequest {
                    app_name: self.app.clone(),
                    user_id: user.to_string(),
                    session_id: session.to_string(),
                    file_name: format!("vision-{hex}.{extension}"),
                    version: None,
                })
                .await;
            let part = match loaded {
                Ok(loaded) => loaded.part,
                Err(error) if error.is_not_found() => continue,
                Err(error) => return Err(error.into()),
            };
            let adk_core::Part::InlineData { data, .. } = part else { continue };
            if crate::evidence::digest_of(&data) != digest {
                tracing::warn!(image.digest = %digest, "a session image does not match its digest; it is not shown");
                return Err(SurfaceError::Invalid(
                    "the stored image does not match its digest; it is not shown".into(),
                ));
            }
            return Ok(Some(EvidenceBytes { mime_type: mime.to_string(), bytes: data }));
        }
        Ok(None)
    }

    async fn example_files(&self, _user: &str) -> Result<Option<Vec<String>>> {
        let Some(root) = &self.eval_fixtures else { return Ok(None) };
        let mut files = Vec::new();
        let mut pending = vec![root.clone()];
        while let Some(dir) = pending.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else { continue };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    // Fixture images live beside their files; four levels is plenty.
                    if path.strip_prefix(root).map_or(0, |p| p.components().count()) < 4 {
                        pending.push(path);
                    }
                } else if let Ok(relative) = path.strip_prefix(root) {
                    let relative = relative.to_string_lossy().replace('\\', "/");
                    if relative.ends_with(".test.json") {
                        files.push(relative);
                    }
                }
            }
        }
        files.sort();
        Ok(Some(files))
    }

    async fn example_set(&self, _user: &str, file: &str) -> Result<Option<serde_json::Value>> {
        let root = self
            .eval_fixtures
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("saving labelled examples"))?;
        crate::viewer::check_file(file).map_err(SurfaceError::Invalid)?;
        match std::fs::read(root.join(file)) {
            Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| {
                SurfaceError::Invalid(format!("{file} is not an eval set: {error}"))
            }),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(SurfaceError::Invalid(format!("{file} could not be read: {error}"))),
        }
    }

    async fn save_example(
        &self,
        _caller: &Caller,
        file: &str,
        set: serde_json::Value,
        image_path: &str,
        image: &EvidenceBytes,
    ) -> Result<()> {
        let root = self
            .eval_fixtures
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("saving labelled examples"))?;
        crate::viewer::check_file(file).map_err(SurfaceError::Invalid)?;
        let target = root.join(file);
        let folder = target.parent().unwrap_or(root).to_path_buf();
        let picture = folder.join(image_path);
        let io = |what: &str, error: std::io::Error| {
            SurfaceError::Invalid(format!("{what} could not be written: {error}"))
        };
        if let Some(parent) = picture.parent() {
            std::fs::create_dir_all(parent).map_err(|e| io("the fixtures folder", e))?;
        }
        if !picture.exists() {
            std::fs::write(&picture, &image.bytes).map_err(|e| io(image_path, e))?;
        }
        let text = serde_json::to_vec_pretty(&set)
            .map_err(|error| SurfaceError::Invalid(format!("the eval set: {error}")))?;
        // Written beside and renamed, so a reader never sees half a file.
        let partial = target.with_extension("json.partial");
        std::fs::write(&partial, text).map_err(|e| io(file, e))?;
        std::fs::rename(&partial, &target).map_err(|e| io(file, e))?;
        Ok(())
    }

    async fn evidence_image(
        &self,
        request: &ApprovalRequest,
        index: usize,
    ) -> Result<Option<EvidenceBytes>> {
        let image = *crate::evidence::images(request)
            .get(index)
            .ok_or_else(|| SurfaceError::not_found(format!("image {index} of this decision")))?;
        let Some(bytes) = self.evidence_bytes(image).await? else { return Ok(None) };
        Ok(Some(EvidenceBytes { mime_type: image.mime_type.clone(), bytes }))
    }

    fn holds_again(&self) -> bool {
        self.approvals.is_some()
            && self.artifacts.is_some()
            && (self.kernel.is_some() || self.harness.is_some())
    }

    async fn hold_again(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        args: serde_json::Value,
        why: &str,
    ) -> Result<()> {
        if !self.holds_again() {
            return Err(SurfaceError::unsupported("holding a call again"));
        }
        // Closed first, at the version the person saw, so the old call can never run as well.
        let closed = ApprovalDecision::reject(caller.subject.clone(), why)
            .with_groups(caller.groups.clone());
        self.approvals()?.decide(&request.id, version, closed).await?;
        let call = RequestedCall::new(
            request.tool_name.clone(),
            args,
            caller.subject.clone(),
            RequestedVia::form(format!("decision:{}", request.id), version, HELD_AGAIN_ACTION),
        );
        self.request_call(caller, &request.scope.session_id, "", call).await
    }

    #[cfg(feature = "web")]
    async fn change_image(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        change: &crate::evidence::ImageChange,
    ) -> Result<crate::evidence::ImageChanged> {
        let artifacts = self
            .artifacts
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("changing an image without its artifacts"))?;
        let image =
            *crate::evidence::images(request).get(change.image as usize).ok_or_else(|| {
                SurfaceError::not_found(format!("image {} of this decision", change.image))
            })?;
        if image.mime_type != "image/png" {
            return Err(SurfaceError::Invalid(format!(
                "only a PNG image can be changed here; this one is {}",
                image.mime_type
            )));
        }
        let bytes = self
            .evidence_bytes(image)
            .await?
            .ok_or_else(|| SurfaceError::Invalid("the image is no longer kept".into()))?;
        let (changed, width, height) =
            crate::evidence::changed_png(&bytes, change).map_err(SurfaceError::Invalid)?;
        let to = crate::evidence::digest_of(&changed);
        // Kept beside the original under the name the vision tools find an image by digest.
        let hex = to.trim_start_matches("sha256:");
        let at = &image.artifact;
        artifacts
            .save(adk_artifact::SaveRequest {
                app_name: at.app_name.clone(),
                user_id: at.user_id.clone(),
                session_id: at.session_id.clone(),
                file_name: format!("vision-{hex}.png"),
                part: adk_core::Part::InlineData {
                    mime_type: "image/png".into(),
                    data: changed,
                    uri: None,
                    annotations: None,
                },
                version: None,
            })
            .await?;
        let mut args = request.args_redacted.clone();
        if let Some(map) = args.as_object_mut() {
            // The new image is already cut to the crop the call asked for.
            map.remove("region");
            map.insert("image".into(), serde_json::Value::String(to.clone()));
        }
        self.hold_again(caller, request, version, args, IMAGE_CHANGED_REASON).await?;
        Ok(crate::evidence::ImageChanged { from: image.digest.clone(), to, width, height })
    }

    #[cfg(feature = "computer-use")]
    async fn screen_plan(&self, request: &ApprovalRequest) -> Option<crate::source::HeldPlan> {
        let held = self.harness.as_ref()?.held_screen_plan(request)?;
        Some(held_plan(&held))
    }

    #[cfg(feature = "computer-use")]
    async fn decide_screen_plan(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
        version: u64,
        digest: &str,
        allow: bool,
        reason: Option<String>,
    ) -> Result<ApprovalRequest> {
        let harness = self
            .harness
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("deciding a screen plan"))?;
        let approvals = self.approvals()?;
        let answer = if allow {
            adk_harness::ScreenPlanAnswer::Approve
        } else {
            adk_harness::ScreenPlanAnswer::Deny {
                message: reason.filter(|reason| !reason.trim().is_empty()),
            }
        };
        let decision = harness
            .decide_held_screen_plan(request, digest, answer, &caller.subject)
            .await?
            .with_groups(caller.groups.clone());
        match approvals.decide(&request.id, version, decision).await {
            Ok(updated) => Ok(updated),
            Err(error) => {
                // Another answer reached the call first: the plan waits for a decision again.
                harness.revert_held_screen_plan(request, digest).await;
                Err(error.into())
            }
        }
    }

    #[cfg(feature = "computer-use")]
    async fn close_screen_plan(
        &self,
        request: &ApprovalRequest,
        plan: &crate::source::HeldPlan,
        why: &str,
    ) -> Result<()> {
        let harness = self
            .harness
            .as_ref()
            .ok_or_else(|| SurfaceError::unsupported("closing a screen plan"))?;
        harness.end_held_screen_plan(request, &plan.view.digest, why).await;
        // Every step still held, the card's own call first: a cancel denies the call, so none
        // runs on an answer given after the stop.
        let approvals = self.approvals()?;
        let mut query = InboxQuery::default()
            .with_session(&request.scope)
            .with_states([ApprovalState::Pending]);
        loop {
            let page = approvals.inbox(query.clone()).await?;
            for item in
                page.items.iter().filter(|item| plan.fingerprints.contains(&item.fingerprint))
            {
                if let Err(error) = approvals.cancel(&item.id, Some(why.to_string())).await {
                    tracing::warn!(error = %error, decision.id = %item.id, "a screen plan step's request was not cancelled");
                }
            }
            match page.next_cursor {
                Some(cursor) => query = query.with_cursor(Some(cursor)),
                None => break,
            }
        }
        Ok(())
    }

    async fn run_ended(&self, request: &ApprovalRequest) -> Option<DateTime<Utc>> {
        let (runs, run_id) = (self.runs.as_ref()?, request.run_id.as_ref()?);
        match runs.get(run_id).await {
            Ok(Some(run)) if run.state.is_terminal() => Some(run.updated_at),
            Ok(_) => None,
            Err(error) => {
                tracing::warn!(error = %error, decision.id = %request.id, "the run waiting on a decision could not be read");
                None
            }
        }
    }

    async fn resolved_by(&self, caller: &Caller, request: &ApprovalRequest) -> Result<()> {
        // A suggested agent is added as the surface that approved it, so its record names
        // where (spec 3.3 §11).
        if request.tool_name == adk_kernel::agents::AGENT_CREATE_TOOL_NAME {
            if let Some(table) = self.agent_table() {
                table.answered(&request.id, &crate::agents::agent_caller(caller)).await;
            }
            return Ok(());
        }
        self.resume_decided(request, Some(caller)).await
    }

    async fn always_allow_offer(&self, request: &ApprovalRequest) -> Option<AlwaysAllowOffer> {
        self.always_allow_rule(None, request).await.map(|(label, ..)| AlwaysAllowOffer { label })
    }

    async fn prepare_always_allow(
        &self,
        caller: &Caller,
        request: &ApprovalRequest,
    ) -> Result<Box<dyn RuleCommit>> {
        let harness =
            self.harness.clone().ok_or_else(|| SurfaceError::unsupported("always allow"))?;
        let (_, rule, from) =
            self.always_allow_rule(Some(caller), request).await.ok_or_else(|| {
                SurfaceError::Invalid("no standing rule applies to this call; allow it once".into())
            })?;
        let surface = serde_json::to_value(caller.surface)
            .ok()
            .and_then(|value| value.as_str().map(str::to_string))
            .unwrap_or_else(|| "surface".to_string());
        let prepared = Arc::new(PreparedRule {
            author: caller.user_id().to_string(),
            version: request.version,
            grant: tokio::sync::Mutex::new(Some(GrantRule { harness, rule, from, surface })),
        });
        self.prepared
            .by_decision
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .insert(request.id.clone(), prepared.clone());
        Ok(Box::new(PreparedCommit {
            rules: self.prepared.clone(),
            decision: request.id.clone(),
            rule: prepared,
        }))
    }

    async fn agents(&self, user: &str) -> Result<Vec<AgentState>> {
        if let Some((kernel, _)) = &self.kernel {
            // Where each agent's commands run: the harness's own agent as the harness
            // reports it, an agent the person added from its definition (spec 3.3 §5.7).
            let views = kernel.agents().list().await?;
            let own = self.harness.as_ref().map(|harness| {
                (
                    harness.agent().info().name.clone(),
                    harness.agent().info().shell().map(shell_place),
                )
            });
            let shell_of = |target: &str| -> Option<crate::model::ShellPlace> {
                if let Some((name, place)) = &own
                    && name == target
                {
                    return place.clone();
                }
                views.iter().find(|view| view.agent.id == target).and_then(|view| {
                    match view.agent.uses.shell {
                        adk_kernel::agents::ShellAccess::None => None,
                        adk_kernel::agents::ShellAccess::Sandboxed => {
                            Some(crate::model::ShellPlace::Sandbox { enforcer: None })
                        }
                        adk_kernel::agents::ShellAccess::Host => {
                            Some(crate::model::ShellPlace::Host)
                        }
                    }
                })
            };
            let mut latest: BTreeMap<String, AgentState> = BTreeMap::new();
            for process in self.processes(user).await? {
                let run = &process.run;
                if latest.contains_key(&run.target) {
                    continue;
                }
                let waiting_on_decision =
                    matches!(run.checkpoint, Some(RunCheckpointRef::AwaitingApproval { .. }));
                latest.insert(
                    run.target.clone(),
                    AgentState {
                        shell: shell_of(&run.target),
                        name: run.target.clone(),
                        session_id: run.session_id.clone(),
                        state: run.state,
                        waiting_on_decision,
                        wake_at: (run.state == RunState::Waiting && !waiting_on_decision)
                            .then_some(run.not_before)
                            .flatten(),
                        suspended: process.meta.suspended_by.is_some(),
                        subagent: (process.meta.kind == adk_kernel::ProcessKind::Subagent).then(
                            || {
                                process
                                    .meta
                                    .labels
                                    .get(adk_kernel::SUBAGENT_NAME_LABEL)
                                    .cloned()
                                    .unwrap_or_else(|| "sub-agent".to_string())
                            },
                        ),
                    },
                );
            }
            // A removed agent leaves the roster; its past runs stay in its threads. One
            // listing carries every agent's state (spec 3.3 §5.7).
            let gone: Vec<String> = views
                .into_iter()
                .filter(|view| {
                    matches!(
                        view.agent.state,
                        adk_kernel::agents::AgentRecordState::Removing
                            | adk_kernel::agents::AgentRecordState::Removed
                    )
                })
                .map(|view| view.agent.id)
                .collect();
            latest.retain(|name, _| !gone.contains(name));
            return Ok(latest.into_values().collect());
        }
        let (name, shell) = match (&self.harness, &self.runner) {
            (Some(harness), _) => (
                harness.agent().info().name.clone(),
                harness.agent().info().shell().map(shell_place),
            ),
            (None, Some(_)) => (self.app.clone(), None),
            (None, None) => return Ok(Vec::new()),
        };
        let active = self.active_sessions(user);
        let waiting = match &self.approvals {
            Some(approvals) => approvals
                .inbox(
                    InboxQuery::default()
                        .with_app_name(self.app.clone())
                        .with_user_id(user)
                        .with_states(vec![ApprovalState::Pending])
                        .with_limit(1),
                )
                .await?
                .items
                .into_iter()
                .next(),
            None => None,
        };
        let state = if !active.is_empty() {
            RunState::Running
        } else if waiting.is_some() {
            RunState::Waiting
        } else {
            RunState::Completed
        };
        Ok(vec![AgentState {
            name,
            session_id: waiting
                .map(|request| request.scope.session_id)
                .or_else(|| active.first().cloned()),
            state,
            waiting_on_decision: state == RunState::Waiting,
            wake_at: None,
            suspended: false,
            subagent: None,
            shell,
        }])
    }

    /// The kernel target new messages run on, else the harness's agent (spec 3.3 §5.5).
    fn primary_agent(&self) -> Option<String> {
        match (&self.kernel, &self.harness) {
            (Some((_, target)), _) => Some(target.clone()),
            (None, Some(harness)) => Some(harness.agent().info().name.clone()),
            (None, None) => None,
        }
    }

    /// A tool the kernel's mounted drivers declare `publish_public` or `financial`, the
    /// classes nothing may allow without a person (spec 3.2 K-I9), as the kernel's own decide
    /// route and chat rate it.
    fn rates_high(&self, request: &ApprovalRequest) -> bool {
        self.driver_classes(&request.tool_name)
            .into_iter()
            .any(adk_kernel::drivers::EffectClass::is_never_auto_allowed)
    }

    /// A tool the kernel's mounted drivers declare `financial` (spec 3.2 K-I9).
    fn moves_money(&self, request: &ApprovalRequest) -> bool {
        self.driver_classes(&request.tool_name)
            .contains(&adk_kernel::drivers::EffectClass::Financial)
    }

    async fn busy(&self, user: &str, session: &str) -> Result<bool> {
        if self.kernel.is_some() {
            return Ok(self.processes(user).await?.iter().any(|process| {
                process.run.session_id.as_deref() == Some(session)
                    && matches!(process.run.state, RunState::Running | RunState::Queued)
            }));
        }
        Ok(self.active_sessions(user).iter().any(|active| active == session))
    }

    /// A kernel's failed processes of the session, each with the error its run recorded;
    /// without a kernel, the turns this source started that ended in an error.
    async fn turn_failures(&self, user: &str, session: &str) -> Result<Vec<TurnFailure>> {
        if self.kernel.is_none() {
            return Ok(self.failed.of(user, session));
        }
        let mut failures: Vec<TurnFailure> = self
            .processes(user)
            .await?
            .into_iter()
            .filter(|process| {
                process.run.session_id.as_deref() == Some(session)
                    && process.run.state == RunState::Failed
            })
            .map(|process| TurnFailure {
                agent: process.run.target,
                at: process.run.updated_at,
                error: process.run.error,
            })
            .collect();
        failures.sort_by_key(|failure| failure.at);
        Ok(failures)
    }

    async fn waiting_on_decision(&self, user: &str, session: &str) -> Result<bool> {
        if self.kernel.is_some() {
            return Ok(self.processes(user).await?.iter().any(|process| {
                process.run.session_id.as_deref() == Some(session)
                    && process.run.state == RunState::Waiting
                    && matches!(
                        process.run.checkpoint,
                        Some(RunCheckpointRef::AwaitingApproval { .. })
                    )
            }));
        }
        let Some(approvals) = &self.approvals else {
            return Ok(false);
        };
        // Every open request of the caller's session, whoever may answer it; only whether
        // one exists leaves this source.
        let page = approvals
            .inbox(
                InboxQuery::default()
                    .with_app_name(self.app.clone())
                    .with_user_id(user)
                    .with_session_id(session)
                    .with_states(vec![ApprovalState::Pending])
                    .with_limit(1),
            )
            .await?;
        Ok(!page.items.is_empty())
    }

    async fn start_turn(&self, caller: &Caller, session: &str, text: &str) -> Result<()> {
        let user = caller.user_id();
        self.ensure_session(user, session).await?;
        if let Some((kernel, _)) = &self.kernel {
            // A thread belongs to one agent: its stamp, then its latest run (spec 3.3 §5.7).
            let target = self.target_for(user, session).await?;
            let run = NewRun::new(
                QueueClass::Interactive.as_str(),
                self.app.clone(),
                user,
                target,
                serde_json::json!({ "text": text }),
            )
            .with_session_id(session)
            .with_authenticated_user();
            kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
            return Ok(());
        }
        self.run_turn(user, session, text, Some(caller)).await
    }

    /// A message with images: as the run's `content` on a kernel, else straight to the
    /// harness or the runner (spec 3.3 §5.1).
    async fn start_turn_images(
        &self,
        caller: &Caller,
        session: &str,
        text: &str,
        images: &[crate::images::MessageImage],
    ) -> Result<()> {
        if images.is_empty() {
            return self.start_turn(caller, session, text).await;
        }
        let user = caller.user_id();
        self.ensure_session(user, session).await?;
        let content = message_content(text, images);
        if let Some((kernel, _)) = &self.kernel {
            let target = self.target_for(user, session).await?;
            return self.spawn_content(kernel, user, session, target, content).await;
        }
        self.run_content(user, session, content, caller).await
    }

    async fn start_turn_with_images(
        &self,
        caller: &Caller,
        agent: &str,
        session: &str,
        text: &str,
        images: &[crate::images::MessageImage],
    ) -> Result<()> {
        if images.is_empty() {
            return self.start_turn_with(caller, agent, session, text).await;
        }
        let Some(target) = self.target_of(agent) else {
            return self.start_turn_images(caller, session, text, images).await;
        };
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("sending a message"))?;
        let user = caller.user_id();
        self.ensure_session(user, session).await?;
        self.spawn_content(kernel, user, session, target, message_content(text, images)).await
    }

    /// A kernel kills the session's running and queued runs; a harness or a runner cancels its
    /// run in flight. A run waiting on a decision is left to wait.
    async fn stop_turn(&self, caller: &Caller, session: &str) -> Result<bool> {
        let user = caller.user_id();
        if let Some((kernel, _)) = &self.kernel {
            let mut stopped = false;
            for process in self.processes(user).await? {
                let run = &process.run;
                if run.session_id.as_deref() == Some(session)
                    && matches!(run.state, RunState::Running | RunState::Queued)
                {
                    kernel.processes().kill(&process.meta.pid, "stopped by the person").await?;
                    stopped = true;
                }
            }
            return Ok(stopped);
        }
        let runner: &Runner = match (&self.harness, &self.runner) {
            (Some(harness), _) => harness.runner(),
            (None, Some(runner)) => runner,
            (None, None) => return Err(SurfaceError::unsupported("stopping a turn")),
        };
        Ok(runner.interrupt_identity(runner.app_name(), user, session))
    }

    /// The turn this process runs takes the message: a kernel's claim of the session on this
    /// replica, else the harness's or the runner's run in flight.
    async fn steer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
        let user = caller.user_id();
        let receipt = if let Some((kernel, _)) = &self.kernel {
            kernel.steer(user, session, text).await?.map(|steering| steering.receipt)
        } else {
            let runner: &Runner = match (&self.harness, &self.runner) {
                (Some(harness), _) => harness.runner(),
                (None, Some(runner)) => runner,
                (None, None) => return Ok(None),
            };
            // Nothing reaches an agent while everything is stopped.
            if let Some(governance) = &self.governance {
                governance.check()?;
            }
            let (user_id, session_id) = Self::ids(user, session)?;
            let app = adk_core::AppName::try_from(runner.app_name())
                .map_err(|error| SurfaceError::Invalid(error.to_string()))?;
            let identity = adk_core::AdkIdentity::new(app, user_id, session_id);
            match runner.steer(&identity, Content::new("user").with_text(text)).await {
                Ok(receipt) => Some(receipt),
                // No run is in flight, or it has not reached its agent yet.
                Err(error)
                    if error.code == adk_core::STEER_NO_ACTIVE_RUN_CODE
                        || error.code == "agent.steer.run_not_ready" =>
                {
                    None
                }
                Err(error) => return Err(SurfaceError::Source(error)),
            }
        };
        let Some(receipt) = receipt else { return Ok(None) };
        let source = self.clone();
        let (user, session) = (user.to_string(), session.to_string());
        Ok(Some(Box::pin(async move {
            let steer_id = receipt.steer_id().to_string();
            match receipt.outcome().await {
                Ok(adk_core::SteerOutcome::Delivered { event_id }) => {
                    Ok(Steered::Delivered { event_id })
                }
                Ok(adk_core::SteerOutcome::Returned(_)) => Ok(Steered::Returned),
                // The run was dropped before it said: the session holds the message's event
                // when the turn took it.
                Err(_) => {
                    let events = source.transcript(&user, &session).await?.unwrap_or_default();
                    Ok(taken(&events, &steer_id))
                }
            }
        })))
    }

    async fn request_call(
        &self,
        caller: &Caller,
        session: &str,
        text: &str,
        call: adk_core::RequestedCall,
    ) -> Result<()> {
        let user = caller.user_id();
        self.ensure_session(user, session).await?;
        if let Some((kernel, _)) = &self.kernel {
            // Held as the drawing agent inside its own target — the target of the session's
            // latest run, an area's or an added agent's — parked durably and woken by the
            // decision on any surface (spec 3.3 §7.4 rule 5, wave 4 decision 13).
            let latest = self
                .processes(user)
                .await?
                .into_iter()
                .find(|process| process.run.session_id.as_deref() == Some(session))
                .map(|process| process.run.target);
            let target = match latest {
                Some(target) => target,
                None => self.target_for(user, session).await?,
            };
            let run = NewRun::new(
                QueueClass::Interactive.as_str(),
                self.app.clone(),
                user,
                target,
                serde_json::json!({ "text": text, "requestedCall": call }),
            )
            .with_session_id(session)
            .with_authenticated_user();
            kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
            return Ok(());
        }
        let Some(harness) = &self.harness else {
            return Err(SurfaceError::unsupported(
                "sending a form an agent drew without a kernel or harness",
            ));
        };
        let (user_id, session_id) = Self::ids(user, session)?;
        let context = RequestContext {
            user_id: user.to_string(),
            scopes: caller.groups.clone(),
            metadata: Default::default(),
        };
        let stream = harness.send_requested(&user_id, &session_id, text, call, context).await?;
        let turn = self.turn_of(user, session);
        tokio::spawn(drain(stream, self.failed.clone(), turn));
        Ok(())
    }

    async fn stop_all(&self, caller: &Caller, reason: &str) -> Result<()> {
        let actor = AuditActor::subject(caller.subject.clone());
        if let Some((kernel, _)) = &self.kernel {
            kernel.freeze(reason, actor).await?;
            return Ok(());
        }
        let governance =
            self.governance.as_ref().ok_or_else(|| SurfaceError::unsupported("stop all"))?;
        governance.freeze_recorded(reason, actor).await?;
        Ok(())
    }

    async fn resume_all(&self, caller: &Caller) -> Result<()> {
        let actor = AuditActor::subject(caller.subject.clone());
        if let Some((kernel, _)) = &self.kernel {
            kernel.unfreeze(actor).await?;
            return Ok(());
        }
        let governance =
            self.governance.as_ref().ok_or_else(|| SurfaceError::unsupported("resume all"))?;
        governance.unfreeze_recorded(actor).await?;
        Ok(())
    }

    async fn stopped(&self) -> Result<bool> {
        if let Some((kernel, _)) = &self.kernel {
            return Ok(kernel.health().frozen);
        }
        Ok(self.governance.as_ref().is_some_and(GovernanceControl::is_frozen))
    }

    async fn mode(&self, user: &str, session: Option<&str>) -> Result<Option<HarnessMode>> {
        let Some(harness) = &self.harness else {
            return Ok(None);
        };
        match session {
            Some(session) => {
                let (user, session) = Self::ids(user, session)?;
                Ok(Some(harness.mode(&user, &session).await?))
            }
            None => Ok(Some(harness.agent().info().default_mode)),
        }
    }

    async fn set_mode(&self, caller: &Caller, session: &str, mode: HarnessMode) -> Result<()> {
        let harness =
            self.harness.as_ref().ok_or_else(|| SurfaceError::unsupported("changing the mode"))?;
        let (user, session) = Self::ids(caller.user_id(), session)?;
        harness.set_mode(&user, &session, mode).await?;
        Ok(())
    }

    // The area this source's turns run in, the primary agent's: with several areas, its spend
    // today against its own limit in force (spec 3.3 §10 K3, §13 Q7).
    async fn spend(&self, user: &str) -> Result<Option<SpendToday>> {
        let Some((kernel, target)) = &self.kernel else {
            return Ok(self.daily_limit.map(|limit| SpendToday { spent: 0, limit: Some(limit) }));
        };
        let area = kernel.partition_of_target(target).cloned().unwrap_or_default();
        let spent = self
            .processes(user)
            .await?
            .iter()
            .filter(|process| process.meta.partition == area)
            .map(|process| process.view.spend_today)
            .sum();
        let limit = match self.daily_limit {
            Some(limit) => Some(limit),
            None => kernel.area_settings(&area).await?.daily_spending_limit,
        };
        Ok(Some(SpendToday { spent, limit }))
    }

    fn quiet_hours(&self) -> Option<QuietHours> {
        self.kernel.as_ref().and_then(|(kernel, _)| kernel.config().quiet_hours)
    }

    fn serves_kernel_routes(&self) -> bool {
        self.kernel.as_ref().is_some_and(|(kernel, _)| kernel.serves_routes())
    }

    fn keeps_ledger(&self) -> bool {
        self.kernel.as_ref().is_some_and(|(kernel, _)| kernel.ledger().is_some())
    }

    async fn ledger(&self, since: DateTime<Utc>) -> Result<Vec<adk_kernel::proc::LedgerEntry>> {
        let Some(ledger) = self.kernel.as_ref().and_then(|(kernel, _)| kernel.ledger()) else {
            return Ok(Vec::new());
        };
        let mut entries = Vec::new();
        let mut query = LedgerQuery::default().from(since).limit(500);
        loop {
            let page = ledger.store().list(&query).await?;
            let Some(last) = page.last().map(|entry| entry.seq) else { break };
            let full = page.len() >= 500;
            entries.extend(page);
            if !full {
                break;
            }
            query = query.after(last);
        }
        Ok(entries)
    }

    fn keeps_agents(&self) -> bool {
        self.kernel.is_some()
    }

    async fn agent_definitions(&self, user: &str) -> Result<Vec<crate::agents::AgentDetail>> {
        let Some((kernel, _)) = &self.kernel else {
            return Ok(Vec::new());
        };
        crate::agents::local::definitions(kernel.agents(), user, PRIMARY_NAME, local_offset()).await
    }

    async fn agent(&self, user: &str, id: &str) -> Result<Option<crate::agents::AgentDetail>> {
        let Some((kernel, _)) = &self.kernel else {
            return Ok(None);
        };
        match crate::agents::local::agent(kernel.agents(), id, user, PRIMARY_NAME, local_offset())
            .await
        {
            Ok(detail) => Ok(Some(detail)),
            Err(SurfaceError::NotFound { .. }) => Ok(None),
            Err(error) => Err(error),
        }
    }

    async fn agent_choices(&self) -> Result<crate::agents::AgentChoices> {
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
        crate::agents::local::choices(kernel.agents(), kernel.partitions()).await
    }

    async fn preview_agent(
        &self,
        caller: &Caller,
        request: crate::agents::AgentPreviewRequest,
    ) -> Result<crate::agents::AgentPreview> {
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("agents of your own"))?;
        crate::agents::local::preview(kernel.agents(), caller, request).await
    }

    async fn add_agent(
        &self,
        caller: &Caller,
        draft: crate::agents::AgentDraft,
        digest: &str,
        replaces: Option<String>,
    ) -> Result<crate::agents::AgentDetail> {
        let action = adk_kernel::agents::AgentAction::Create {
            definition: draft.into_definition(),
            replaces,
        };
        self.apply_agent(caller, action, digest).await
    }

    async fn change_agent(
        &self,
        caller: &Caller,
        agent: &str,
        version: u64,
        draft: crate::agents::AgentDraft,
        digest: &str,
    ) -> Result<crate::agents::AgentDetail> {
        let action = adk_kernel::agents::AgentAction::Change {
            id: agent.to_string(),
            expected_version: version,
            definition: draft.into_definition(),
        };
        self.apply_agent(caller, action, digest).await
    }

    async fn pause_agent(
        &self,
        caller: &Caller,
        agent: &str,
    ) -> Result<crate::agents::AgentDetail> {
        let action = adk_kernel::agents::AgentAction::Pause { id: agent.to_string() };
        let digest = action.digest();
        self.apply_agent(caller, action, &digest).await
    }

    async fn resume_agent(
        &self,
        caller: &Caller,
        agent: &str,
    ) -> Result<crate::agents::AgentDetail> {
        let action = adk_kernel::agents::AgentAction::Resume { id: agent.to_string() };
        let digest = action.digest();
        self.apply_agent(caller, action, &digest).await
    }

    async fn remove_agent(
        &self,
        caller: &Caller,
        agent: &str,
        version: u64,
        digest: &str,
    ) -> Result<crate::agents::EndedWork> {
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("removing an agent"))?;
        let action = adk_kernel::agents::AgentAction::Remove {
            id: agent.to_string(),
            expected_version: version,
        };
        match crate::agents::local::apply(
            kernel.agents(),
            caller,
            action,
            digest,
            PRIMARY_NAME,
            local_offset(),
        )
        .await?
        {
            crate::agents::local::Applied::Removed(ended) => Ok(ended),
            crate::agents::local::Applied::Agent(_) => Ok(crate::agents::EndedWork::default()),
        }
    }

    async fn copy_rule_to_agent(&self, caller: &Caller, agent: &str, rule: &str) -> Result<String> {
        let harness =
            self.harness.as_ref().ok_or_else(|| SurfaceError::unsupported("copying a rule"))?;
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("copying a rule"))?;
        // Only an agent the person added and still has: never a suggestion, whose id may be
        // given again, nor a removed one.
        let added =
            kernel.agents().get(agent).await?.is_some_and(|view| view.agent.state.is_hosted());
        if !added {
            return Err(SurfaceError::not_found(format!("agent '{agent}'")));
        }
        let store = harness.agent().runtime().standing_rules().clone();
        let original = store
            .list(&self.app, caller.user_id())
            .await?
            .into_iter()
            .find(|candidate| candidate.id == rule)
            .ok_or_else(|| SurfaceError::not_found(format!("rule '{rule}'")))?;
        let pinned = adk_core::AgentPrincipal::derived(&self.app, agent).id.as_str().to_string();
        let copy = adk_harness::copy_rule_to(&original, &pinned, caller.subject.clone())?;
        let label = copy.label.clone();
        // Through the harness, which records `harness.rule.created` before the rule is
        // stored (spec 3.1 I39, spec 3.3 §11).
        let surface = serde_json::to_value(caller.surface)
            .ok()
            .and_then(|value| value.as_str().map(str::to_string))
            .unwrap_or_else(|| "surface".to_string());
        harness.agent().grant_rule(copy, &surface, None).await?;
        Ok(label)
    }

    async fn agent_threads(&self, user: &str, agent: &str) -> Result<Vec<(String, DateTime<Utc>)>> {
        let mut threads: BTreeMap<String, DateTime<Utc>> = BTreeMap::new();
        for process in self.processes(user).await? {
            if process.run.target != agent {
                continue;
            }
            if let Some(session) = process.run.session_id.clone() {
                let at = threads.entry(session).or_insert(process.run.updated_at);
                *at = (*at).max(process.run.updated_at);
            }
        }
        Ok(threads.into_iter().collect())
    }

    async fn agent_of_session(&self, user: &str, session: &str) -> Result<Option<String>> {
        if self.kernel.is_none() {
            return Ok(None);
        }
        let stamped = self
            .sessions
            .get(GetRequest {
                app_name: self.app.clone(),
                user_id: user.to_string(),
                session_id: session.to_string(),
                num_recent_events: Some(1),
                after: None,
            })
            .await
            .ok()
            .and_then(|found| found.state().get(adk_harness::AGENT_STATE_KEY))
            .and_then(|stamp| stamp.as_str().map(str::to_string));
        if stamped.is_some() {
            return Ok(stamped);
        }
        Ok(self
            .processes(user)
            .await?
            .into_iter()
            .find(|process| process.run.session_id.as_deref() == Some(session))
            .map(|process| process.run.target))
    }

    async fn start_turn_with(
        &self,
        caller: &Caller,
        agent: &str,
        session: &str,
        text: &str,
    ) -> Result<()> {
        let Some(target) = self.target_of(agent) else {
            return self.start_turn(caller, session, text).await;
        };
        let (kernel, _) =
            self.kernel.as_ref().ok_or_else(|| SurfaceError::unsupported("sending a message"))?;
        let user = caller.user_id();
        self.ensure_session(user, session).await?;
        let run = NewRun::new(
            QueueClass::Interactive.as_str(),
            self.app.clone(),
            user,
            target,
            serde_json::json!({ "text": text }),
        )
        .with_session_id(session)
        .with_authenticated_user();
        kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
        Ok(())
    }
}

impl LocalSource {
    /// Spawns an interactive run of `target` that starts from `content`.
    async fn spawn_content(
        &self,
        kernel: &Kernel,
        user: &str,
        session: &str,
        target: String,
        content: Content,
    ) -> Result<()> {
        let input = serde_json::json!({ "content": content });
        let run =
            NewRun::new(QueueClass::Interactive.as_str(), self.app.clone(), user, target, input)
                .with_session_id(session)
                .with_authenticated_user();
        kernel.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
        Ok(())
    }

    /// [`run_turn`](Self::run_turn) on a whole message, as `caller`.
    async fn run_content(
        &self,
        user: &str,
        session: &str,
        content: Content,
        caller: &Caller,
    ) -> Result<()> {
        let (user_id, session_id) = Self::ids(user, session)?;
        let context = RequestContext {
            user_id: caller.user_id().to_string(),
            scopes: caller.groups.clone(),
            metadata: Default::default(),
        };
        let stream = if let Some(harness) = &self.harness {
            harness.send_content_as(&user_id, &session_id, content, context).await
        } else if let Some(runner) = &self.runner {
            let config = adk_core::RunConfig {
                request_context: Some(context),
                ..runner.run_config().clone()
            };
            runner.run_with_config(user_id, session_id.clone(), content, Some(config)).await
        } else {
            return Err(SurfaceError::unsupported(
                "sending a message without a kernel, harness or runner",
            ));
        };
        let stream = stream?;
        let turn = self.turn_of(user, session);
        tokio::spawn(drain(stream, self.failed.clone(), turn));
        Ok(())
    }
}

/// The plan a held call is a step of, as its card shows it (spec 3.7 Q8).
#[cfg(feature = "computer-use")]
fn held_plan(held: &adk_harness::HeldScreenPlan) -> crate::source::HeldPlan {
    let plan = &held.plan;
    let steps = plan
        .steps
        .iter()
        .map(|step| crate::model::ScreenPlanStepView {
            operation: step
                .action
                .get("operation")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("action")
                .to_string(),
            target: step.target.as_ref().and_then(|target| target.bounds.as_ref()).map(|bounds| {
                let p = bounds.to_points();
                format!("({:.0}, {:.0})-({:.0}, {:.0}) pt", p.x, p.y, p.x + p.width, p.y + p.height)
            }),
            screenshot: step.target.as_ref().and_then(|target| target.screenshot_hash.clone()),
            proposed: step.proposed.clone(),
        })
        .collect();
    crate::source::HeldPlan {
        view: crate::model::ScreenPlanView {
            digest: plan.digest.clone(),
            window: plan.window.to_string(),
            steps,
        },
        text: held.render(),
        step: held.step,
        open: held.state == adk_harness::HeldPlanState::Open,
        fingerprints: held.fingerprints.clone(),
    }
}

/// A person's message: its text, then its images.
fn message_content(text: &str, images: &[crate::images::MessageImage]) -> Content {
    let mut content = Content::new("user");
    if !text.trim().is_empty() {
        content = content.with_text(text);
    }
    for image in images {
        content = content.with_inline_data(image.mime_type.clone(), image.data.clone());
    }
    content
}

/// Where `bash` runs, as the surface shows it (spec 3.3 §5.7).
fn shell_place(status: &adk_harness::IsolationStatus) -> crate::model::ShellPlace {
    use crate::model::ShellPlace;
    match status {
        adk_harness::IsolationStatus::Host => ShellPlace::Host,
        adk_harness::IsolationStatus::OsSandbox { enforcer } => {
            ShellPlace::Sandbox { enforcer: Some(enforcer.clone()) }
        }
        adk_harness::IsolationStatus::Container { image } => {
            ShellPlace::Container { image: image.clone() }
        }
        adk_harness::IsolationStatus::Remote { provider, off_host } => {
            ShellPlace::Remote { provider: provider.clone(), off_host: *off_host }
        }
        adk_harness::IsolationStatus::Degraded { requested, reason } => {
            ShellPlace::Degraded { requested: requested.clone(), reason: reason.clone() }
        }
        // An isolation a later harness adds is not claimed as a sandbox.
        _ => ShellPlace::Host,
    }
}

impl LocalSource {
    /// Resumes the session of a decided `request` (spec 3.3 §7.3): a durable run parked on the
    /// call is woken by the approval service; a call held in a plain run resumes with an
    /// empty turn, as `Harness::resume` does, as the person who answered when it is theirs.
    async fn resume_decided(
        &self,
        request: &ApprovalRequest,
        caller: Option<&Caller>,
    ) -> Result<()> {
        if request.run_id.is_some() && self.kernel.is_some() {
            return Ok(());
        }
        if self.harness.is_none() && self.runner.is_none() {
            return Ok(());
        }
        self.run_turn(&request.scope.user_id, &request.scope.session_id, "", caller).await
    }

    /// The sessions of `user` in this application with a run in flight, oldest first.
    fn active_sessions(&self, user: &str) -> Vec<String> {
        let runs = match (&self.harness, &self.runner) {
            (Some(harness), _) => harness.runner().active_runs(),
            (None, Some(runner)) => runner.active_runs(),
            (None, None) => Vec::new(),
        };
        let mut sessions: Vec<String> = runs
            .into_iter()
            .filter(|run| run.user_id.as_ref() == user && run.app_name.as_ref() == self.app)
            .map(|run| run.session_id.as_ref().to_string())
            .collect();
        sessions.sort();
        sessions.dedup();
        sessions
    }
}