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
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
//! The engine (spec 3.3 §6): the feed, the projection and the commands every surface shares.
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use adk_core::audit_log::{
AuditActor, AuditDecision, AuditRecordDraft, AuditRecordKind, AuditTrail,
};
use adk_core::{ApprovalDecision, ApprovalRequest, ApprovalState, Clock, SystemClock};
use chrono::{DateTime, FixedOffset, Local, Utc};
use futures::future::BoxFuture;
use futures::stream::{self, BoxStream, StreamExt};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::{Notify, oneshot};
use tokio::task::JoinHandle;
use crate::agents::{AgentDetail, AgentLife, GrantedUse};
use crate::answers::{AnswerLog, AnswerRecord, InMemoryAnswerLog, SURFACE_AUDIT_DECIDE};
use crate::error::{Result, SurfaceError};
use crate::hints::{CardHint, CardHints};
use crate::model::{
AgentRef, AgentRow, Briefing, Decided, DecisionCard, FeedEntry, Mode, ModeView, Reversibility,
Served, StatusLine,
};
use crate::origin::{Caller, Origin, SurfaceKind};
use crate::project::{self, Place, Projector};
use crate::rules::{self, Answer, Row};
use crate::source::{HeldPlan, Source, Steered, Steering};
use crate::words;
/// The audit action of "Send" and "Queue" (spec 3.3 §11).
pub const SURFACE_AUDIT_SEND: &str = "surface.send";
/// The audit action of a message sent to a running turn (spec 3.3 §6 "steer", §11): what
/// "Steer" was refused or offered, and how a message a turn held ended.
pub const SURFACE_AUDIT_STEER: &str = "surface.steer";
/// The audit action of **Stop the turn** (spec 3.3 §5.1), recorded before the turn stops.
pub const SURFACE_AUDIT_STOP_TURN: &str = "surface.stop_turn";
/// The audit action of "Stop all" (spec 3.3 §11).
pub const SURFACE_AUDIT_STOP_ALL: &str = "surface.stop_all";
/// The audit action of "Resume all" (spec 3.3 §11).
pub const SURFACE_AUDIT_RESUME_ALL: &str = "surface.resume_all";
/// The audit action of a mode change (spec 3.3 §11).
pub const SURFACE_AUDIT_SET_MODE: &str = "surface.set_mode";
/// The audit action of an app's call approved by the home's opt-in consent policy instead of
/// a person (spec 3.3 §6.1 `genui-apps`).
pub const SURFACE_AUDIT_APP_CALL_AUTO_APPROVED: &str = "surface.app.call_auto_approved";
/// The audit action of a drawn form's Send (spec 3.3 §7.4 rule 5, §11).
pub const SURFACE_AUDIT_DRAWN_SUBMITTED: &str = "surface.drawn.submitted";
/// The audit action of a person's approval of a form's call, sealed to the drawing they saw
/// (spec 3.3 §7.4 rule 5).
pub const SURFACE_AUDIT_DRAWN_SEALED: &str = "surface.drawn.sealed";
/// The audit action of an answer as it is given, written before it takes effect; its
/// `surface.decide` record says how it ended (spec 3.3 §11).
pub const SURFACE_AUDIT_ANSWER: &str = "surface.answer";
/// The audit action of a person changing an image before it leaves: the old digest, the new
/// one and the change, written before the call is held again (spec 3.7 §9.3 `vision.edit`).
pub const SURFACE_AUDIT_IMAGE_CHANGE: &str = "surface.image.change";
/// The audit action of a labelled example saved from the annotated viewer (spec 3.7 §8.2):
/// the session, the answer, the image's digest, the file, the case and the region kept.
pub const SURFACE_AUDIT_VISION_EXAMPLE: &str = "surface.vision.example";
/// The code an answer is recorded with when the images it names are not the call's.
const EVIDENCE_CHANGED: &str = "surface.evidence_changed";
/// What the agent is told of a call a person changed before it ran: it is held again, with
/// what it would send now, for their answer (spec 3.7 V-I5).
const HELD_AGAIN_REASON: &str = "The person changed this call before it ran. It is held again \
with the change, and the images it would send now, for their answer.";
/// How often the feed reads the session store when the source has nothing faster.
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(500);
/// The longest the delivery loop of queued input waits before it looks at the session again,
/// when nothing wakes it sooner. It waits as long as the session has an open decision or a
/// running turn, however long that is (spec 3.3 §7.3, S-I4).
const DRAIN_BACKOFF_MAX: Duration = Duration::from_secs(5);
tokio::task_local! {
/// The transcript digest of the spoken answer being recorded: every `surface.decide`
/// record written while it is in scope carries it, and none carries the words
/// (spec 3.3 §5.6).
static SPOKEN_DIGEST: String;
}
/// Runs `future` with the transcript digest `digest` in scope, when there is one.
async fn with_digest<F: std::future::Future>(digest: Option<String>, future: F) -> F::Output {
match digest {
Some(digest) => SPOKEN_DIGEST.scope(digest, future).await,
None => future.await,
}
}
/// A command from a surface (spec 3.3 §6). Every command runs as an authenticated
/// [`Caller`], whose subject, surface and [`Origin`] reach its audit record.
///
/// A message sent while a turn of its session runs reaches that turn (§6 "steer"): the
/// engine offers it through [`Source::steer`], the runtime screens it as it screens a turn's
/// own message, and the agent takes it at its next safe point. A turn that ends first hands
/// the message back, and it goes as the session's next message, once.
///
/// | Command | A turn of the session runs | Answers |
/// |---|---|---|
/// | [`Send`](Self::Send) | Offered to the turn; it waits in the session's queue until the turn takes it or hands it back | At once: [`Queued`](CommandOutcome::Queued) |
/// | [`Steer`](Self::Steer) | The same | Once the message has a fate: [`Steered`](CommandOutcome::Steered), or [`Queued`](CommandOutcome::Queued) when handed back |
/// | [`Queue`](Self::Queue) | Never offered: the session's next message | At once: [`Queued`](CommandOutcome::Queued) |
///
/// # Example
///
/// ```rust
/// use adk_surface::{Answer, Command};
///
/// let command: Command = serde_json::from_value(serde_json::json!({
/// "type": "decide",
/// "decisionId": "apr_1",
/// "version": 1,
/// "answer": "allowOnce",
/// }))
/// .unwrap();
/// assert!(matches!(command, Command::Decide { answer: Answer::AllowOnce, .. }));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Command {
/// Answers a decision at the version the surface saw (S-I2).
#[serde(rename_all = "camelCase")]
Decide {
/// The card's `id`.
decision_id: String,
/// The card's `version`.
version: u64,
/// The answer.
answer: Answer,
/// The changed arguments of an `edit`.
#[serde(default, skip_serializing_if = "Option::is_none")]
edited_args: Option<Value>,
/// Why, for a `deny`; reported to the agent.
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
/// The surface showed the call in full (§7.1).
#[serde(default)]
expanded: bool,
/// The digests of the images the surface showed, in the order of the card's media
/// (spec 3.7 §8.2): an answer that lets a call with images run names the images it
/// lets leave, and is refused when they are not the call's.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
evidence: Vec<String>,
},
/// Tightens the crop of one of a decision's images or covers more of it, then holds the
/// call again with the new image in its place (spec 3.7 §8.2, board choice A8): the crop
/// only shrinks and covering only grows. The decision at `version` closes; the call with
/// the new image waits for the person's answer.
#[serde(rename_all = "camelCase")]
ChangeImage {
/// The card's `id`.
decision_id: String,
/// The card's `version`.
version: u64,
/// The digest of the image the person changed, as the card showed it.
from: String,
/// The change.
change: crate::evidence::ImageChange,
/// Only make the new image and say its digest and size, holding nothing again: what
/// the editor shows before **Use this image** (board choice A8).
#[serde(default)]
preview: bool,
},
/// Cancels a spoken "allow once" inside its cancel window (§7.2).
#[serde(rename_all = "camelCase")]
CancelAnswer {
/// The decision.
decision_id: String,
},
/// Sends a message; queued instead while a decision of the session is open (S-I4). A
/// running turn of the session is offered it and takes it at its agent's next safe point;
/// a turn that ends first leaves it queued as the session's next message.
#[serde(rename_all = "camelCase")]
Send {
/// The session.
session_id: String,
/// The message.
text: String,
/// The images the person sent with it (spec 3.3 §5.1): at most
/// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
/// running turn; it goes as the session's next.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
images: Vec<crate::model::ImageData>,
},
/// Sends a message to the running turn of the caller's own session and waits for what
/// became of it (§6 "steer"): [`Steered`](CommandOutcome::Steered) when the turn took it,
/// [`Queued`](CommandOutcome::Queued) or [`Sent`](CommandOutcome::Sent) when it was handed
/// back and goes as the session's next message. A person sends it, never an agent.
#[serde(rename_all = "camelCase")]
Steer {
/// The session.
session_id: String,
/// The message.
text: String,
},
/// Stops the running turn of the caller's own session (spec 3.3 §5.1): a person only; the
/// agent waits for the next message, and nothing held for a decision is answered.
#[serde(rename_all = "camelCase")]
StopTurn {
/// The session.
session_id: String,
},
/// Queues a message as the session's next, after its open decisions (S-I4): never offered
/// to a running turn.
#[serde(rename_all = "camelCase")]
Queue {
/// The session.
session_id: String,
/// The message.
text: String,
/// The images the person sent with it (spec 3.3 §5.1): at most
/// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
/// running turn; it goes as the session's next.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
images: Vec<crate::model::ImageData>,
},
/// Stops every agent (S-I10).
#[serde(rename_all = "camelCase")]
StopAll {
/// Why.
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
},
/// Resumes after a stop: the web home or a paired local terminal only (S-I10).
ResumeAll,
/// Changes how much a session's agent acts on its own.
#[serde(rename_all = "camelCase")]
SetMode {
/// The session.
session_id: String,
/// The mode.
mode: Mode,
},
/// Starts a thread with `agent`: the session's first message goes to it, and its
/// harness stamps the session as its own (spec 3.3 §5.7 "Threads").
#[serde(rename_all = "camelCase")]
NewThread {
/// The agent: a roster row's name.
agent: String,
/// The new session.
session_id: String,
/// The first message.
text: String,
/// The images the person sent with it (spec 3.3 §5.1): at most
/// [`MAX_IMAGES`](crate::MAX_IMAGES). A message with images is never offered to a
/// running turn; it goes as the session's next.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
images: Vec<crate::model::ImageData>,
},
/// Adds an agent by hand, previewed with `digest` (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
AddAgent {
/// The definition.
draft: Box<crate::agents::AgentDraft>,
/// The digest of the preview the person confirmed.
digest: String,
/// The suggestion **Change it first** replaces, by the agent id it would get.
#[serde(default, skip_serializing_if = "Option::is_none")]
replaces: Option<String>,
},
/// Changes an agent at the version seen, previewed with `digest` (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
ChangeAgent {
/// The agent.
agent: String,
/// The version seen.
version: u64,
/// The definition after the change.
draft: Box<crate::agents::AgentDraft>,
/// The digest of the preview the person confirmed.
digest: String,
},
/// Pauses an agent (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
PauseAgent {
/// The agent.
agent: String,
},
/// Resumes an agent paused by hand: the web home or a paired local terminal (S-I10).
#[serde(rename_all = "camelCase")]
ResumeAgent {
/// The agent.
agent: String,
},
/// Removes an agent at the version seen, previewed with `digest` (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
RemoveAgent {
/// The agent.
agent: String,
/// The version seen.
version: u64,
/// The digest of the preview that named what ends.
digest: String,
},
/// Copies one of the person's standing rules to an agent, pinned to it (spec 3.3 §5.7
/// "Copy one of your rules", S-I19).
#[serde(rename_all = "camelCase")]
CopyRuleToAgent {
/// The agent.
agent: String,
/// The rule.
rule_id: String,
},
/// Sends a form an agent drew, from the version the person saw (spec 3.3 §7.4 rule 5):
/// never runs its tool, but asks for the call, which the drawing agent holds for the
/// person's decision. Only a person at a screen sends one (`keyboard`, `pointer`,
/// `touch`). Feature `genui`.
#[serde(rename_all = "camelCase")]
SubmitDrawn {
/// The session the form is in.
session_id: String,
/// The drawn surface.
surface_id: String,
/// The version the person saw.
version: u64,
/// The declared action the person used.
action_id: String,
/// What the person typed or picked, by the field's data path (`/to`).
#[serde(default)]
values: serde_json::Map<String, Value>,
},
}
/// What a command did (spec 3.3 §6).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum CommandOutcome {
/// This answer was recorded; `card.decided` says how it ended when it did.
#[serde(rename_all = "camelCase")]
Answered {
/// The decision after the answer.
card: DecisionCard,
},
/// Someone answered first: shown, never retried (S-I2).
#[serde(rename_all = "camelCase")]
AlreadyDecided {
/// Who answered, where, how and when.
decided: Decided,
/// The decision.
card: DecisionCard,
},
/// The decision changed since the version the surface saw and is still open: show it
/// again (S-I2).
#[serde(rename_all = "camelCase")]
Changed {
/// The decision now.
card: DecisionCard,
},
/// What a change to an image would make, held nowhere: the editor shows it before **Use
/// this image** (board choice A8).
#[serde(rename_all = "camelCase")]
ImagePreview {
/// The image the change would make: its digest and size, and the one it replaces.
changed: crate::evidence::ImageChanged,
},
/// The call was held again with what the person changed — its arguments, or one of its
/// images (spec 3.7 V-I5): `card` is the old decision, closed; the call waiting with the
/// new image follows in the feed.
#[serde(rename_all = "camelCase")]
HeldAgain {
/// The image change, when an image changed.
#[serde(default, skip_serializing_if = "Option::is_none")]
changed: Option<crate::evidence::ImageChanged>,
/// The old decision.
card: DecisionCard,
},
/// A spoken "allow once" takes effect at `cancel_until` unless cancelled (§7.2).
#[serde(rename_all = "camelCase")]
Pending {
/// The decision.
decision_id: String,
/// When it takes effect.
cancel_until: DateTime<Utc>,
/// "Allowing once in 5 seconds".
text: String,
},
/// A spoken answer was cancelled in its window.
#[serde(rename_all = "camelCase")]
AnswerCancelled {
/// The decision.
decision_id: String,
},
/// The message started a turn.
#[serde(rename_all = "camelCase")]
Sent {
/// The session.
session_id: String,
},
/// The session's running turn was stopped, or none was running (spec 3.3 §5.1).
#[serde(rename_all = "camelCase")]
TurnStopped {
/// The session.
session_id: String,
/// A turn was running and stopped.
stopped: bool,
/// "Stopped. Your agent waits for your next message."
text: String,
},
/// The session's running turn took the message at its agent's next safe point (§6
/// "steer"): the session holds it as event `event_id`, and the turn's next model call
/// carries it.
#[serde(rename_all = "camelCase")]
Steered {
/// The session.
session_id: String,
/// The id of the session event that carries the message.
event_id: String,
},
/// The message waits: until the session's open decisions are answered (S-I4), or until its
/// running turn takes it or ends.
#[serde(rename_all = "camelCase")]
Queued {
/// The session.
session_id: String,
/// Its place in the queue, from 1.
position: u32,
/// "Sent after this card is answered".
text: String,
},
/// Every agent stopped.
#[serde(rename_all = "camelCase")]
Stopped {
/// "All agents stopped".
text: String,
},
/// Agents run again.
Resumed,
/// The mode changed.
#[serde(rename_all = "camelCase")]
ModeSet {
/// The mode now.
mode: ModeView,
},
/// The agent was added (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
AgentAdded {
/// The agent now.
agent: crate::agents::AgentDetail,
},
/// The agent was changed.
#[serde(rename_all = "camelCase")]
AgentChanged {
/// The agent now.
agent: crate::agents::AgentDetail,
},
/// The agent was paused.
#[serde(rename_all = "camelCase")]
AgentPaused {
/// The agent now.
agent: crate::agents::AgentDetail,
},
/// The agent runs again.
#[serde(rename_all = "camelCase")]
AgentResumed {
/// The agent now.
agent: crate::agents::AgentDetail,
},
/// The agent was removed; its threads stay.
#[serde(rename_all = "camelCase")]
AgentRemoved {
/// What ended.
ended: crate::agents::EndedWork,
},
/// The agent changed since the version the surface showed: show it again (spec 3.3 §5.7).
#[serde(rename_all = "camelCase")]
AgentOutOfDate {
/// The agent now.
agent: crate::agents::AgentDetail,
/// "Finance was changed in the terminal at 10:01".
text: String,
},
/// A rule was copied to the agent (spec 3.3 S-I19).
#[serde(rename_all = "camelCase")]
RuleCopied {
/// The agent.
agent: String,
/// The rule's words.
label: String,
},
/// A drawn form was sent: its call is on its way to the drawing agent, which holds it for
/// the person's decision (spec 3.3 §7.4 rule 5). The form's state follows from that
/// decision, never from this answer.
#[serde(rename_all = "camelCase")]
FormSent {
/// The session.
session_id: String,
/// The drawn surface.
surface_id: String,
/// The version sent.
version: u64,
/// The call asked for.
call_id: String,
},
}
/// One frame of a session's feed (spec 3.3 §6): the snapshot, then the live tail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum FeedFrame {
/// One event of the session store; resume after its `seq` (`Last-Event-ID`).
#[serde(rename_all = "camelCase")]
Entry {
/// The entry.
entry: FeedEntry,
},
/// The session's open decisions changed.
#[serde(rename_all = "camelCase")]
Decisions {
/// The open decisions of the session.
cards: Vec<DecisionCard>,
},
/// The store's history of the session was replaced (rewound, or deleted and started
/// again): drop what was shown; the entries follow again from the start.
#[serde(rename_all = "camelCase")]
Reset {
/// How many events the store holds now.
len: u64,
},
/// An entry already sent changed: the turn after it ended in an error, which a
/// [`TurnFailed`](crate::ThreadItem::TurnFailed) item now says. Show it in place of the
/// entry with the same `seq`; resuming still goes after the last `seq` of an `Entry`.
#[serde(rename_all = "camelCase")]
Changed {
/// The entry, as it reads now.
entry: FeedEntry,
},
}
type Classify<T> = Arc<dyn Fn(&ApprovalRequest) -> T + Send + Sync>;
/// A session's failed turns as thread items, by the `seq` of the entry each follows.
type FailedTurns = std::collections::BTreeMap<u64, Vec<crate::model::ThreadItem>>;
/// One read of a session's feed: the frames to send, the cursor after them and the id of the
/// event at it, the open-decision signature and the failed turns the sent entries carry.
struct FeedRead {
frames: Vec<FeedFrame>,
sent: u64,
last: Option<String>,
cards: Vec<(String, u64)>,
failed: FailedTurns,
}
/// Builds a [`SurfaceEngine`].
pub struct SurfaceEngineBuilder {
source: Arc<dyn Source>,
audit: Option<AuditTrail>,
answers: Option<Arc<dyn AnswerLog>>,
projector: Projector,
quiet_set: bool,
poll: Duration,
clock: Arc<dyn Clock>,
voice_window: Duration,
stops_need: Option<String>,
card_hints: Vec<Arc<dyn CardHints>>,
granted: Vec<GrantedUse>,
#[cfg(feature = "genui")]
seals: Option<crate::genui::ApprovalSeals>,
cameras: Option<crate::camera::Cameras>,
}
impl fmt::Debug for SurfaceEngineBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SurfaceEngineBuilder")
.field("projector", &self.projector)
.finish_non_exhaustive()
}
}
impl SurfaceEngineBuilder {
/// Writes a record of every command to `trail` (spec 3.3 §11). Without one, commands are
/// not audited.
#[must_use]
pub fn audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
/// Keeps how each answer was given in `log` instead of in memory.
#[must_use]
pub fn answers(mut self, log: Arc<dyn AnswerLog>) -> Self {
self.answers = Some(log);
self
}
/// Where decisions are also shown, for "Also on your phone and in Telegram".
#[must_use]
pub fn places(mut self, places: impl IntoIterator<Item = Place>) -> Self {
self.projector.places = places.into_iter().collect();
self
}
/// Shows times at `offset` east of UTC instead of the host's time zone.
#[must_use]
pub fn utc_offset(mut self, offset: FixedOffset) -> Self {
self.projector.offset = offset;
self
}
/// Quiet time, overriding the source's.
#[must_use]
pub fn quiet_hours(mut self, quiet: adk_kernel::QuietHours) -> Self {
self.projector.quiet = Some(quiet);
self.quiet_set = true;
self
}
/// Shows the agent named `name` as `display_name`.
#[must_use]
pub fn agent_name(mut self, name: impl Into<String>, display_name: impl Into<String>) -> Self {
self.projector.names.insert(name.into(), display_name.into());
self
}
/// Writes a decision's heading — what will happen, in plain words — with `heading`
/// instead of from the tool and its main argument.
#[must_use]
pub fn heading(
mut self,
heading: impl Fn(&ApprovalRequest) -> String + Send + Sync + 'static,
) -> Self {
self.projector.heading = Arc::new(heading) as Classify<String>;
self
}
/// Tells calls that spend money with `money` instead of by the `payments_*` tool names.
#[must_use]
pub fn money(
mut self,
money: impl Fn(&ApprovalRequest) -> bool + Send + Sync + 'static,
) -> Self {
self.projector.money = Arc::new(money) as Classify<bool>;
self
}
/// Tells whether a call can be taken back with `reversibility`.
#[must_use]
pub fn reversibility(
mut self,
reversibility: impl Fn(&ApprovalRequest) -> Reversibility + Send + Sync + 'static,
) -> Self {
self.projector.reversibility = Arc::new(reversibility) as Classify<Reversibility>;
self
}
/// Adds `hints`, a feature's [`CardHints`], after those added before (spec 3.3 §7.1): for
/// each field of a card the first hint that sets it wins, and [`heading`](Self::heading),
/// [`money`](Self::money) and [`reversibility`](Self::reversibility) stay the fallback. A
/// hint may only make a card stricter or add words; it never adds an answer or changes the
/// risk (§7.2).
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_core::ApprovalRequest;
/// use adk_surface::{CardHint, CardHints, LocalSource, SurfaceEngine};
///
/// struct Payments;
///
/// #[async_trait::async_trait]
/// impl CardHints for Payments {
/// async fn hint(&self, request: &ApprovalRequest) -> Option<CardHint> {
/// let mine = request.origin.as_ref()?.source == "mcp:payments";
/// mine.then(|| CardHint::new().spends_money())
/// }
/// }
///
/// # fn example(source: LocalSource) {
/// let engine = SurfaceEngine::builder(Arc::new(source)).card_hints(Arc::new(Payments)).build();
/// # let _ = engine;
/// # }
/// ```
#[must_use]
pub fn card_hints(mut self, hints: Arc<dyn CardHints>) -> Self {
self.card_hints.push(hints);
self
}
/// Grants every agent the home runs `granted`, shown on its detail under "On this home it
/// can also:" (spec 3.3 §5.7, S-I12, S-I13). A host grants a use when it gives each agent
/// it runs the tools for it; a second grant with the same id replaces the first.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::{GrantedUse, LocalSource, SurfaceEngine};
///
/// # fn example(source: LocalSource) {
/// let engine = SurfaceEngine::builder(Arc::new(source))
/// .grant(GrantedUse::new(
/// "genui",
/// "Show forms and tables in your threads — sending asks you first",
/// ))
/// .build();
/// assert_eq!(engine.granted().len(), 1);
/// # }
/// ```
#[must_use]
pub fn grant(mut self, granted: GrantedUse) -> Self {
match self.granted.iter_mut().find(|known| known.id == granted.id) {
Some(known) => *known = granted,
None => self.granted.push(granted),
}
self
}
/// Seals each approval of a drawn form's call to the drawing the person saw, with
/// `seals` (spec 3.3 §7.4 rule 5); give the same seals to the harness that runs the
/// drawing agent (`HarnessAgentBuilder::requested_call_seal`), which checks them right
/// before the call runs.
#[cfg(feature = "genui")]
#[must_use]
pub fn approval_seals(mut self, seals: crate::genui::ApprovalSeals) -> Self {
self.seals = Some(seals);
self
}
/// Shows drawings in the extension catalog `catalog` too (spec 3.3 §6.1 `genui`,
/// extension catalogs): register every catalog the agents' render tools draw in
/// (`DrawToolset::catalog`). A drawing in a catalog not registered here is refused
/// ("this home does not render the catalog …").
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::genui::DrawToolset;
/// use adk_surface::{LocalSource, SurfaceEngine};
///
/// # fn example(source: LocalSource, toolset: DrawToolset) {
/// let engine = SurfaceEngine::builder(Arc::new(source)).with_catalog(toolset.catalog()).build();
/// assert_eq!(engine.catalogs().iter().count(), 2);
/// # }
/// ```
#[cfg(feature = "genui")]
#[must_use]
pub fn with_catalog(mut self, catalog: &'static crate::genui::Catalog) -> Self {
self.projector.catalogs = self.projector.catalogs.clone().with(catalog);
self
}
/// How often the feed reads the store when the source signals nothing sooner.
#[must_use]
pub fn poll_interval(mut self, poll: Duration) -> Self {
self.poll = poll;
self
}
/// The clock "waiting since" and quiet time are read against.
#[must_use]
pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
/// How long a spoken "allow once" can be cancelled (default
/// [`VOICE_CANCEL_WINDOW_SECS`](crate::rules::VOICE_CANCEL_WINDOW_SECS)).
#[must_use]
pub fn voice_cancel_window(mut self, window: Duration) -> Self {
self.voice_window = window;
self
}
/// Lets only callers in `group` give **Stop all** and **Resume all** (spec 3.3 §11
/// S-I10). Both act on every run the source makes, whoever started it, so a server that
/// admits more than one person keeps them for its operator; any other caller gets
/// `surface.operator_only`. Without it, every caller may.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::{LocalSource, SurfaceEngine};
///
/// # fn example(source: LocalSource) {
/// let engine = SurfaceEngine::builder(Arc::new(source)).stops_need("operator").build();
/// # let _ = engine;
/// # }
/// ```
#[must_use]
pub fn stops_need(mut self, group: impl Into<String>) -> Self {
self.stops_need = Some(group.into());
self
}
/// Serves the live camera surface over `cameras` (spec 3.7 §8.2): the routes under
/// `/surface/cameras` read and act on them. Without it they answer `surface.unsupported`.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::camera::Cameras;
/// use adk_surface::{LocalSource, SurfaceEngine};
///
/// # fn example(source: LocalSource, cameras: Cameras) {
/// let engine = SurfaceEngine::builder(Arc::new(source)).cameras(cameras).build();
/// # let _ = engine;
/// # }
/// ```
#[must_use]
pub fn cameras(mut self, cameras: crate::camera::Cameras) -> Self {
self.cameras = Some(cameras);
self
}
/// The engine.
pub fn build(mut self) -> SurfaceEngine {
if !self.quiet_set {
self.projector.quiet = self.source.quiet_hours();
}
// The source's rating counts beside the request's (spec 3.3 §7.2, spec 3.2 K-I9), so a
// call a kernel rates high needs presence or a paired local terminal on every surface.
let source = Arc::clone(&self.source);
let money = Arc::clone(&self.projector.money);
self.projector.money =
Arc::new(move |request| money(request) || source.moves_money(request));
let source = Arc::clone(&self.source);
self.projector.rates_high = Arc::new(move |request| source.rates_high(request));
// A drawn form's call never offers Always allow, whatever hints the host adds
// (spec 3.3 §7.4 rule 5, wave 4 decision 12).
#[cfg(feature = "genui")]
let drawn = Arc::new(crate::genui::DrawnHints::new(
Arc::clone(&self.source),
self.projector.clone(),
));
#[cfg(feature = "genui")]
self.card_hints.insert(0, Arc::clone(&drawn) as Arc<dyn CardHints>);
self.projector.voice_window_secs =
u32::try_from(self.voice_window.as_millis().div_ceil(1000)).unwrap_or(u32::MAX);
SurfaceEngine {
inner: Arc::new(Inner {
source: self.source,
projector: self.projector,
audit: self.audit,
answers: self.answers.unwrap_or_else(|| Arc::new(InMemoryAnswerLog::new())),
poll: self.poll,
clock: self.clock,
voice_window: self.voice_window,
stops_need: self.stops_need,
card_hints: self.card_hints,
granted: self.granted,
cameras: self.cameras,
#[cfg(feature = "genui")]
drawn,
#[cfg(feature = "genui")]
seals: self.seals,
queues: Mutex::new(HashMap::new()),
next_input: AtomicU64::new(1),
draining: Mutex::new(HashSet::new()),
wake: Notify::new(),
spoken: Mutex::new(HashMap::new()),
changed_images: Mutex::new(HashMap::new()),
served: Mutex::new(std::collections::BTreeSet::new()),
}),
}
}
}
/// The engine every surface runs on (spec 3.3 §6): it reads a [`Source`], projects what it
/// reads into cards, thread items, agent rows, the status line and the briefing, and carries
/// out commands under the rules of §7.2 and §7.4.
///
/// Surfaces hold no state a reconnect cannot rebuild: everything here is read from the
/// source's stores, except input queued behind an open decision or a running turn, which
/// waits in this process and is sent, oldest first, once the session is free — whichever
/// surface answered the decision. A message queued behind a running turn is offered to that
/// turn (§6 "steer"): it leaves the queue when the turn takes it, and stays in its place when
/// the turn hands it back, so it reaches the agent exactly once.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::{Caller, LocalSource, Origin, SurfaceEngine, SurfaceKind};
///
/// # async fn example(sessions: Arc<dyn adk_session::SessionService>, approvals: Arc<dyn adk_core::ApprovalService>) -> adk_surface::Result<()> {
/// let source = LocalSource::builder("adk-rust").sessions(sessions).approvals(approvals).build()?;
/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
/// let me = Caller::human("ana", SurfaceKind::Web, Origin::Pointer);
/// for card in engine.decisions(&me).await? {
/// println!("{} · {}", card.heading, card.status_text);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct SurfaceEngine {
inner: Arc<Inner>,
}
struct Inner {
source: Arc<dyn Source>,
projector: Projector,
audit: Option<AuditTrail>,
answers: Arc<dyn AnswerLog>,
poll: Duration,
clock: Arc<dyn Clock>,
voice_window: Duration,
/// The group Stop all and Resume all need, when only some callers may give them.
stops_need: Option<String>,
/// Features' card hints, in the order they were added (spec 3.3 §7.1).
card_hints: Vec<Arc<dyn CardHints>>,
/// What every agent the home runs may also do (spec 3.3 §5.7).
granted: Vec<GrantedUse>,
/// The cameras of the live camera surface (spec 3.7 §8.2).
cameras: Option<crate::camera::Cameras>,
/// The cards of drawn forms this engine sent (spec 3.3 §7.4 rule 5).
#[cfg(feature = "genui")]
drawn: Arc<crate::genui::DrawnHints>,
/// The seals of approvals of drawn forms' calls, when set.
#[cfg(feature = "genui")]
seals: Option<crate::genui::ApprovalSeals>,
/// Input queued behind an open decision or a running turn, per (user, session), oldest
/// first.
queues: Mutex<HashMap<(String, String), VecDeque<QueuedInput>>>,
/// The id of the next queued message.
next_input: AtomicU64,
/// Sessions with a delivery loop running. Changed only under the `queues` lock, so a
/// message queued while a loop ends always finds a loop.
draining: Mutex<HashSet<(String, String)>>,
/// Wakes the delivery loops to look again: an answer or a message through this engine.
wake: Notify,
/// Spoken "allow once" answers inside their cancel window, by decision.
spoken: Mutex<HashMap<String, Spoken>>,
/// Images a person changed through this engine, by the new image's digest: the digest it
/// replaced, which the card of the call held again names (spec 3.7 §8.2).
changed_images: Mutex<HashMap<String, String>>,
/// The parts of the home served beside the engine's routes that routers and the host named
/// ([`SurfaceEngine::serve`]).
served: Mutex<std::collections::BTreeSet<Served>>,
}
/// A send's audit fields, with how many images the message carries when it carries any.
fn with_images(mut fields: Value, images: usize) -> Value {
if images > 0 {
fields["images"] = json!(images);
}
fields
}
/// One message of a session's queue.
struct QueuedInput {
/// Names the message while it waits, whatever joins or leaves the queue.
id: u64,
text: String,
/// The images the person sent with it.
images: Vec<crate::images::MessageImage>,
/// The session's running turn holds it (spec 3.3 §6 "steer"): it is sent as the next
/// message only once the turn hands it back.
offered: bool,
}
/// A spoken "allow once" waiting out its cancel window.
struct Spoken {
/// The task that commits it.
handle: JoinHandle<()>,
/// Which answer this is: the task commits only while its own entry is here.
token: Arc<()>,
/// Who said it: only they cancel it.
user: String,
/// The decision.
request: ApprovalRequest,
/// The digest of what was said, for the record of its cancel (spec 3.3 §5.6).
digest: Option<String>,
}
impl fmt::Debug for SurfaceEngine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SurfaceEngine")
.field("app_name", &self.inner.source.app_name())
.field("projector", &self.inner.projector)
.finish_non_exhaustive()
}
}
impl SurfaceEngine {
/// A builder over `source`.
pub fn builder(source: Arc<dyn Source>) -> SurfaceEngineBuilder {
let offset = *Local::now().offset();
SurfaceEngineBuilder {
source,
audit: None,
answers: None,
projector: Projector::new(offset),
quiet_set: false,
poll: DEFAULT_POLL_INTERVAL,
clock: Arc::new(SystemClock),
voice_window: Duration::from_secs(u64::from(rules::VOICE_CANCEL_WINDOW_SECS)),
stops_need: None,
card_hints: Vec::new(),
granted: Vec::new(),
#[cfg(feature = "genui")]
seals: None,
cameras: None,
}
}
/// The source.
pub fn source(&self) -> &Arc<dyn Source> {
&self.inner.source
}
fn now(&self) -> DateTime<Utc> {
self.inner.clock.now()
}
/// The cameras of the live camera surface, when the engine serves them (spec 3.7 §8.2).
pub fn camera_hub(&self) -> Option<&crate::camera::Cameras> {
self.inner.cameras.as_ref()
}
/// The engine's clock, for the camera views.
pub(crate) fn clock_now(&self) -> DateTime<Utc> {
self.now()
}
/// How agents are named and times are shown.
pub(crate) fn projector(&self) -> &Projector {
&self.inner.projector
}
/// `Ok` when `session` is one of `caller`'s (S-I8), `surface.not_found` otherwise.
pub(crate) async fn owns_session(&self, caller: &Caller, session: &str) -> Result<()> {
self.transcript(caller, session).await.map(|_| ())
}
/// Sends `text` to `session` as `caller`'s message, queued behind an open decision or a
/// running turn as a typed message is.
pub(crate) async fn send_message(
&self,
caller: &Caller,
session: &str,
text: String,
) -> Result<CommandOutcome> {
self.send(caller, session.to_string(), text, Vec::new(), false, true).await
}
/// What every agent the home runs may also do, as the host granted it (spec 3.3 §5.7).
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use adk_surface::{LocalSource, SurfaceEngine};
///
/// # fn example(source: LocalSource) {
/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
/// assert!(engine.granted().is_empty());
/// # }
/// ```
pub fn granted(&self) -> &[GrantedUse] {
&self.inner.granted
}
/// The catalogs this engine shows drawings in: `forms` and every catalog registered with
/// [`SurfaceEngineBuilder::with_catalog`] (spec 3.3 §6.1 `genui`).
#[cfg(feature = "genui")]
pub fn catalogs(&self) -> &crate::genui::Catalogs {
&self.inner.projector.catalogs
}
/// How long a spoken answer, or a spoken screen action, can be cancelled (spec 3.3 §5.6).
#[cfg(feature = "verb-ui")]
pub(crate) fn voice_cancel_window(&self) -> Duration {
self.inner.voice_window
}
/// `detail` with what the home grants every agent it runs: only an agent that runs, added
/// or paused, is granted anything (spec 3.3 §5.7).
fn with_granted(&self, mut detail: AgentDetail) -> AgentDetail {
detail.granted = match detail.state {
AgentLife::Active | AgentLife::Paused => self.inner.granted.clone(),
AgentLife::Suggested
| AgentLife::Removing
| AgentLife::Removed
| AgentLife::Refused => Vec::new(),
};
detail
}
/// What the features say about `request`'s card, merged in the order they were added
/// (spec 3.3 §7.1).
async fn hint(&self, request: &ApprovalRequest) -> CardHint {
let mut merged = CardHint::new();
for hints in &self.inner.card_hints {
if let Some(hint) = hints.hint(request).await {
merged = merged.then(hint);
}
}
merged
}
// -----------------------------------------------------------------------
// Reads
// -----------------------------------------------------------------------
/// The decisions waiting for `caller`, oldest first, drawn from their inbox entries
/// (spec 3.3 §7.1, S-I1).
///
/// # Errors
///
/// Returns the source's error.
pub async fn decisions(&self, caller: &Caller) -> Result<Vec<DecisionCard>> {
self.open_decisions(caller, None).await
}
/// The decisions of one session waiting for `caller`, oldest first (spec 3.3 §10 C1).
///
/// # Errors
///
/// Returns the source's error.
pub async fn session_decisions(
&self,
caller: &Caller,
session: &str,
) -> Result<Vec<DecisionCard>> {
self.open_decisions(caller, Some(session)).await
}
async fn open_decisions(
&self,
caller: &Caller,
session: Option<&str>,
) -> Result<Vec<DecisionCard>> {
let mut requests: Vec<ApprovalRequest> = self
.inner
.source
.requests(caller, session, true)
.await?
.into_iter()
.filter(|request| {
owns(caller, request)
&& request.state == ApprovalState::Pending
&& session.is_none_or(|session| request.scope.session_id == session)
})
.collect();
requests.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
let held: HashSet<&str> =
requests.iter().map(|request| request.fingerprint.as_str()).collect();
let mut cards = Vec::with_capacity(requests.len());
for request in &requests {
// A later step of an open screen plan waits behind its first step's card: one card
// per plan (spec 3.7 Q8).
if let Some(plan) = self.inner.source.screen_plan(request).await
&& plan.step > 0
&& plan.open
&& plan.fingerprints.first().is_some_and(|first| held.contains(first.as_str()))
{
continue;
}
cards.push(self.card(caller, request).await?);
}
Ok(cards)
}
/// One decision as `caller` sees it: waiting, or decided with who, where and when.
///
/// # Errors
///
/// Returns `surface.not_found` when no decision of the caller has `id` (S-I8), or the
/// source's error.
pub async fn decision(&self, caller: &Caller, id: &str) -> Result<DecisionCard> {
let request = self.owned_request(caller, id).await?;
self.card(caller, &request).await
}
async fn owned_request(&self, caller: &Caller, id: &str) -> Result<ApprovalRequest> {
self.inner
.source
.request(id)
.await?
.filter(|request| owns(caller, request))
.ok_or_else(|| SurfaceError::not_found(format!("decision '{id}'")))
}
async fn card(&self, caller: &Caller, request: &ApprovalRequest) -> Result<DecisionCard> {
let always = match request.state {
ApprovalState::Pending => self.always_label(request).await,
_ => None,
};
let answer = match request.state {
ApprovalState::Pending => None,
// Where an answer was given only adds to the card; the card is shown without it.
_ => self.inner.answers.find_for(request).await.unwrap_or_else(|error| {
tracing::warn!(error = %error, decision.id = %request.id, "where a decision was answered could not be read");
None
}),
};
let hint = self.hint(request).await;
let mut card =
self.inner.projector.card(request, caller, always, answer.as_ref(), self.now(), &hint);
// A call held again after a person changed it closed this request with a refusal; it
// reads as the change it was (spec 3.7 V-I5).
if let (Some(decided), Some(record)) = (card.decided.as_mut(), answer.as_ref())
&& request.state == ApprovalState::Rejected
&& record.answer == Answer::Edit
&& record.approval_id == request.id
{
decided.answer = crate::model::DecidedAnswer::Edited;
decided.text = words::held_again_at(&decided.at_text);
if let Some(step) = card.timeline.last_mut() {
step.text = decided.text.clone();
}
}
self.add_media(caller, request, &hint, &mut card).await;
self.add_plan(caller, request, &hint, &mut card).await;
// How far a surface's answer reaches: once, or by the standing rule it made (§5.4).
if let (Some(decided), Some(record)) = (card.decided.as_mut(), answer.as_ref())
&& decided.via.is_some()
{
decided.scope_text = match record.answer {
Answer::AllowOnce => Some(words::DONE_ONCE.to_string()),
Answer::AlwaysAllow => self
.inner
.source
.always_allow_offer(request)
.await
.map(|offer| lower_first(&offer.label)),
Answer::Edit | Answer::Deny => None,
};
}
// An added agent is drawn with its own name and colour (spec 3.3 §5.7).
if let Some(detail) = self.inner.source.agent(caller.user_id(), &card.agent.name).await? {
card.agent = detail.agent;
}
// "How it got here" for a suggested agent: the suggesting turn, naming what it read.
if card.adds_agent.is_some()
&& let Ok(Some(events)) =
self.inner.source.transcript(caller.user_id(), &request.scope.session_id).await
{
let projector = &self.inner.projector;
let steps = crate::agents::suggestion_steps(
&events,
&card.agent.display_name,
request.created_at,
|at| projector.hh_mm(at),
);
let mut timeline: Vec<crate::model::TimelineStep> = steps
.into_iter()
.map(|text| crate::model::TimelineStep { text, current: false })
.collect();
// The suggesting turn's steps take the place of a hint's first step and "Asked at".
let asked = usize::from(hint.first_step.is_some()) + 1;
timeline.extend(card.timeline.into_iter().skip(asked));
card.timeline = timeline;
}
Ok(card)
}
/// The screen plan whose one card `request` carries (spec 3.7 Q8): the plan's first step,
/// while no one decided the plan, or once the request itself was decided.
async fn card_plan(&self, request: &ApprovalRequest) -> Option<HeldPlan> {
self.inner
.source
.screen_plan(request)
.await
.filter(|plan| plan.step == 0 && (plan.open || request.state != ApprovalState::Pending))
}
/// A screen plan's first step carries the plan's one card (spec 3.7 Q8): the plan's
/// heading, its window and every step with its target in place of the call, and only
/// **Allow** and **Deny** — **Allow** where the whole plan can be shown, once it was shown
/// in full. A chat card carries the heading alone (S-I5).
async fn add_plan(
&self,
caller: &Caller,
request: &ApprovalRequest,
hint: &CardHint,
card: &mut DecisionCard,
) {
let Some(plan) = self.card_plan(request).await else { return };
let steps = plan.view.steps.len();
let (text, truncated) = project::cut_call_text(plan.text.clone());
if rules::row(caller) == Row::Chat {
card.heading = words::screen_plan_chat_heading(steps);
card.call.truncated = truncated;
} else {
card.heading = project::capped(
&words::screen_plan_heading(steps, &plan.view.window),
project::CARD_HEADING_LIMIT,
);
card.call = crate::model::CallView {
tool: request.tool_name.clone(),
args: serde_json::to_value(&plan.view).unwrap_or(Value::Null),
text,
truncated,
};
card.detail = Some(crate::model::CardDetail::new(words::SCREEN_PLAN_DETAIL));
card.plan = Some(plan.view.clone());
}
if request.state == ApprovalState::Pending {
let mut facts = self.inner.projector.facts(request, None, hint);
facts.plan = true;
facts.truncated = truncated;
card.allowed = rules::allowed_answers(caller, &facts);
} else if let Some(decided) = card.decided.as_mut()
&& decided.answer == crate::model::DecidedAnswer::Edited
{
// The plan's binding is not a person's edit: the card reads as the yes it was.
decided.answer = crate::model::DecidedAnswer::Yes;
let phrase = decided.via.as_ref().map(crate::origin::Via::phrase);
decided.text = words::said(
(!decided.by_you).then_some(decided.by.as_str()),
words::SaidWhat::Yes,
phrase.as_deref(),
&decided.at_text,
);
if let Some(step) = card.timeline.last_mut() {
step.text = project::capped(&decided.text, project::CARD_LINE_LIMIT);
}
}
}
/// Closes `plan`'s open card, whose first step `request` holds, because everything was
/// stopped (spec 3.7 Q8, V-I17).
async fn close_plan(&self, request: &ApprovalRequest, plan: &HeldPlan) {
if let Err(error) = self
.inner
.source
.close_screen_plan(request, plan, words::STOP_ALL_CLOSED_THE_PLAN)
.await
{
tracing::warn!(error = %error, decision.id = %request.id, "a screen plan's card stayed open after a stop");
}
self.inner.wake.notify_waiters();
}
/// The caller's decisions answered or ended since `since`, newest first, for a surface
/// that opens again after a while, such as the phone (spec 3.3 §5.4).
///
/// # Errors
///
/// Returns the source's error.
pub async fn decided_since(
&self,
caller: &Caller,
since: DateTime<Utc>,
) -> Result<Vec<DecisionCard>> {
let decided_at = |request: &ApprovalRequest| {
request
.decisions
.last()
.map(|decision| decision.decided_at)
.or(request.resolved_at)
.unwrap_or(request.created_at)
};
let mut requests: Vec<ApprovalRequest> = self
.inner
.source
.requests(caller, None, false)
.await?
.into_iter()
.filter(|request| {
owns(caller, request)
&& request.state != ApprovalState::Pending
&& decided_at(request) >= since
})
.collect();
requests.sort_by(|a, b| decided_at(b).cmp(&decided_at(a)).then_with(|| a.id.cmp(&b.id)));
let mut cards = Vec::with_capacity(requests.len());
for request in &requests {
cards.push(self.card(caller, request).await?);
}
Ok(cards)
}
/// The label of "Always allow" for `request`, when the source can create its rule. A
/// request that needs more than one approver never offers it: the rule would let every
/// later call skip the other approvers (spec 3.3 §7.2, §8.2).
/// The images `request` holds, on its card, and what they change about its answers and
/// its timeline (spec 3.7 §8.2): a chat card carries none (S-I5), and a decision whose run
/// ended while it waits says so (board choice A12).
async fn add_media(
&self,
caller: &Caller,
request: &ApprovalRequest,
hint: &CardHint,
card: &mut DecisionCard,
) {
let waiting = request.state == ApprovalState::Pending;
if waiting && let Some(ended) = self.inner.source.run_ended(request).await {
let at_text = self.inner.projector.hh_mm(ended);
let minutes = (ended - request.created_at).num_minutes().max(0);
card.parked = Some(crate::model::ParkedView {
at: ended,
text: words::stopped_waiting(&card.agent.display_name, &at_text),
at_text: at_text.clone(),
});
let at = card.timeline.len().saturating_sub(1);
let step = crate::model::TimelineStep {
text: words::run_ended(minutes, &at_text),
current: false,
};
card.timeline.insert(at, step);
}
let decided = card.decided.as_ref().map(|decided| decided.answer);
let agent = card.agent.display_name.clone();
let Some(media) = self.media(request, hint, decided, &agent).await else { return };
if waiting {
rules::image_answers(rules::row(caller), self.image_gate(&media), &mut card.allowed);
if let Some(day) =
media.images.iter().find_map(|image| image.purged.as_ref()?.day.clone())
{
let at = card.timeline.len().saturating_sub(1);
let step = crate::model::TimelineStep {
text: words::image_deleted_step(&day),
current: false,
};
card.timeline.insert(at, step);
}
}
if rules::row(caller) != Row::Chat {
card.media = Some(media);
}
}
/// The media of `request`'s card, or `None` when it holds no image.
async fn media(
&self,
request: &ApprovalRequest,
hint: &CardHint,
decided: Option<crate::model::DecidedAnswer>,
agent: &str,
) -> Option<crate::evidence::CardMedia> {
let first = crate::evidence::images(request).first().map(|image| image.digest.clone())?;
let kept = self.inner.source.evidence_kept(request).await;
let replaces = {
let changed =
self.inner.changed_images.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
request
.args_redacted
.get("image")
.and_then(Value::as_str)
.and_then(|named| changed.get(named))
.or_else(|| changed.get(&first))
.cloned()
};
// "Open the source image" opens the annotated viewer when the source keeps the
// session's images and the feature named no other place (board choice A9).
let viewer_facts =
hint.media.as_ref().filter(|facts| facts.source_href.is_none()).and_then(|facts| {
let named = request.args_redacted.get("image").and_then(Value::as_str)?;
self.inner.source.keeps_vision_answers().then(|| {
facts.clone().with_source_href(crate::viewer::viewer_path(
&request.scope.session_id,
named,
))
})
});
crate::evidence::project(
request,
&crate::evidence::MediaInput {
facts: viewer_facts.as_ref().or(hint.media.as_ref()),
kept: &kept,
decided,
agent: agent.to_string(),
now: self.now(),
offset: self.inner.projector.offset,
can_change: self.inner.source.holds_again(),
replaces,
},
)
}
/// What the rules need to know of a card's images.
fn image_gate(&self, media: &crate::evidence::CardMedia) -> rules::ImageGate {
rules::ImageGate {
sendable: media.sendable(),
holds_again: self.inner.source.holds_again(),
}
}
/// The `index`th image decision `id` holds as evidence, for `caller` (spec 3.7 §8.3): only a
/// decision the caller may see, its bytes checked against the evidence's digest by the
/// source.
///
/// # Errors
///
/// `surface.not_found` when the caller has no such decision or image, or the image is no
/// longer kept; the source's error.
pub async fn evidence_image(
&self,
caller: &Caller,
id: &str,
index: usize,
) -> Result<crate::evidence::EvidenceBytes> {
let request = self.owned_request(caller, id).await?;
let missing = || SurfaceError::not_found(format!("image {index} of decision '{id}'"));
if index >= crate::evidence::images(&request).len() {
return Err(missing());
}
self.inner.source.evidence_image(&request, index).await?.ok_or_else(missing)
}
// -----------------------------------------------------------------------
// The annotated viewer (spec 3.7 §8.2, X12)
// -----------------------------------------------------------------------
/// The answer records of `session` for `caller`, parsed; a record that does not parse is
/// logged and left out.
async fn vision_records(
&self,
caller: &Caller,
session: &str,
) -> Result<Vec<crate::viewer::Record>> {
// Only the caller's own session (S-I8): the inbox's rule for a thread.
self.transcript(caller, session).await?;
let raw = self.inner.source.vision_answers(caller.user_id(), session).await?;
Ok(raw
.into_iter()
.filter_map(|value| match crate::viewer::Record::parse(value) {
Ok(record) => Some(record),
Err(error) => {
tracing::warn!(error = %error, session.id = %session, "an answer record is not shown");
None
}
})
.collect())
}
/// The annotated viewer of image `image` — a `sha256:` digest, or the name of an image
/// the session holds — in `caller`'s `session` (spec 3.7 §8.2, X12): every answer the
/// vision tools gave for it, `answer` shown (the newest otherwise), `compare` beside it.
///
/// # Errors
///
/// `surface.not_found` when the caller has no such session or the session no such image;
/// the source's error.
pub async fn viewer(
&self,
caller: &Caller,
session: &str,
image: &str,
answer: Option<&str>,
compare: Option<&str>,
) -> Result<crate::viewer::ViewerView> {
let records = self.vision_records(caller, session).await?;
let missing = || SurfaceError::not_found(format!("image '{image}' of session '{session}'"));
let digest = if image.starts_with("sha256:") {
image.to_string()
} else if let Some(record) = records.iter().find(|record| {
record.image.name.as_deref() == Some(image)
|| record.image.artifact.as_deref() == Some(image)
}) {
record.image.digest.clone()
} else {
let bytes = self
.inner
.source
.vision_image(caller.user_id(), session, image)
.await?
.ok_or_else(missing)?;
crate::evidence::digest_of(&bytes.bytes)
};
let records: Vec<crate::viewer::Record> =
records.into_iter().filter(|record| record.image.digest == digest).collect();
let agent = records.last().map(|record| record.agent.clone()).unwrap_or_default();
let files = self.inner.source.example_files(caller.user_id()).await?;
let input = crate::viewer::ViewerInput {
session,
agent_name: self.inner.projector.agent(&agent).display_name,
offset: self.inner.projector.offset,
can_save: files.is_some(),
files: files.unwrap_or_default(),
};
if let Some(view) = crate::viewer::view(&records, answer, compare, &input) {
return Ok(view);
}
// Nothing has answered for it yet: the picture alone.
let bytes = self.inner.source.vision_image(caller.user_id(), session, &digest).await?;
let bytes = match bytes {
Some(bytes) => bytes,
None => self
.inner
.source
.vision_image(caller.user_id(), session, image)
.await?
.ok_or_else(missing)?,
};
Ok(crate::viewer::unanswered(session, image, &digest, &bytes, &input))
}
/// The bytes of image `image` (a digest or a name) of `caller`'s `session`, checked
/// against its digest (spec 3.7 §8.3).
///
/// # Errors
///
/// `surface.not_found` when the caller has no such session or image; the source's error.
pub async fn viewer_image(
&self,
caller: &Caller,
session: &str,
image: &str,
) -> Result<crate::evidence::EvidenceBytes> {
self.transcript(caller, session).await?;
self.inner.source.vision_image(caller.user_id(), session, image).await?.ok_or_else(|| {
SurfaceError::not_found(format!("image '{image}' of session '{session}'"))
})
}
/// The `RegionSet` of answer `answer` in `caller`'s `session`, as the vision tools
/// published it (board choice V14); with `with`, both answers' sets in an array.
///
/// # Errors
///
/// `surface.not_found` when the caller has no such session or answer.
pub async fn viewer_export(
&self,
caller: &Caller,
session: &str,
answer: &str,
with: Option<&str>,
) -> Result<Value> {
let records = self.vision_records(caller, session).await?;
let set = |id: &str| {
crate::viewer::find(&records, id)
.map(|record| serde_json::to_value(&record.region_set).unwrap_or(Value::Null))
.ok_or_else(|| {
SurfaceError::not_found(format!("answer '{id}' of session '{session}'"))
})
};
match with {
Some(other) => Ok(Value::Array(vec![set(answer)?, set(other)?])),
None => set(answer),
}
}
/// Saves a labelled example from an answer in `caller`'s `session` (board choices V11–V13):
/// an `adk-eval` case in the eval set `example.file`, its image beside the file. The run's
/// answer is untouched; the example is recorded (`surface.vision.example`).
///
/// # Errors
///
/// `surface.not_found` when the caller has no such session or answer; `surface.invalid`
/// when the example does not fit the answer or the file; `surface.unsupported` when the
/// source saves no examples.
pub async fn save_example(
&self,
caller: &Caller,
session: &str,
example: &crate::viewer::LabelledExample,
) -> Result<crate::viewer::SavedExample> {
crate::viewer::check_file(&example.file).map_err(SurfaceError::Invalid)?;
let records = self.vision_records(caller, session).await?;
let record = crate::viewer::find(&records, &example.answer).ok_or_else(|| {
SurfaceError::not_found(format!("answer '{}' of session '{session}'", example.answer))
})?;
let case = crate::viewer::example_case(record, example).map_err(SurfaceError::Invalid)?;
let image = self
.inner
.source
.vision_image(caller.user_id(), session, &record.image.digest)
.await?
.ok_or_else(|| SurfaceError::not_found(format!("image '{}'", record.image.digest)))?;
let existing = self.inner.source.example_set(caller.user_id(), &example.file).await?;
let set = crate::viewer::with_case(existing, &example.file, case);
let image_path = crate::viewer::fixture_image_path(&record.image.digest, &image.mime_type);
// The example is on record before it is written (spec 3.3 §11).
self.record(
caller,
SURFACE_AUDIT_VISION_EXAMPLE,
json!({
"sessionId": session,
"answer": record.call_id,
"invocationId": record.invocation_id,
"tool": record.tool,
"imageDigest": record.image.digest,
"file": example.file,
"caseName": example.case_name,
"scope": example.scope,
"region": example.region,
}),
)
.await?;
self.inner.source.save_example(caller, &example.file, set, &image_path, &image).await?;
Ok(crate::viewer::SavedExample {
file: example.file.clone(),
case_name: example.case_name.clone(),
image: image_path,
text: format!(
"Saved to {} as {}. The run's answer stays as it was.",
example.file, example.case_name
),
})
}
async fn always_label(&self, request: &ApprovalRequest) -> Option<String> {
if request.policy.quorum > 1 {
return None;
}
self.inner.source.always_allow_offer(request).await.map(|offer| offer.label)
}
/// The session's thread: every event of its store, numbered by position (spec 3.3 §6).
///
/// # Errors
///
/// Returns `surface.not_found` when the caller has no such session (S-I8), or the
/// source's error.
pub async fn thread(&self, caller: &Caller, session: &str) -> Result<Vec<FeedEntry>> {
let events = self.transcript(caller, session).await?;
let links = self.links(caller, session, &events).await?;
let answered = project::answered_calls(&events);
let failed = self.failed_turns(caller, session, &events).await;
Ok(events
.iter()
.enumerate()
.map(|(index, event)| self.entry(index as u64 + 1, event, &links, &answered, &failed))
.collect())
}
/// The entry of the event at `seq`, ending with the turns `failed` says ended in an error
/// after it.
fn entry(
&self,
seq: u64,
event: &adk_core::Event,
links: &HashMap<u64, project::Link>,
answered: &HashSet<String>,
failed: &FailedTurns,
) -> FeedEntry {
let mut entry = self.inner.projector.entry(seq, event, links, answered);
entry.items.extend(failed.get(&seq).into_iter().flatten().cloned());
entry
}
/// The session's turns that ended in an error, as thread items keyed by the `seq` of the
/// last event before each ended. A turn that failed before the session held any event has
/// no entry to follow and is left out. When the source cannot say, the thread shows
/// without them.
async fn failed_turns(
&self,
caller: &Caller,
session: &str,
events: &[adk_core::Event],
) -> FailedTurns {
let failures = match self.inner.source.turn_failures(caller.user_id(), session).await {
Ok(failures) => failures,
Err(error) => {
tracing::warn!(session.id = %session, error = %error, "the turns that failed could not be read; the thread shows without them");
return FailedTurns::new();
}
};
let mut failed = FailedTurns::new();
for failure in failures {
let Some(index) = events.iter().rposition(|event| event.timestamp <= failure.at) else {
continue;
};
failed
.entry(index as u64 + 1)
.or_default()
.push(self.inner.projector.turn_failed(&failure));
}
failed
}
async fn transcript(&self, caller: &Caller, session: &str) -> Result<Vec<adk_core::Event>> {
self.inner
.source
.transcript(caller.user_id(), session)
.await?
.ok_or_else(|| SurfaceError::not_found(format!("session '{session}'")))
}
/// The inbox entry of each held call in the session's `events`, by `seq`
/// ([`project::links`]).
async fn links(
&self,
caller: &Caller,
session: &str,
events: &[adk_core::Event],
) -> Result<HashMap<u64, project::Link>> {
let requests: Vec<ApprovalRequest> = self
.inner
.source
.requests(caller, Some(session), false)
.await?
.into_iter()
.filter(|request| owns(caller, request) && request.scope.session_id == session)
.collect();
Ok(project::links(events, &requests))
}
/// The session's feed (spec 3.3 §6): every event after `after` (none: from the start) as
/// an [`Entry`](FeedFrame::Entry) numbered by its position in the session store, the
/// session's open decisions, then the live tail. Resuming with the last `seq` received
/// never skips or repeats an event.
///
/// While the stream runs, a history the store replaced — rewound, or deleted and started
/// again — sends [`Reset`](FeedFrame::Reset) and the entries again from the start, whether
/// it got shorter or grew back past what was sent. A client that resumes after `after`
/// is trusted to hold the store's events up to it.
///
/// A turn that ends in an error leaves no event, so the entry it follows is sent again as
/// [`Changed`](FeedFrame::Changed), ending with a
/// [`TurnFailed`](crate::ThreadItem::TurnFailed) item; a resumed stream sends each entry
/// before `after` that carries one.
///
/// The stream ends with an error when the session cannot be read.
pub fn feed(
&self,
caller: Caller,
session: String,
after: Option<u64>,
) -> BoxStream<'static, Result<FeedFrame>> {
struct State {
engine: SurfaceEngine,
caller: Caller,
session: String,
sent: u64,
/// The id of the event at `sent`, once this stream has read it.
last: Option<String>,
cards: Option<Vec<(String, u64)>>,
/// The failed turns the entries sent so far carry; `None` before the first read,
/// so a resumed stream sends again each entry before `after` whose turn failed.
failed: Option<FailedTurns>,
buffer: VecDeque<FeedFrame>,
/// The wait for the next change, begun before the last read so nothing that
/// changes during a read is missed; `None` when a change came during the read.
next: Option<BoxFuture<'static, ()>>,
first: bool,
done: bool,
}
let state = State {
engine: self.clone(),
caller,
session,
sent: after.unwrap_or(0),
last: None,
cards: None,
failed: None,
buffer: VecDeque::new(),
next: None,
first: true,
done: false,
};
stream::unfold(state, |mut state| async move {
loop {
if let Some(frame) = state.buffer.pop_front() {
return Some((Ok(frame), state));
}
if state.done {
return None;
}
if !state.first
&& let Some(next) = state.next.take()
{
next.await;
}
state.first = false;
let source = Arc::clone(&state.engine.inner.source);
let poll = state.engine.inner.poll;
let mut next: BoxFuture<'static, ()> =
Box::pin(async move { source.changed(poll).await });
state.next = match futures::poll!(next.as_mut()) {
std::task::Poll::Ready(()) => None,
std::task::Poll::Pending => Some(next),
};
match state
.engine
.refresh(
&state.caller,
&state.session,
state.sent,
&state.last,
&state.cards,
state.failed.as_ref(),
)
.await
{
Ok(read) => {
state.sent = read.sent;
state.last = read.last;
state.cards = Some(read.cards);
state.failed = Some(read.failed);
state.buffer.extend(read.frames);
}
Err(error) => {
state.done = true;
return Some((Err(error), state));
}
}
}
})
.boxed()
}
/// The frames since `sent`, with the new cursor, the id of the event at it, the
/// open-decision signature and the failed turns the sent entries now carry.
async fn refresh(
&self,
caller: &Caller,
session: &str,
mut sent: u64,
last: &Option<String>,
cards: &Option<Vec<(String, u64)>>,
shown: Option<&FailedTurns>,
) -> Result<FeedRead> {
let events = self.transcript(caller, session).await?;
let len = events.len() as u64;
let failed = self.failed_turns(caller, session, &events).await;
let mut frames = Vec::new();
let at_cursor = usize::try_from(sent)
.ok()
.and_then(|sent| sent.checked_sub(1))
.and_then(|index| events.get(index))
.map(|event| &event.id);
// Shorter than what was sent, or another event where the last one sent was: the
// store's history was replaced.
let replaced = last.as_ref().is_some_and(|last| at_cursor != Some(last));
if sent > len || replaced {
frames.push(FeedFrame::Reset { len });
sent = 0;
}
// Entries already sent whose failed turns changed since, such as the person's message
// of a turn whose model call has just failed.
let none = FailedTurns::new();
let before = shown.unwrap_or(&none);
let changed: Vec<u64> = failed
.keys()
.chain(before.keys())
.copied()
.filter(|seq| *seq <= sent && failed.get(seq) != before.get(seq))
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
if sent < len || !changed.is_empty() {
let links = self.links(caller, session, &events).await?;
let answered = project::answered_calls(&events);
for seq in changed {
if let Some(event) = usize::try_from(seq - 1).ok().and_then(|at| events.get(at)) {
let entry = self.entry(seq, event, &links, &answered, &failed);
frames.push(FeedFrame::Changed { entry });
}
}
for (index, event) in
events.iter().enumerate().skip(usize::try_from(sent).unwrap_or(usize::MAX))
{
let entry = self.entry(index as u64 + 1, event, &links, &answered, &failed);
frames.push(FeedFrame::Entry { entry });
}
sent = len;
}
let last = usize::try_from(sent)
.ok()
.and_then(|sent| sent.checked_sub(1))
.and_then(|index| events.get(index))
.map(|event| event.id.clone());
let open = self.session_decisions(caller, session).await?;
let signature: Vec<(String, u64)> =
open.iter().map(|card| (card.id.clone(), card.version)).collect();
if cards.as_ref() != Some(&signature) {
frames.push(FeedFrame::Decisions { cards: open });
}
Ok(FeedRead { frames, sent, last, cards: signature, failed })
}
/// The caller's agents (spec 3.3 §8.1).
///
/// # Errors
///
/// Returns the source's error.
pub async fn agents(&self, caller: &Caller) -> Result<Vec<AgentRow>> {
let rows: Vec<AgentRow> = self
.inner
.source
.agents(caller.user_id())
.await?
.iter()
.map(|state| self.inner.projector.agent_row(state))
.collect();
// The person's own agents join the roster from their definitions, so one that has
// never run is listed as Ready (spec 3.3 §5.7 "The roster").
let definitions = self.inner.source.agent_definitions(caller.user_id()).await?;
let can_change =
!matches!(caller.origin, Origin::Agent { .. }) && rules::may_change_agents(caller);
Ok(crate::agents::roster(rows, &definitions, can_change))
}
/// How `caller` answered since `since` (spec 3.3 §5.1 "How you answered"): each answer
/// counted, and on which surfaces.
///
/// # Errors
///
/// Returns the answer log's error.
pub async fn answers_since(
&self,
caller: &Caller,
since: DateTime<Utc>,
) -> Result<crate::answers::AnswerSummary> {
let mine: Vec<AnswerRecord> = self
.inner
.answers
.since(since)
.await?
.into_iter()
.filter(|record| record.by.id == caller.user_id())
.collect();
Ok(crate::answers::AnswerSummary::of(since, &mine))
}
/// The threads `caller` has with `agent`, newest first (spec 3.3 §5.1 "Thread history"):
/// each session and when it last changed.
///
/// # Errors
///
/// Returns the source's error.
pub async fn agent_threads(
&self,
caller: &Caller,
agent: &str,
) -> Result<crate::agents::AgentThreads> {
let offset = self.inner.projector.offset;
let mut threads: Vec<crate::agents::ThreadSummary> = self
.inner
.source
.agent_threads(caller.user_id(), agent)
.await?
.into_iter()
.map(|(session_id, at)| crate::agents::ThreadSummary {
session_id,
at,
when: at.with_timezone(&offset).format("%-d %b %H:%M").to_string(),
})
.collect();
threads.sort_by_key(|thread| std::cmp::Reverse(thread.at));
Ok(crate::agents::AgentThreads { agent: agent.to_string(), threads })
}
/// The agents `caller` removed, each with its threads, which stay readable (spec 3.3
/// §5.7, §13 decision 18): what "Removed agents" at the roster's foot lists.
///
/// # Errors
///
/// Returns the source's error.
pub async fn removed_agents(
&self,
caller: &Caller,
) -> Result<Vec<crate::agents::RemovedAgent>> {
let source = &self.inner.source;
let mut removed = Vec::new();
for detail in source.agent_definitions(caller.user_id()).await? {
if detail.state != crate::agents::AgentLife::Removed {
continue;
}
let threads = source.agent_threads(caller.user_id(), &detail.id).await?;
removed.push(crate::agents::RemovedAgent::of(
&detail,
threads,
self.inner.projector.offset,
));
}
removed.sort_by(|a, b| {
a.agent.display_name.to_lowercase().cmp(&b.agent.display_name.to_lowercase())
});
Ok(removed)
}
/// Every agent `caller` added, removed ones included, with its version: what the
/// terminal's `--output json` compares, so a change to any field is one line (spec 3.3
/// §5.7).
///
/// # Errors
///
/// Returns the source's error.
pub async fn agent_details(&self, caller: &Caller) -> Result<Vec<crate::agents::AgentDetail>> {
let details = self.inner.source.agent_definitions(caller.user_id()).await?;
Ok(details.into_iter().map(|detail| self.with_granted(detail)).collect())
}
/// The agent a message goes to when the person names none (spec 3.3 §5.5): the tray's
/// "Ask Finance". `None` when the source has no single primary agent
/// ([`Source::primary_agent`]).
pub fn primary_agent(&self) -> Option<AgentRef> {
self.inner.source.primary_agent().map(|name| self.inner.projector.agent(&name))
}
/// The status line (spec 3.3 §5.1): the mode word of `session` (or the default), spend
/// against the daily limit, quiet time, and the count of decisions.
///
/// # Errors
///
/// Returns the source's error.
pub async fn status(&self, caller: &Caller, session: Option<&str>) -> Result<StatusLine> {
let source = &self.inner.source;
let decisions = self.decisions(caller).await?.len();
let stopped = source.stopped().await?;
Ok(StatusLine {
mode: source.mode(caller.user_id(), session).await?.map(project::mode_view),
spend: source.spend(caller.user_id()).await?.map(project::spend_view),
quiet: self.inner.projector.quiet_view(self.now()),
decisions: u32::try_from(decisions).unwrap_or(u32::MAX),
stopped,
stopped_text: stopped.then(|| words::ALL_AGENTS_STOPPED.to_string()),
host_utc_offset_minutes: Some(
self.now().with_timezone(&Local).offset().local_minus_utc() / 60,
),
serves: self.serves(),
})
}
/// Names `part` among the parts of the home this server serves beside the engine's
/// routes, so the web home reads its routes ([`StatusLine::serves`]). adk-surface's routers
/// name their own as they are built; a host names a part it mounts from elsewhere, such as
/// the website's desk.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_session::InMemorySessionService;
/// use adk_surface::{LocalSource, Served, SurfaceEngine};
///
/// let source = LocalSource::builder("adk-rust")
/// .sessions(Arc::new(InMemorySessionService::new()))
/// .build()
/// .unwrap();
/// let engine = SurfaceEngine::builder(Arc::new(source)).build();
/// engine.serve(Served::Website);
/// assert_eq!(engine.serves(), vec![Served::Website]);
/// ```
pub fn serve(&self, part: Served) {
self.inner.served.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(part);
}
/// The parts of the home this server serves beside the engine's routes, in order: those
/// named with [`serve`](Self::serve), the cameras when the engine has a camera hub, and the
/// kernel's control plane when the source's kernel built its routes.
pub fn serves(&self) -> Vec<Served> {
let mut parts =
self.inner.served.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
if self.inner.cameras.is_some() {
parts.insert(Served::Cameras);
}
if self.inner.source.serves_kernel_routes() {
parts.insert(Served::Kernel);
}
parts.into_iter().collect()
}
/// "While you were away" since `since` (spec 3.3 §5.1, §8.1): spend, waiting decisions,
/// and one line per event on the `/proc` ledger — the events the kernel's
/// `GET /kernel/away` lists (§10 K4) — each agent by the name the roster gives it.
///
/// # Errors
///
/// Returns the source's error.
pub async fn briefing(&self, caller: &Caller, since: DateTime<Utc>) -> Result<Briefing> {
let source = &self.inner.source;
let lines = source
.ledger(since)
.await?
.iter()
.filter_map(|entry| self.inner.projector.briefing_line(entry))
.collect();
let waiting = self.decisions(caller).await?.len();
Ok(Briefing {
title: words::WHILE_YOU_WERE_AWAY.to_string(),
since,
since_text: words::briefing_since(&self.inner.projector.hh_mm(since)),
spend: source.spend(caller.user_id()).await?.map(project::spend_view),
waiting: u32::try_from(waiting).unwrap_or(u32::MAX),
lines,
recorded: source.keeps_ledger(),
})
}
// -----------------------------------------------------------------------
// Commands
// -----------------------------------------------------------------------
/// Carries out `command` as `caller` (spec 3.3 §6, §7.2, §7.4, §11).
///
/// # Errors
///
/// | Code | When |
/// |---|---|
/// | `surface.not_found` | No decision or session of the caller has that id (S-I8); a `Steer` to a session that is not the caller's |
/// | `surface.answer_not_allowed` | The surface may not give this answer (§7.2) |
/// | `surface.confirm_presence` | A high-risk approval without confirming it is you |
/// | `surface.call_not_expanded` | A truncated call approved before it was expanded |
/// | `surface.not_here` | An agent answering or steering, resuming outside the home, loosening the mode from chat or voice, a `Steer` while everything is stopped |
/// | `surface.operator_only` | Stop all or Resume all from a caller outside the group [`stops_need`](SurfaceEngineBuilder::stops_need) names |
/// | `surface.invalid` | A spoken answer: it goes through `decide_spoken` with its transcript (feature `voice`) |
/// | `surface.unsupported` | The source cannot do it |
/// | the source's code | The source failed |
pub async fn execute(&self, caller: &Caller, command: Command) -> Result<CommandOutcome> {
match command {
// A spoken answer is recorded with its transcript's digest (spec 3.3 §5.6).
Command::Decide { .. } if rules::row(caller) == Row::Voice => {
Err(SurfaceError::Invalid(
"a spoken answer goes through decide_spoken with its transcript".into(),
))
}
Command::Decide {
decision_id,
version,
answer,
edited_args,
reason,
expanded,
evidence,
} => {
self.decide(
caller,
&decision_id,
version,
answer,
edited_args,
reason,
(expanded, evidence),
None,
)
.await
}
Command::ChangeImage { decision_id, version, from, change, preview } => {
self.change_image(caller, &decision_id, version, &from, change, preview).await
}
Command::CancelAnswer { decision_id } => self.cancel_answer(caller, &decision_id).await,
Command::Send { session_id, text, images } => {
let images = crate::images::decode(&images)?;
self.send(caller, session_id, text, images, false, true).await
}
Command::Steer { session_id, text } => self.steer(caller, session_id, text).await,
Command::StopTurn { session_id } => self.stop_turn(caller, session_id).await,
Command::Queue { session_id, text, images } => {
let images = crate::images::decode(&images)?;
self.send(caller, session_id, text, images, true, false).await
}
Command::StopAll { reason } => {
self.may_stop(caller)?;
self.stop_all(caller, reason).await
}
Command::ResumeAll => {
self.may_stop(caller)?;
self.resume_all(caller).await
}
Command::SetMode { session_id, mode } => self.set_mode(caller, &session_id, mode).await,
Command::NewThread { agent, session_id, text, images } => {
let images = crate::images::decode(&images)?;
self.new_thread(caller, &agent, session_id, text, images).await
}
command @ (Command::AddAgent { .. }
| Command::ChangeAgent { .. }
| Command::PauseAgent { .. }
| Command::ResumeAgent { .. }
| Command::RemoveAgent { .. }
| Command::CopyRuleToAgent { .. }) => self.agent_command(caller, command).await,
Command::SubmitDrawn { session_id, surface_id, version, action_id, values } => {
self.submit_drawn(caller, session_id, surface_id, version, &action_id, &values)
.await
}
}
}
/// Sends a drawn form (spec 3.3 §7.4 rule 5), checked in order: the session is the
/// caller's (S-I8), the caller is a person at a screen, the surface is at `version`, the
/// action is declared, and the values fit their fields. Then it is recorded and the call
/// is asked for; nothing runs until the person decides.
#[cfg(feature = "genui")]
async fn submit_drawn(
&self,
caller: &Caller,
session: String,
surface: String,
version: u64,
action: &str,
values: &serde_json::Map<String, Value>,
) -> Result<CommandOutcome> {
let events = self.transcript(caller, &session).await?;
if !matches!(caller.origin, Origin::Keyboard | Origin::Pointer | Origin::Touch) {
return Err(SurfaceError::NotHere(words::SEND_FORMS_FROM_A_SCREEN.to_string()));
}
let sent = crate::genui::submission(
&events,
&self.inner.projector.catalogs,
&surface,
version,
action,
values,
)?;
// A running turn writes the session meanwhile, so the call waits until it ends, as a
// message does: a second run would interleave its events with the turn's (S-I4).
let key = (caller.user_id().to_string(), session.clone());
let queued = self
.inner
.queues
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&key)
.is_some_and(|queued| !queued.is_empty())
|| self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).contains(&key);
if queued || self.inner.source.busy(caller.user_id(), &session).await? {
return Err(SurfaceError::Invalid(words::SEND_FORM_WHEN_FREE.to_string()));
}
let call = adk_core::RequestedCall::new(
sent.tool.clone(),
sent.args.clone(),
caller.subject.clone(),
adk_core::RequestedVia::form(surface.clone(), version, action)
.with_digest(sent.digest.clone()),
);
let call_id = call.function_call_id.clone();
if !self.inner.drawn.begin_send(
caller.user_id(),
&session,
(&surface, version),
&call,
&events,
) {
return Err(SurfaceError::Invalid(words::FORM_BEING_SENT.to_string()));
}
// Recorded before it is asked for: a send whose record failed is never asked for. The
// record carries digests, never the values: the arguments' digest is the one the
// call's own approval records carry.
let args_digest = self.inner.audit.as_ref().map(|trail| trail.digest(&sent.args));
let asked = async {
self.record(
caller,
SURFACE_AUDIT_DRAWN_SUBMITTED,
json!({
"sessionId": session,
"surfaceId": surface,
"version": version,
"actionId": action,
"tool": sent.tool,
"argsDigest": args_digest,
"valuesDigest": sent.values_digest,
"callId": call_id,
"drawnBy": sent.drawn_by,
"drawingDigest": sent.digest,
}),
)
.await?;
self.inner.source.request_call(caller, &session, "", call).await
};
if let Err(error) = asked.await {
self.inner.drawn.withdraw(&call_id);
return Err(error);
}
Ok(CommandOutcome::FormSent { session_id: session, surface_id: surface, version, call_id })
}
/// The session's events, when it is the caller's own (S-I8): what an app in it showed.
#[cfg(feature = "genui-apps")]
pub(crate) async fn app_transcript(
&self,
caller: &Caller,
session: &str,
) -> Result<Vec<adk_core::Event>> {
self.transcript(caller, session).await
}
/// Approves the waiting decision `decision_id` by the home's policy `policy` (spec 3.3
/// §6.1 `genui-apps`, opt-in tiered consent the person set): decided as the person, the
/// rule recorded as `surface.app.call_auto_approved` and on the decision, then resumed like
/// their answer.
#[cfg(feature = "genui-apps")]
pub(crate) async fn approve_by_policy(
&self,
caller: &Caller,
decision_id: &str,
version: u64,
policy: &str,
ext: Value,
) -> Result<()> {
let mut fields = json!({ "approvalId": decision_id, "policy": policy, "initiator": "app" });
if let (Some(fields), Value::Object(ext)) = (fields.as_object_mut(), ext) {
fields.extend(ext);
}
self.record(caller, SURFACE_AUDIT_APP_CALL_AUTO_APPROVED, fields).await?;
// The person's own standing consent: decided as them, the rule on the record.
let mut decision =
ApprovalDecision::approve(caller.subject.clone()).with_groups(caller.groups.clone());
decision.reason = Some(format!("approved by the home's {policy} consent"));
let updated = self.inner.source.decide(decision_id, version, decision).await?;
if updated.state != ApprovalState::Pending {
if let Err(error) = self.inner.source.resolved_by(caller, &updated).await {
tracing::warn!(error = %error, decision.id = %updated.id, "the approved call could not be resumed");
}
self.spawn_drain(caller.clone(), updated.scope.session_id.clone());
}
Ok(())
}
/// Asks for `call`, a tool call the app from `app` asked for in `session` (spec 3.3 §6.1
/// `genui-apps`): held as the agent whose call showed the app, for the person's decision,
/// whose card says "The app from Weather asked" and never offers **Always allow**.
#[cfg(feature = "genui-apps")]
pub(crate) async fn ask_for_app_call(
&self,
caller: &Caller,
session: &str,
call: adk_core::RequestedCall,
app: &str,
) -> Result<()> {
self.inner.drawn.app_asked(caller.user_id(), session, &call, app);
self.inner.source.request_call(caller, session, "", call).await
}
#[cfg(not(feature = "genui"))]
async fn submit_drawn(
&self,
caller: &Caller,
session: String,
_surface: String,
_version: u64,
_action: &str,
_values: &serde_json::Map<String, Value>,
) -> Result<CommandOutcome> {
self.transcript(caller, &session).await?;
Err(SurfaceError::unsupported("sending a form an agent drew"))
}
/// Answers a decision by voice (spec 3.3 §5.6, §7.2): the one way a spoken answer is
/// recorded. `transcript` is what the person said; every `surface.decide` record of the
/// answer carries its SHA-256 as `transcriptDigest`, and none carries the words.
///
/// The voice row of §7.2 applies: **Allow once** for an everyday call, which waits out
/// the cancel window ([`CommandOutcome::Pending`]; its end arrives on
/// [`SpokenAnswer::settled`](crate::voice::SpokenAnswer::settled)), and **Deny** for any
/// call. The call counts as not expanded, so a call shown truncated is decided on screen.
///
/// # Errors
///
/// `surface.invalid` when `caller` is not on the voice surface with origin voice; the
/// codes of [`execute`](Self::execute) otherwise.
///
/// # Example
///
/// ```rust,no_run
/// use adk_surface::{Answer, Caller, CommandOutcome, Origin, SurfaceEngine, SurfaceKind};
///
/// # async fn example(engine: SurfaceEngine, id: &str, version: u64) -> adk_surface::Result<()> {
/// let ana = Caller::human("ana", SurfaceKind::Voice, Origin::Voice);
/// let spoken = engine.decide_spoken(&ana, id, version, Answer::AllowOnce, "allow once").await?;
/// if let CommandOutcome::Pending { text, .. } = &spoken.outcome {
/// println!("{text}");
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "voice")]
pub async fn decide_spoken(
&self,
caller: &Caller,
decision_id: &str,
version: u64,
answer: Answer,
transcript: &str,
) -> Result<crate::voice::SpokenAnswer> {
use sha2::Digest as _;
if caller.origin != Origin::Voice || caller.surface != crate::origin::SurfaceKind::Voice {
return Err(SurfaceError::Invalid(
"decide_spoken records a spoken answer: the caller is on the voice surface and \
its origin is voice"
.into(),
));
}
let digest = format!("{:x}", sha2::Sha256::digest(transcript.as_bytes()));
let (settle, settled) = oneshot::channel();
let outcome = with_digest(
Some(digest),
self.decide(
caller,
decision_id,
version,
answer,
None,
None,
(false, Vec::new()),
Some(settle),
),
)
.await?;
let settled = matches!(outcome, CommandOutcome::Pending { .. }).then_some(settled);
Ok(crate::voice::SpokenAnswer { outcome, settled })
}
#[allow(clippy::too_many_arguments)]
async fn decide(
&self,
caller: &Caller,
id: &str,
version: u64,
answer: Answer,
edited_args: Option<Value>,
reason: Option<String>,
(expanded, evidence): (bool, Vec<String>),
settle: Option<oneshot::Sender<Result<CommandOutcome>>>,
) -> Result<CommandOutcome> {
let request = self.owned_request(caller, id).await?;
if let Origin::Agent { agent } = &caller.origin {
let error = SurfaceError::NotHere(format!(
"an agent ({agent}) never answers a decision; it waits for a person (spec 3.3 §7.4)"
));
self.audit_decide(caller, &request, answer, "refused", Some(&error.code())).await?;
return Err(error);
}
if request.state != ApprovalState::Pending {
return self.already_decided(caller, &request, answer).await;
}
let always = self.always_label(&request).await;
let hint = self.hint(&request).await;
let mut facts = self.inner.projector.facts(&request, always, &hint);
let plan = self.card_plan(&request).await.filter(|plan| plan.open);
if let Some(plan) = &plan {
facts.plan = true;
facts.truncated = project::cut_call_text(plan.text.clone()).1;
facts.always_label = None;
}
let images: Vec<String> =
crate::evidence::images(&request).iter().map(|image| image.digest.clone()).collect();
if !images.is_empty() {
let agent = self.inner.projector.agent(&project::agent_name(&request)).display_name;
let media = self.media(&request, &hint, None, &agent).await;
facts.image = media.as_ref().map(|media| self.image_gate(media));
}
if let Err(violation) = rules::check(caller, &facts, answer, expanded) {
let error = SurfaceError::Rule(violation);
self.audit_decide(caller, &request, answer, "refused", Some(&error.code())).await?;
return Err(error);
}
if let Some(plan) = plan {
// A plan is approved by a person looking at it while agents may act: answered
// after everything was stopped, its card closes (spec 3.7 Q8, V-I17).
if self.inner.source.stopped().await? {
self.close_plan(&request, &plan).await;
let closed = self.inner.source.request(&request.id).await?.unwrap_or(request);
if closed.state == ApprovalState::Pending {
return Err(SurfaceError::NotHere(
"everything is stopped: a screen plan is answered once agents may act \
again"
.into(),
));
}
return self.already_decided(caller, &closed, answer).await;
}
return self
.commit(caller, &request, version, answer, (None, reason), Some(&plan))
.await;
}
if answer == Answer::Edit && edited_args.is_none() {
return Err(SurfaceError::Invalid("an edit needs the changed arguments".into()));
}
// An answer to an MCP server's form is checked against its schema before it is on
// record, so the person hears what to fix instead of the server declining it later.
if answer == Answer::Edit
&& let Some(crate::model::ElicitationView::Form { fields, .. }) =
crate::project::elicitation_of(&request)
&& let Some(content) = edited_args.as_ref()
&& let Err(reason) = crate::project::check_answer(&fields, content)
{
return Err(SurfaceError::Invalid(format!(
"the answer does not fit the form: {reason}"
)));
}
// An answer that lets a call with images run names the images the person saw: the
// decision binds to those digests, and to no other image (spec 3.7 V-I5).
if !images.is_empty()
&& matches!(answer, Answer::AllowOnce | Answer::AlwaysAllow | Answer::Edit)
{
if evidence.is_empty() {
return Err(SurfaceError::Invalid(
"an answer that sends images names the digests of the images it saw: send \
the card's `media.images[].digest` as `evidence`"
.into(),
));
}
if evidence != images || request.version != version {
self.audit_decide(caller, &request, answer, "changed", Some(EVIDENCE_CHANGED))
.await?;
let card = self.card(caller, &request).await?;
return Ok(CommandOutcome::Changed { card });
}
}
// An edited call with images is held again with what it would send now, never run on
// arguments whose images nobody saw (spec 3.7 V-I5).
if !images.is_empty() && answer == Answer::Edit {
let args = edited_args.unwrap_or(Value::Null);
return self.held_again(caller, &request, version, args).await;
}
if rules::row(caller) == Row::Voice && answer == Answer::AllowOnce {
// A spoken answer to a decision that changed since it was read is shown again at
// once, as on every other surface, never promised and then dropped (S-I2).
if request.version != version {
self.audit_decide(
caller,
&request,
answer,
"changed",
Some("approval.version_conflict"),
)
.await?;
let card = self.card(caller, &request).await?;
return Ok(CommandOutcome::Changed { card });
}
return self.speak_later(caller, request, version, settle).await;
}
self.commit(caller, &request, version, answer, (edited_args, reason), None).await
}
/// Tightens the crop of one of decision `id`'s images or covers more of it, then holds its
/// call again with the new image (spec 3.7 §8.2, board choice A8, V-I5).
async fn change_image(
&self,
caller: &Caller,
id: &str,
version: u64,
from: &str,
change: crate::evidence::ImageChange,
preview: bool,
) -> Result<CommandOutcome> {
let request = self.owned_request(caller, id).await?;
if !matches!(caller.origin, Origin::Keyboard | Origin::Pointer | Origin::Touch)
|| !matches!(rules::row(caller), Row::Web | Row::Phone | Row::Terminal)
{
return Err(SurfaceError::NotHere(
"an image is changed by a person looking at it, in the home or on the phone".into(),
));
}
if request.state != ApprovalState::Pending {
return self.already_decided(caller, &request, Answer::Edit).await;
}
let card = self.card(caller, &request).await?;
let media = card.media.as_ref().ok_or_else(|| {
SurfaceError::Invalid(format!("decision '{id}' holds no image to change"))
})?;
let image = media.images.get(change.image as usize).ok_or_else(|| {
SurfaceError::not_found(format!("image {} of decision '{id}'", change.image))
})?;
if request.version != version || image.digest != from {
return Ok(CommandOutcome::Changed { card });
}
if !media.can_change {
return Err(SurfaceError::unsupported("changing this image before it leaves"));
}
change.check(image.width, image.height).map_err(SurfaceError::Invalid)?;
if preview {
return self.preview_change(&request, from, &change).await;
}
// The change is on record before it takes effect (spec 3.3 §11).
self.record(
caller,
SURFACE_AUDIT_IMAGE_CHANGE,
json!({
"approvalId": request.id,
"sessionId": request.scope.session_id,
"tool": request.tool_name,
"version": version,
"fromDigest": from,
"crop": change.crop,
"cover": change.cover,
}),
)
.await?;
let changed = match self.inner.source.change_image(caller, &request, version, &change).await
{
Ok(changed) => changed,
Err(error) => return self.not_held_again(caller, &request, error).await,
};
self.inner
.changed_images
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(changed.to.clone(), changed.from.clone());
self.record(
caller,
SURFACE_AUDIT_IMAGE_CHANGE,
json!({
"approvalId": request.id,
"fromDigest": changed.from,
"toDigest": changed.to,
"outcome": "held_again",
}),
)
.await?;
self.after_held_again(caller, &request, Some(changed)).await
}
/// The image `change` would make of `request`'s image, made as the source makes it, and
/// held nowhere (board choice A8).
#[cfg(feature = "web")]
async fn preview_change(
&self,
request: &ApprovalRequest,
from: &str,
change: &crate::evidence::ImageChange,
) -> Result<CommandOutcome> {
let image = self
.inner
.source
.evidence_image(request, change.image as usize)
.await?
.ok_or_else(|| SurfaceError::Invalid("the image is no longer kept".into()))?;
let (bytes, width, height) =
crate::evidence::changed_png(&image.bytes, change).map_err(SurfaceError::Invalid)?;
let changed = crate::evidence::ImageChanged {
from: from.to_string(),
to: crate::evidence::digest_of(&bytes),
width,
height,
};
Ok(CommandOutcome::ImagePreview { changed })
}
#[cfg(not(feature = "web"))]
async fn preview_change(
&self,
_request: &ApprovalRequest,
_from: &str,
_change: &crate::evidence::ImageChange,
) -> Result<CommandOutcome> {
Err(SurfaceError::unsupported("changing an image before it leaves"))
}
/// Holds `request`'s call again with the edited `args` (spec 3.7 V-I5).
async fn held_again(
&self,
caller: &Caller,
request: &ApprovalRequest,
version: u64,
args: Value,
) -> Result<CommandOutcome> {
self.record(
caller,
SURFACE_AUDIT_ANSWER,
json!({
"approvalId": request.id,
"sessionId": request.scope.session_id,
"tool": request.tool_name,
"answer": Answer::Edit,
"version": version,
"heldAgain": true,
}),
)
.await?;
if let Err(error) =
self.inner.source.hold_again(caller, request, version, args, HELD_AGAIN_REASON).await
{
return self.not_held_again(caller, request, error).await;
}
self.after_held_again(caller, request, None).await
}
/// What a hold again that failed shows: the decision as it is now when someone answered
/// or changed it first (S-I2), else the error.
async fn not_held_again(
&self,
caller: &Caller,
request: &ApprovalRequest,
error: SurfaceError,
) -> Result<CommandOutcome> {
let Some(now) = self.inner.source.request(&request.id).await? else {
return Err(error);
};
if now.state != ApprovalState::Pending {
return self.already_decided(caller, &now, Answer::Edit).await;
}
if now.version != request.version {
let card = self.card(caller, &now).await?;
return Ok(CommandOutcome::Changed { card });
}
Err(error)
}
/// Records a hold again as the person's change and shows the closed decision.
async fn after_held_again(
&self,
caller: &Caller,
request: &ApprovalRequest,
changed: Option<crate::evidence::ImageChanged>,
) -> Result<CommandOutcome> {
let record = AnswerRecord {
approval_id: request.id.clone(),
by: caller.subject.clone(),
via: caller.via(),
answer: Answer::Edit,
at: self.now(),
};
if let Err(error) = self.inner.answers.record(&record).await {
tracing::warn!(error = %error, decision.id = %request.id, "where the change was made could not be kept");
}
self.inner.wake.notify_waiters();
let closed =
self.inner.source.request(&request.id).await?.unwrap_or_else(|| request.clone());
if let Err(error) =
self.audit_decide(caller, &closed, Answer::Edit, "held_again", None).await
{
tracing::warn!(error = %error, decision.id = %closed.id, "the call was held again; its audit record failed");
}
let card = self.card(caller, &closed).await?;
Ok(CommandOutcome::HeldAgain { changed, card })
}
/// Records the answer: `ApprovalService::decide` at `version`, never retried (S-I2); for a
/// screen plan's card, the plan's decision through the source, which records it on the
/// plan's first step (spec 3.7 Q8).
async fn commit(
&self,
caller: &Caller,
request: &ApprovalRequest,
version: u64,
answer: Answer,
(edited_args, reason): (Option<Value>, Option<String>),
plan: Option<&HeldPlan>,
) -> Result<CommandOutcome> {
let rule = match answer {
Answer::AlwaysAllow => {
Some(self.inner.source.prepare_always_allow(caller, request).await?)
}
_ => None,
};
let subject = caller.subject.clone();
let mut decision = match answer {
Answer::AllowOnce | Answer::AlwaysAllow => ApprovalDecision::approve(subject),
Answer::Edit => ApprovalDecision::edit(subject, edited_args.unwrap_or(Value::Null)),
Answer::Deny => ApprovalDecision::reject(subject, reason.clone().unwrap_or_default()),
}
.with_groups(caller.groups.clone());
if answer == Answer::Deny && reason.as_deref().is_none_or(str::is_empty) {
decision.reason = None;
}
// The answer is on record before it takes effect, and one that cannot be recorded is
// not given (spec 3.3 §11).
let mut given = json!({
"approvalId": request.id,
"sessionId": request.scope.session_id,
"tool": request.tool_name,
"answer": answer,
"version": version,
});
if let Ok(digest) = SPOKEN_DIGEST.try_with(Clone::clone) {
given["transcriptDigest"] = json!(digest);
}
if let Some(plan) = plan {
given["planDigest"] = json!(plan.view.digest);
}
self.record(caller, SURFACE_AUDIT_ANSWER, given).await?;
// A yes to a form's call is sealed to the drawing the person saw before it takes
// effect, so the call that runs is the one they approved (spec 3.3 §7.4 rule 5).
#[cfg(feature = "genui")]
if matches!(answer, Answer::AllowOnce | Answer::Edit)
&& let Some(seals) = &self.inner.seals
&& let Some(sent) = self.inner.drawn.sent_call(request)
{
let args = decision.edited_args.clone().unwrap_or_else(|| sent.args.clone());
let card_text = format!(
"{} {}",
request.tool_name,
serde_json::to_string(&args).unwrap_or_default()
);
let seal = seals.seal(crate::genui::SealInput {
function_call_id: sent.call_id.clone(),
tool_name: request.tool_name.clone(),
args,
card_text,
drawing_digest: sent.digest.clone(),
surface_id: sent.form.0.clone(),
version: sent.form.1,
approver: caller.user_id().to_string(),
});
self.record(
caller,
SURFACE_AUDIT_DRAWN_SEALED,
json!({
"approvalId": request.id,
"callId": sent.call_id,
"surfaceId": sent.form.0,
"version": sent.form.1,
"drawingDigest": sent.digest,
"seal": seal,
}),
)
.await?;
}
let decided = match plan {
Some(plan) => {
let allow = answer != Answer::Deny;
self.inner
.source
.decide_screen_plan(caller, request, version, &plan.view.digest, allow, reason)
.await
}
None => self.inner.source.decide(&request.id, version, decision).await,
};
match decided {
Ok(updated) => {
// The decision is recorded and cannot be taken back: nothing after this point
// fails the command or keeps the decided call and the queued input waiting.
let resolved = updated.state != ApprovalState::Pending;
// The standing rule only once the request was approved: an approval that a
// quorum still waits on has not won (spec 3.3 §8.2).
if let Some(rule) = rule.filter(|_| updated.state == ApprovalState::Approved)
&& let Err(error) = rule.commit().await
{
tracing::warn!(error = %error, decision.id = %updated.id, "the call was allowed once; its standing rule could not be created");
}
if resolved {
let record = AnswerRecord {
approval_id: updated.id.clone(),
by: caller.subject.clone(),
via: caller.via(),
answer,
at: self.now(),
};
if let Err(error) = self.inner.answers.record(&record).await {
tracing::warn!(error = %error, decision.id = %updated.id, "where the answer was given could not be kept");
}
}
if let Err(error) =
self.audit_decide(caller, &updated, answer, "decided", None).await
{
tracing::warn!(error = %error, decision.id = %updated.id, "the answer took effect; its audit record failed");
}
if resolved {
if let Err(error) = self.inner.source.resolved_by(caller, &updated).await {
tracing::warn!(error = %error, decision.id = %updated.id, "the decided call could not be resumed");
}
self.spawn_drain(caller.clone(), updated.scope.session_id.clone());
}
let card = self.card(caller, &updated).await?;
Ok(CommandOutcome::Answered { card })
}
Err(SurfaceError::Source(error))
if matches!(
error.code,
"approval.version_conflict" | "approval.already_resolved" | "approval.expired"
) || (error.category == adk_core::ErrorCategory::Conflict
&& error.code != "approval.already_decided") =>
{
let current = match self.owned_request(caller, &request.id).await {
Ok(current) => current,
// The source lists open requests only: answered, but not saying how.
Err(SurfaceError::NotFound { .. }) => {
return self.decided_elsewhere(caller, request, answer).await;
}
Err(error) => return Err(error),
};
if current.state == ApprovalState::Pending {
self.audit_decide(caller, ¤t, answer, "changed", Some(error.code))
.await?;
let card = self.card(caller, ¤t).await?;
return Ok(CommandOutcome::Changed { card });
}
self.already_decided(caller, ¤t, answer).await
}
Err(error) => Err(error),
}
}
async fn already_decided(
&self,
caller: &Caller,
request: &ApprovalRequest,
answer: Answer,
) -> Result<CommandOutcome> {
self.audit_decide(caller, request, answer, "already_decided", None).await?;
let card = self.card(caller, request).await?;
let decided = card.decided.clone().ok_or_else(|| {
SurfaceError::Invalid(format!("decision '{}' is not decided", request.id))
})?;
Ok(CommandOutcome::AlreadyDecided { decided, card })
}
/// A decision the source no longer lists after a conflict: decided, details unknown.
async fn decided_elsewhere(
&self,
caller: &Caller,
request: &ApprovalRequest,
answer: Answer,
) -> Result<CommandOutcome> {
self.audit_decide(caller, request, answer, "already_decided", None).await?;
let hint = self.hint(request).await;
let mut card = self.inner.projector.card(request, caller, None, None, self.now(), &hint);
// When it was decided is not known either: `at` is when this surface found out, and
// no time is shown.
let decided = Decided {
by: String::new(),
by_you: false,
via: None,
at: self.now(),
at_text: String::new(),
answer: crate::model::DecidedAnswer::Unknown,
text: words::DECIDED.to_string(),
scope_text: None,
};
card.status = crate::model::CardStatus::Decided;
card.status_text = words::DECIDED.to_string();
card.allowed.options.clear();
card.allowed.open_in_home = false;
card.allowed.cancel_window_secs = None;
card.allowed.note = None;
if let Some(step) = card.timeline.last_mut() {
step.text = words::DECIDED.to_string();
}
card.decided = Some(decided.clone());
Ok(CommandOutcome::AlreadyDecided { decided, card })
}
/// A spoken "allow once" waits out its cancel window, then commits (spec 3.3 §5.6, §7.2);
/// how the window ended goes to `settle`.
async fn speak_later(
&self,
caller: &Caller,
request: ApprovalRequest,
version: u64,
settle: Option<oneshot::Sender<Result<CommandOutcome>>>,
) -> Result<CommandOutcome> {
let window = self.inner.voice_window;
let cancel_until = self.now()
+ chrono::Duration::from_std(window).unwrap_or_else(|_| chrono::Duration::seconds(5));
self.audit_decide(caller, &request, Answer::AllowOnce, "pending", None).await?;
let digest = SPOKEN_DIGEST.try_with(Clone::clone).ok();
let engine = self.clone();
let speaker = caller.clone();
let id = request.id.clone();
let task_id = id.clone();
let spoken = request.clone();
let token = Arc::new(());
let mine = Arc::clone(&token);
let (go, entered) = oneshot::channel::<()>();
let handle = tokio::spawn(with_digest(digest.clone(), async move {
// Its entry is in place before the window starts, so a cancel always finds it.
if entered.await.is_err() {
return;
}
tokio::time::sleep(window).await;
// Cancel and Stop all remove the entry before they abort the task: an answer whose
// entry is gone, or was replaced, is withdrawn, whatever the abort's timing.
let withdrawn = {
let mut spoken = engine.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
let current =
spoken.get(&task_id).is_some_and(|entry| Arc::ptr_eq(&entry.token, &mine));
if current {
spoken.remove(&task_id);
}
!current
};
if withdrawn {
return;
}
// Everything stopped meanwhile, here or on another surface: nothing runs.
let result = if engine.inner.source.stopped().await.unwrap_or(false) {
if let Err(error) = engine
.audit_decide(
&speaker,
&request,
Answer::AllowOnce,
"cancelled",
Some("surface.stopped"),
)
.await
{
tracing::warn!(error = %error, decision.id = %task_id, "a spoken answer was cancelled; its audit record failed");
}
Err(SurfaceError::NotHere(words::ALL_AGENTS_STOPPED.to_string()))
} else {
engine
.commit(&speaker, &request, version, Answer::AllowOnce, (None, None), None)
.await
};
match &result {
Ok(CommandOutcome::Answered { .. }) => {}
Ok(outcome) => {
tracing::info!(decision.id = %task_id, outcome = ?outcome, "a spoken answer was not recorded: the decision changed in its cancel window");
}
Err(error) => {
tracing::warn!(error = %error, decision.id = %task_id, "a spoken answer could not be recorded");
}
}
if let Some(settle) = settle {
let _ = settle.send(result);
}
}));
let entry =
Spoken { handle, token, user: caller.user_id().to_string(), request: spoken, digest };
if let Some(previous) =
self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner()).insert(id.clone(), entry)
{
previous.handle.abort();
}
let _ = go.send(());
Ok(CommandOutcome::Pending {
decision_id: id,
cancel_until,
text: words::allowing_in(
u64::try_from(window.as_millis().div_ceil(1000)).unwrap_or(u64::MAX),
),
})
}
/// Cancels a spoken answer at once, without reading the source, so a cancel never waits
/// on a store; like a stop, it is recorded after, and a failed record does not undo it.
async fn cancel_answer(&self, caller: &Caller, id: &str) -> Result<CommandOutcome> {
let spoken = {
let mut spoken = self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
match spoken.get(id) {
Some(entry) if entry.user == caller.user_id() => spoken.remove(id),
_ => None,
}
};
let Some(spoken) = spoken else {
return Err(SurfaceError::not_found(format!("a spoken answer to '{id}' to cancel")));
};
spoken.handle.abort();
if let Err(error) = with_digest(
spoken.digest,
self.audit_decide(caller, &spoken.request, Answer::AllowOnce, "cancelled", None),
)
.await
{
tracing::warn!(error = %error, decision.id = %id, "the spoken answer was cancelled; its audit record failed");
}
Ok(CommandOutcome::AnswerCancelled { decision_id: id.to_string() })
}
/// **Stop the turn**: a person stops the running turn of their own session; recorded
/// before it takes effect.
async fn stop_turn(&self, caller: &Caller, session: String) -> Result<CommandOutcome> {
if let Origin::Agent { agent } = &caller.origin {
return Err(SurfaceError::NotHere(format!(
"an agent ({agent}) never stops a person's turn; a person does (spec 3.3 §7.4)"
)));
}
if self.inner.source.transcript(caller.user_id(), &session).await?.is_none() {
return Err(SurfaceError::not_found(format!("session '{session}'")));
}
self.audit_command(caller, SURFACE_AUDIT_STOP_TURN, json!({ "sessionId": session }))
.await?;
let stopped = self.inner.source.stop_turn(caller, &session).await?;
Ok(CommandOutcome::TurnStopped {
session_id: session,
stopped,
text: words::TURN_STOPPED.to_string(),
})
}
/// Sends `text` as a message of the session: a turn at once when the session is free,
/// queued otherwise, or always when `queue`. With `offer`, a message that waits behind a
/// running turn is offered to that turn (spec 3.3 §6 "steer").
async fn send(
&self,
caller: &Caller,
session: String,
text: String,
images: Vec<crate::images::MessageImage>,
queue: bool,
offer: bool,
) -> Result<CommandOutcome> {
if text.trim().is_empty() && images.is_empty() {
return Err(SurfaceError::Invalid("the message is empty".into()));
}
// A running turn takes text at its next safe point; images wait for the next turn.
let offer = offer && images.is_empty();
let pictures = images.len();
let key = (caller.user_id().to_string(), session.clone());
let open = self.session_open(caller, &session).await?;
// Earlier queued input goes first, including a message the delivery loop is starting
// a turn for right now: a new message never overtakes it (S-I4). Input the running
// turn holds is no reason to wait: that turn takes its messages in order.
let (waiting, earlier) = {
let queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
let queued = queues.get(&key);
(
queued.is_some_and(|queued| queued.iter().any(|input| !input.offered)),
queued.is_some_and(|queued| !queued.is_empty())
|| self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).contains(&key),
)
};
// A running turn takes the message next, as an open decision does (S-I4).
let busy = !open && !waiting && self.inner.source.busy(caller.user_id(), &session).await?;
if open || earlier || busy || queue {
// Recorded before it is queued: a message whose record failed is never sent.
self.audit_command(
caller,
SURFACE_AUDIT_SEND,
with_images(json!({ "sessionId": session, "queued": true }), pictures),
)
.await?;
let held = match busy && offer && !queue {
true => self.offer(caller, &session, &text).await?,
false => None,
};
let (id, position) = self.enqueue(&key, text.clone(), images, held.is_some());
if let Some(held) = held {
self.settle_offer(caller.clone(), session.clone(), id, held, None);
}
self.spawn_drain(caller.clone(), session.clone());
let text = if open {
words::SENT_AFTER_THIS_CARD_IS_ANSWERED
} else {
words::SENT_WHEN_YOUR_AGENT_IS_FREE
};
return Ok(CommandOutcome::Queued {
session_id: session,
position,
text: text.to_string(),
});
}
self.audit_command(
caller,
SURFACE_AUDIT_SEND,
with_images(json!({ "sessionId": session, "queued": false }), pictures),
)
.await?;
self.inner.source.start_turn_images(caller, &session, &text, &images).await?;
Ok(CommandOutcome::Sent { session_id: session })
}
/// Adds `text` to the end of the session's queue; returns its id and its place, from 1.
fn enqueue(
&self,
key: &(String, String),
text: String,
images: Vec<crate::images::MessageImage>,
offered: bool,
) -> (u64, u32) {
let id = self.inner.next_input.fetch_add(1, Ordering::Relaxed);
let mut queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
let queued = queues.entry(key.clone()).or_default();
queued.push_back(QueuedInput { id, text, images, offered });
(id, u32::try_from(queued.len()).unwrap_or(u32::MAX))
}
/// Offers `text` to the session's running turn (spec 3.3 §6 "steer"). `None` when no turn
/// takes it, or the source cannot be asked just now: the message then waits its turn. A
/// message the runtime refuses is not queued, and the refusal is on record.
async fn offer(&self, caller: &Caller, session: &str, text: &str) -> Result<Option<Steering>> {
match self.inner.source.steer(caller, session, text).await {
Ok(held) => Ok(held),
Err(error) if transient(&error) => {
tracing::debug!(error = %error, session.id = %session, "a running turn could not be offered a message; it waits as the next message");
Ok(None)
}
Err(error) => {
let fields =
json!({ "sessionId": session, "outcome": "refused", "code": error.code() });
if let Err(audit) = self.audit_command(caller, SURFACE_AUDIT_STEER, fields).await {
tracing::warn!(error = %audit, session.id = %session, "a refused message's audit record failed");
}
Err(error)
}
}
}
/// Follows the queued message `id`, which the session's running turn holds, to its end,
/// on a task of the engine's own, so a surface that goes away loses nothing. Taken by
/// the turn, the message leaves the queue; handed back, it stays in its place as the
/// session's next message. `done` hears which.
fn settle_offer(
&self,
caller: Caller,
session: String,
id: u64,
held: Steering,
done: Option<oneshot::Sender<Result<CommandOutcome>>>,
) {
let engine = self.clone();
tokio::spawn(async move {
let key = (caller.user_id().to_string(), session.clone());
let settled = held.await;
let delivered = match &settled {
Ok(Steered::Delivered { event_id }) => Some(event_id.clone()),
Ok(Steered::Returned) => None,
// What became of it could not be read. A message is never dropped, so it
// goes as the next message.
Err(error) => {
tracing::warn!(error = %error, session.id = %session, "what became of a message a running turn held could not be read; it goes as the next message");
None
}
};
let position = {
let mut queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
let queued = queues.entry(key).or_default();
let place = queued.iter().position(|input| input.id == id);
match (place, &delivered) {
(Some(place), Some(_)) => {
queued.remove(place);
}
(Some(place), None) => queued[place].offered = false,
(None, _) => {}
}
place.map_or(1, |place| u32::try_from(place + 1).unwrap_or(u32::MAX))
};
let fields = match &delivered {
Some(event_id) => {
json!({ "sessionId": session, "outcome": "delivered", "eventId": event_id })
}
None => json!({ "sessionId": session, "outcome": "returned" }),
};
// The message already has its fate: a record that fails does not change it.
if (delivered.is_some() || done.is_some())
&& let Err(error) = engine.audit_command(&caller, SURFACE_AUDIT_STEER, fields).await
{
tracing::warn!(error = %error, session.id = %session, "a steered message's audit record failed");
}
// The delivery loop looks again: a message handed back is the session's next,
// and a queue the turn emptied ends the loop.
engine.inner.wake.notify_waiters();
engine.spawn_drain(caller, session.clone());
if let Some(done) = done {
let outcome = match delivered {
Some(event_id) => CommandOutcome::Steered { session_id: session, event_id },
None => CommandOutcome::Queued {
session_id: session,
position,
text: words::SENT_WHEN_YOUR_AGENT_IS_FREE.to_string(),
},
};
let _ = done.send(Ok(outcome));
}
});
}
/// "Steer" (spec 3.3 §6): sends `text` to the running turn of the caller's own session
/// and waits for what became of it. Refused, and recorded as refused, from an agent, for
/// a session that is not the caller's (S-I8), and while everything is stopped.
async fn steer(
&self,
caller: &Caller,
session: String,
text: String,
) -> Result<CommandOutcome> {
if text.trim().is_empty() {
return Err(SurfaceError::Invalid("the message is empty".into()));
}
let refusal = if let Origin::Agent { agent } = &caller.origin {
Some(SurfaceError::NotHere(format!(
"an agent ({agent}) never sends a message to a person's running turn; a person \
does (spec 3.3 §7.4)"
)))
} else if self.inner.source.transcript(caller.user_id(), &session).await?.is_none() {
Some(SurfaceError::not_found(format!("session '{session}'")))
} else if self.inner.source.stopped().await? {
Some(SurfaceError::NotHere(words::ALL_AGENTS_STOPPED.to_string()))
} else {
None
};
if let Some(error) = refusal {
self.audit_command(
caller,
SURFACE_AUDIT_STEER,
json!({ "sessionId": session, "outcome": "refused", "code": error.code() }),
)
.await?;
return Err(error);
}
let key = (caller.user_id().to_string(), session.clone());
// An open decision, or a message that waits, goes first (S-I4): the message is handed
// back at once, as the session's next.
let waiting = self
.inner
.queues
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&key)
.is_some_and(|queued| queued.iter().any(|input| !input.offered));
if waiting || self.session_open(caller, &session).await? {
return self.send(caller, session, text, Vec::new(), false, false).await;
}
// Recorded before the turn holds it: a message whose record failed is never sent.
self.audit_command(
caller,
SURFACE_AUDIT_STEER,
json!({ "sessionId": session, "outcome": "offered" }),
)
.await?;
let Some(held) = self.offer(caller, &session, &text).await? else {
// No turn takes it here.
return self.send(caller, session, text, Vec::new(), false, false).await;
};
let (id, _) = self.enqueue(&key, text, Vec::new(), true);
let (done, settled) = oneshot::channel();
self.settle_offer(caller.clone(), session, id, held, Some(done));
settled.await.unwrap_or_else(|_| {
Err(SurfaceError::Invalid(
"the engine stopped before the turn said whether it took the message; the \
session's thread shows it when it did"
.into(),
))
})
}
/// Whether the session has a decision open: one the caller may answer, or a call held for
/// someone else (§7.4 rule 2).
async fn session_open(&self, caller: &Caller, session: &str) -> Result<bool> {
let own =
self.inner.source.requests(caller, Some(session), true).await?.iter().any(|request| {
owns(caller, request)
&& request.state == ApprovalState::Pending
&& request.scope.session_id == session
});
Ok(own || self.inner.source.waiting_on_decision(caller.user_id(), session).await?)
}
/// Delivers the session's queued input, oldest first and one turn at a time, once it has
/// no open decision and no running turn (S-I4). The loop waits for as long as that takes,
/// whichever surface answers the decision, and keeps a message whose turn could not start
/// at the front of the queue.
fn spawn_drain(&self, caller: Caller, session: String) {
let key = (caller.user_id().to_string(), session.clone());
{
let queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
if queues.get(&key).is_none_or(VecDeque::is_empty) {
return;
}
if !self.inner.draining.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone()) {
// The loop already runs: have it look again now.
self.inner.wake.notify_waiters();
return;
}
}
let engine = self.clone();
tokio::spawn(async move {
let poll = engine.inner.poll;
let mut wait = poll;
loop {
let woken = engine.inner.wake.notified();
tokio::pin!(woken);
woken.as_mut().enable();
{
let queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
if queues.get(&key).is_none_or(VecDeque::is_empty) {
engine
.inner
.draining
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&key);
return;
}
}
// A message the running turn holds is not sent until the turn hands it back.
let held = engine
.inner
.queues
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&key)
.and_then(VecDeque::front)
.is_some_and(|input| input.offered);
let free = match engine.session_open(&caller, &session).await {
_ if held => Ok(false),
Ok(true) => Ok(false),
Ok(false) => {
engine.inner.source.busy(caller.user_id(), &session).await.map(|busy| !busy)
}
Err(error) => Err(error),
};
match free {
Ok(true) => {}
Ok(false) => {
tokio::select! {
() = engine.inner.source.changed(wait) => {}
() = &mut woken => {}
}
wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
continue;
}
Err(error) => {
tracing::debug!(error = %error, session.id = %session, "queued input waits: the session could not be read");
tokio::select! {
() = tokio::time::sleep(wait) => {}
() = &mut woken => {}
}
wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
continue;
}
}
let next = {
let mut queues = engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
match queues.get_mut(&key) {
Some(queued) if queued.front().is_some_and(|input| !input.offered) => {
queued.pop_front()
}
_ => None,
}
};
let Some(input) = next else { continue };
match engine
.inner
.source
.start_turn_images(&caller, &session, &input.text, &input.images)
.await
{
Ok(()) => {
wait = poll;
// Let the turn begin before looking again.
tokio::time::sleep(poll).await;
}
Err(error) => {
{
let mut queues =
engine.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
queues.entry(key.clone()).or_default().push_front(input);
if !transient(&error) {
// It stays queued and shown; the next message or answer tries
// again.
tracing::warn!(error = %error, session.id = %session, "queued input could not be sent; it stays queued");
engine
.inner
.draining
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&key);
return;
}
}
tracing::warn!(error = %error, session.id = %session, "queued input could not be sent yet; trying again");
tokio::select! {
() = tokio::time::sleep(wait) => {}
() = &mut woken => {}
}
wait = (wait * 2).min(DRAIN_BACKOFF_MAX);
}
}
}
});
}
/// Takes back the newest input queued for the session, before it is sent; `None` when
/// none waits (spec 3.3 §7.4 rule 2), or when the session's running turn holds the newest
/// (§6 "steer"): the turn may take it at any moment.
pub fn unqueue_last(&self, caller: &Caller, session: &str) -> Option<String> {
let mut queues = self.inner.queues.lock().unwrap_or_else(|e| e.into_inner());
let queued = queues.get_mut(&(caller.user_id().to_string(), session.to_string()))?;
match queued.back() {
Some(input) if !input.offered => queued.pop_back().map(|input| input.text),
_ => None,
}
}
/// The input queued for the session, oldest first, as the person reads it: an app's
/// suggestion is its words and label. A message the session's running turn holds is
/// listed until the turn takes it.
pub fn queued(&self, caller: &Caller, session: &str) -> Vec<String> {
self.inner
.queues
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(&(caller.user_id().to_string(), session.to_string()))
.map(|queue| {
queue
.iter()
.map(|input| {
crate::genui::suggested_message(&input.text)
.unwrap_or_else(|| input.text.clone())
})
.collect()
})
.unwrap_or_default()
}
/// Looks at once whether the session's queued input can be sent, after an answer
/// recorded outside [`execute`](Self::execute), such as a take over (spec 3.3 §7.4 rule 2).
/// Queued input is sent without it too, once the session is free.
pub fn deliver_queued(&self, caller: &Caller, session: &str) {
self.spawn_drain(caller.clone(), session.to_string());
}
/// Stop all and Resume all reach every run, so they need the group set with
/// [`SurfaceEngineBuilder::stops_need`] (spec 3.3 §11 S-I10).
fn may_stop(&self, caller: &Caller) -> Result<()> {
match &self.inner.stops_need {
Some(group) if !caller.groups.iter().any(|held| held == group) => {
Err(SurfaceError::OperatorOnly { group: group.clone() })
}
_ => Ok(()),
}
}
async fn stop_all(&self, caller: &Caller, reason: Option<String>) -> Result<CommandOutcome> {
let reason = reason.unwrap_or_else(|| words::STOP_ALL.to_string());
// A spoken "allow once" still in its cancel window is withdrawn first: Stop all is the
// strongest withdrawal (S-I10).
let cancelled: Vec<String> = {
let mut spoken = self.inner.spoken.lock().unwrap_or_else(|e| e.into_inner());
spoken
.drain()
.map(|(id, entry)| {
entry.handle.abort();
id
})
.collect()
};
// Every camera's gate closes before anything else (spec 3.7 V-I17): no frame passes
// the hub from here on, wherever the freeze reaches next.
if let Some(cameras) = &self.inner.cameras
&& let Err(error) = cameras.freeze_all().await
{
tracing::warn!(error = %error, "the cameras' gate closed; their source refused the pause");
}
// Stopping never waits on the audit log (spec 3.2 K-I8): record after, warn on failure.
self.inner.source.stop_all(caller, &reason).await?;
// Every open screen plan's card closes: a plan is approved by a person looking at it
// while agents may act, never across a stop (spec 3.7 Q8, V-I17).
let mut closed = Vec::new();
for request in self.inner.source.requests(caller, None, true).await.unwrap_or_default() {
if request.state == ApprovalState::Pending
&& let Some(plan) = self.card_plan(&request).await
{
self.close_plan(&request, &plan).await;
closed.push(request.id.clone());
}
}
let mut fields = json!({ "reason": reason });
if !cancelled.is_empty() {
fields["cancelledAnswers"] = json!(cancelled);
}
if !closed.is_empty() {
fields["closedPlans"] = json!(closed);
}
if let Err(error) = self.audit_command(caller, SURFACE_AUDIT_STOP_ALL, fields).await {
tracing::warn!(error = %error, "stop all took effect; its audit record failed");
}
Ok(CommandOutcome::Stopped { text: words::ALL_AGENTS_STOPPED.to_string() })
}
async fn resume_all(&self, caller: &Caller) -> Result<CommandOutcome> {
if !rules::may_resume(caller) {
return Err(SurfaceError::NotHere(
"Resume all happens only in the web home or on a paired local terminal \
(spec 3.3 S-I10)"
.into(),
));
}
self.audit_command(caller, SURFACE_AUDIT_RESUME_ALL, json!({})).await?;
self.inner.source.resume_all(caller).await?;
if let Some(cameras) = &self.inner.cameras {
cameras.thaw_all().await?;
}
Ok(CommandOutcome::Resumed)
}
async fn set_mode(&self, caller: &Caller, session: &str, mode: Mode) -> Result<CommandOutcome> {
let target = project::harness_mode(mode);
let current = self.inner.source.mode(caller.user_id(), Some(session)).await?;
let loosens = current.is_none_or(|current| current.is_stricter_than(target));
if matches!(caller.origin, Origin::Agent { .. })
|| (loosens && !rules::may_loosen_mode(caller))
{
return Err(SurfaceError::NotHere(
"letting agents do more on their own is a standing permission: change it in \
the home app, on your phone or in the terminal"
.into(),
));
}
// In an added agent's own thread the mode can only make it ask more (spec 3.3 §5.7).
if let Some(agent) = self.inner.source.agent_of_session(caller.user_id(), session).await?
&& let Some(detail) = self.inner.source.agent(caller.user_id(), &agent).await?
&& project::harness_mode(detail.mode.mode).is_stricter_than(target)
{
return Err(SurfaceError::NotHere(crate::agents::words::asks_at_most(
&detail.draft.display_name,
&detail.mode.label,
)));
}
// A thread with no message yet takes a mode where the source opens it for the caller,
// as a kernel's `/mode` does; elsewhere only the caller's own session does (S-I8).
if self.inner.source.transcript(caller.user_id(), session).await?.is_none()
&& !self.inner.source.opens_sessions()
{
return Err(SurfaceError::not_found(format!("session '{session}'")));
}
self.audit_command(
caller,
SURFACE_AUDIT_SET_MODE,
json!({ "sessionId": session, "mode": target.as_str() }),
)
.await?;
self.inner.source.set_mode(caller, session, target).await?;
Ok(CommandOutcome::ModeSet { mode: project::mode_view(target) })
}
// -----------------------------------------------------------------------
// Agents a person adds (spec 3.3 §5.7)
// -----------------------------------------------------------------------
/// Whether the roster ends with **New agent** for `caller` (spec 3.3 §5.7).
pub fn can_add_agents(&self, caller: &Caller) -> bool {
self.inner.source.keeps_agents()
&& !matches!(caller.origin, Origin::Agent { .. })
&& rules::may_change_agents(caller)
}
/// One agent `caller` added (spec 3.3 §5.7 "Agent settings").
///
/// # Errors
///
/// `surface.not_found` when the caller has no such agent, or the source's error.
pub async fn agent(&self, caller: &Caller, id: &str) -> Result<crate::agents::AgentDetail> {
self.inner
.source
.agent(caller.user_id(), id)
.await?
.map(|detail| self.with_granted(detail))
.ok_or_else(|| SurfaceError::not_found(format!("agent '{id}'")))
}
/// What `caller` may choose for an agent.
///
/// # Errors
///
/// `surface.not_here` where agents are not changed, or the source's error.
pub async fn agent_choices(&self, caller: &Caller) -> Result<crate::agents::AgentChoices> {
Self::may_change_agents(caller)?;
self.inner.source.agent_choices().await
}
/// **Here is what Finance can do**: the preview of `request` (spec 3.3 §5.7).
///
/// # Errors
///
/// `surface.not_here` where agents are not changed, or the kernel's refusal.
pub async fn preview_agent(
&self,
caller: &Caller,
request: crate::agents::AgentPreviewRequest,
) -> Result<crate::agents::AgentPreview> {
Self::may_change_agents(caller)?;
self.inner.source.preview_agent(caller, request).await
}
/// Refuses a caller who may not change agents here: an agent, or a surface other than the
/// web home and the terminal (spec 3.3 §5.7, §7.2).
fn may_change_agents(caller: &Caller) -> Result<()> {
if let Origin::Agent { agent } = &caller.origin {
return Err(SurfaceError::NotHere(format!(
"an agent ({agent}) never adds, changes, pauses or removes an agent; a person \
does (spec 3.3 §5.7)"
)));
}
if !rules::may_change_agents(caller) {
return Err(SurfaceError::NotHere(
"agents are set up and changed in the home app or the terminal (spec 3.3 §7.2)"
.into(),
));
}
Ok(())
}
async fn new_thread(
&self,
caller: &Caller,
agent: &str,
session: String,
text: String,
images: Vec<crate::images::MessageImage>,
) -> Result<CommandOutcome> {
if text.trim().is_empty() && images.is_empty() {
return Err(SurfaceError::Invalid("the message is empty".into()));
}
if let Origin::Agent { agent } = &caller.origin {
return Err(SurfaceError::NotHere(format!(
"an agent ({agent}) never starts a thread for a person (spec 3.3 §7.4)"
)));
}
self.audit_command(
caller,
SURFACE_AUDIT_SEND,
with_images(
json!({ "sessionId": session, "queued": false, "agent": agent }),
images.len(),
),
)
.await?;
self.inner.source.start_turn_with_images(caller, agent, &session, &text, &images).await?;
Ok(CommandOutcome::Sent { session_id: session })
}
async fn agent_command(&self, caller: &Caller, command: Command) -> Result<CommandOutcome> {
Self::may_change_agents(caller)?;
let source = &self.inner.source;
let agent_of = |command: &Command| match command {
Command::ChangeAgent { agent, .. }
| Command::PauseAgent { agent }
| Command::ResumeAgent { agent }
| Command::RemoveAgent { agent, .. }
| Command::CopyRuleToAgent { agent, .. } => Some(agent.clone()),
_ => None,
};
let agent = agent_of(&command);
let result = match command {
Command::AddAgent { draft, digest, replaces } => source
.add_agent(caller, *draft, &digest, replaces)
.await
.map(|agent| CommandOutcome::AgentAdded { agent: self.with_granted(agent) }),
Command::ChangeAgent { agent, version, draft, digest } => source
.change_agent(caller, &agent, version, *draft, &digest)
.await
.map(|agent| CommandOutcome::AgentChanged { agent: self.with_granted(agent) }),
Command::PauseAgent { agent } => source
.pause_agent(caller, &agent)
.await
.map(|agent| CommandOutcome::AgentPaused { agent: self.with_granted(agent) }),
Command::ResumeAgent { agent } => {
// Resuming is the person at the home or a paired local terminal (S-I10).
if !rules::may_resume_agent(caller) {
return Err(SurfaceError::NotHere(
words::ALL_AGENTS_STOPPED_RESUME_IN_HOME.to_string(),
));
}
source
.resume_agent(caller, &agent)
.await
.map(|agent| CommandOutcome::AgentResumed { agent: self.with_granted(agent) })
}
Command::RemoveAgent { agent, version, digest } => source
.remove_agent(caller, &agent, version, &digest)
.await
.map(|ended| CommandOutcome::AgentRemoved { ended }),
Command::CopyRuleToAgent { agent, rule_id } => source
.copy_rule_to_agent(caller, &agent, &rule_id)
.await
.map(|label| CommandOutcome::RuleCopied { agent, label }),
_ => return Err(SurfaceError::Invalid("not a command about an agent".into())),
};
match (result, agent) {
// Someone changed it since: shown again with what it is now, never overwritten.
(Err(error), Some(agent)) if crate::agents::local::out_of_date(&error) => {
let detail = self.agent(caller, &agent).await?;
// Where it was changed: "in the terminal", "in the home app", "on your phone".
let place = detail
.changed_on
.as_deref()
.and_then(|surface| serde_json::from_value::<SurfaceKind>(json!(surface)).ok())
.map_or_else(
|| "elsewhere".to_string(),
|surface| crate::origin::Via { surface, origin: Origin::Keyboard }.phrase(),
);
let text = crate::agents::words::changed_in(
&detail.draft.display_name,
&place,
&self.inner.projector.hh_mm(detail.changed_at),
);
Ok(CommandOutcome::AgentOutOfDate { agent: detail, text })
}
(result, _) => result,
}
}
// -----------------------------------------------------------------------
// Audit (spec 3.3 §11)
// -----------------------------------------------------------------------
fn draft(caller: &Caller, kind: AuditRecordKind, action: &str) -> AuditRecordDraft {
let mut draft = AuditRecordDraft::new(kind, action)
.actor(AuditActor::subject(caller.subject.clone()))
.ext("surface", serde_json::to_value(caller.surface).unwrap_or(Value::Null))
.ext("origin", serde_json::to_value(&caller.origin).unwrap_or(Value::Null));
if let Some(device) = &caller.device {
draft = draft.ext("device", json!(device));
}
if caller.presence_confirmed {
draft = draft.ext("presence", json!("confirmed"));
}
draft
}
async fn audit_decide(
&self,
caller: &Caller,
request: &ApprovalRequest,
answer: Answer,
outcome: &str,
code: Option<&str>,
) -> Result<()> {
let Some(trail) = &self.inner.audit else {
return Ok(());
};
let decision = match (outcome, answer) {
("decided", Answer::Deny) => Some(AuditDecision::Rejected),
("decided", _) => Some(AuditDecision::Approved),
_ => None,
};
let mut draft = Self::draft(caller, AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
.ext("approvalId", json!(request.id))
.ext("sessionId", json!(request.scope.session_id))
.ext("tool", json!(request.tool_name))
.ext("answer", serde_json::to_value(answer).unwrap_or(Value::Null))
.ext("outcome", json!(outcome));
if let Some(decision) = decision {
draft = draft.decision(decision);
}
// Whose call it was, so the record can say "You let Finance send one email" (§11).
if let Some(acting) = &request.acting {
draft = draft.ext("actingAgent", json!(acting.agent.id.to_string()));
}
// What the call acts on, as a feature names it, so a denial names its item as the
// change's own record does: "Finance asked to snooze News digest" (§8, §11).
if let Some(title) = crate::hints::named(&self.inner.card_hints, request).await {
draft = draft.ext("title", json!(title)).ext("summary", json!(request.summary));
}
if let Some(code) = code {
draft = draft.ext("code", json!(code));
}
if let Ok(digest) = SPOKEN_DIGEST.try_with(Clone::clone) {
draft = draft.ext("transcriptDigest", json!(digest));
}
trail.record(draft).await.map_err(SurfaceError::Source)
}
/// The record of a command `caller` gave (spec 3.3 §11): Stop all and Resume all as
/// governance, a mode change as configuration, every other command through
/// [`record`](Self::record).
pub(crate) async fn audit_command(
&self,
caller: &Caller,
action: &str,
fields: Value,
) -> Result<()> {
let kind = match action {
SURFACE_AUDIT_STOP_ALL | SURFACE_AUDIT_RESUME_ALL => AuditRecordKind::Governance,
SURFACE_AUDIT_SET_MODE => AuditRecordKind::Configuration,
_ => return self.record(caller, action, fields).await,
};
self.write_record(caller, kind, action, fields).await
}
/// Writes the record `action` of what `caller` did through a surface, with `fields` as its
/// extensions (spec 3.3 §11): stamped with the caller's surface, origin, device and
/// presence as every surface record is, of kind `Other("surface")`, which the kernel's
/// surface-records route accepts. A feature records what a person did with it here, such
/// as `surface.verb`. Without an audit trail nothing is written.
pub(crate) async fn record(&self, caller: &Caller, action: &str, fields: Value) -> Result<()> {
self.write_record(caller, AuditRecordKind::Other("surface".to_string()), action, fields)
.await
}
async fn write_record(
&self,
caller: &Caller,
kind: AuditRecordKind,
action: &str,
fields: Value,
) -> Result<()> {
let Some(trail) = &self.inner.audit else {
return Ok(());
};
let mut draft = Self::draft(caller, kind, action);
if let Value::Object(fields) = fields {
for (key, value) in fields {
draft = draft.ext(key, value);
}
}
trail.record(draft).await.map_err(SurfaceError::Source)
}
}
/// Whether a turn that could not start may start later: the source was busy, unavailable or
/// over a limit, not refusing the request itself.
fn transient(error: &SurfaceError) -> bool {
use adk_core::ErrorCategory;
match error {
SurfaceError::Source(error) => match error.category {
ErrorCategory::RateLimited
| ErrorCategory::Timeout
| ErrorCategory::Unavailable
| ErrorCategory::Cancelled
| ErrorCategory::Internal
| ErrorCategory::ResourceExhausted
| ErrorCategory::Conflict => true,
ErrorCategory::InvalidInput
| ErrorCategory::Unauthorized
| ErrorCategory::Forbidden
| ErrorCategory::NotFound
| ErrorCategory::Unsupported => false,
},
SurfaceError::NotFound { .. }
| SurfaceError::Rule(_)
| SurfaceError::NotHere(_)
| SurfaceError::OperatorOnly { .. }
| SurfaceError::Unsupported { .. }
| SurfaceError::Invalid(_) => false,
}
}
/// `label` with its first letter in lower case, to follow a "·" in a sentence.
fn lower_first(label: &str) -> String {
let mut chars = label.chars();
match chars.next() {
Some(first) => first.to_lowercase().chain(chars).collect(),
None => String::new(),
}
}
/// The session-owner check every read and command makes (spec 3.3 §11 S-I8).
fn owns(caller: &Caller, request: &ApprovalRequest) -> bool {
request.scope.user_id == caller.user_id()
}
#[cfg(test)]
mod tests {
use adk_core::audit_log::InMemoryAuditRecorder;
use adk_core::{InMemoryApprovalStore, StoreApprovalService};
use adk_session::InMemorySessionService;
use super::*;
use crate::LocalSource;
/// A feature's record carries who did it, where and how, as every surface record does,
/// under the kind the kernel's surface-records route accepts (spec 3.3 §11).
#[tokio::test]
async fn a_feature_record_is_stamped_like_every_surface_record() {
let source = LocalSource::builder("adk-rust")
.sessions(Arc::new(InMemorySessionService::new()))
.approvals(Arc::new(StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))))
.build()
.unwrap();
let audit = InMemoryAuditRecorder::new();
let engine = SurfaceEngine::builder(Arc::new(source))
.audit(AuditTrail::new(Arc::new(audit.clone())))
.build();
let caller = Caller::human("ana", SurfaceKind::Phone, Origin::Touch)
.with_device("dev-1")
.with_presence_confirmed();
engine.record(&caller, "surface.verb", json!({ "verb": "snooze" })).await.unwrap();
let expected =
AuditRecordDraft::new(AuditRecordKind::Other("surface".into()), "surface.verb")
.actor(AuditActor::subject(caller.subject.clone()))
.ext("surface", json!("phone"))
.ext("origin", json!({ "kind": "touch" }))
.ext("device", json!("dev-1"))
.ext("presence", json!("confirmed"))
.ext("verb", json!("snooze"));
assert_eq!(audit.records(), vec![expected]);
}
}