tilo-actions 0.5.2

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
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
//! Using another peer's actions: a transport-neutral vocabulary.
//!
//! A peer that serves live apps (a desktop session, a headless app server)
//! can let an authenticated remote caller list the actions it
//! publishes, invoke one, follow its progress, and cancel it. This module is
//! the whole contract between the two sides:
//!
//! - [`RemoteActionMessage`] — requests and their answers, wrapped in a
//!   versioned [`RemoteActionFrame`] that any transport carries as opaque
//!   bytes.
//! - [`ActionProvider`] — what a peer implements to answer them, and [`serve`],
//!   which maps one request frame onto a provider. Answers that need an
//!   application's help arrive later as a [`Pending`], so no caller blocks.
//! - [`CatalogueQuery`] — paged, filtered browsing of what a provider offers.
//! - [`InvocationLog`] — the idempotency rule every provider shares: an
//!   invocation is keyed by its caller-chosen [`InvocationId`], so a retry
//!   after a lost reply observes the original invocation instead of running
//!   the action twice.
//!
//! Who is calling is never read from a payload. The transport that
//! authenticated the connection constructs the [`Caller`] and hands it to the
//! provider beside the message; nothing in a frame can name or change it.
//!
//! Descriptors, addresses, arguments, outputs and lifecycle updates are the
//! same types the local action surface already uses ([`ActionDescriptor`](crate::api::ActionDescriptor),
//! [`ActionAddress`], [`InvocationUpdate`], [`ActionOutput`],
//! [`ActionFailure`]), so a remote caller sees exactly what a local one does.

use std::collections::{HashMap, VecDeque};

use serde::{Deserialize, Serialize};

pub use window_actions::{activation_requested, link_scheme, render_anchor};

pub mod admitted;
pub use admitted::{Admits, Admitted, LiveRead, LiveView, Outcome, ReportsProgress, Serving};
mod application;
pub mod asked;
/// An app's sound output on the device, on the connection its launcher handed it.
pub mod audio_output;
/// An outside service's call carried into a workspace's call, on an app's connection.
pub mod call;
mod caller;
/// An app's own place in a workspace's call, on the connection its launcher handed it.
pub mod native_media;
/// A shell the device's shell runtime runs, carried on an app's connection.
pub mod shell;
pub use caller::{Caller, Invited, KeptCaller, KeyCall, PlacedCaller, device_agent_id};
pub mod signed_invocation;
pub use signed_invocation::{CallAllowed, SignedCall, SignedInvocation};
mod catalogue;
mod changes;
mod confirmation;
mod content_get;
mod content_link;
mod content_put;
/// Adding a computer to the person's devices with a one-use ticket: the computer's own daemon
/// issues it, prints the one string, and the new computer logs in with it.
pub mod device_tickets;
mod pending;
pub mod session_actions;
mod vault;
pub use vault::{
    ItemRef, KEEP_SEALED, KEEP_USES, REMOVE_SEALED, VAULT_DEVICE_KEY, VAULT_FIND,
    VAULT_FORGET_PAGE_LOGIN, VAULT_ITEM_KIND, VAULT_KEEP, VAULT_KEEP_PAGE_LOGIN, VAULT_KIND,
    VAULT_LIST, VAULT_PAGE_FILL, VAULT_PAGE_LOGINS, VAULT_PROVIDER, VAULT_RECORD, VAULT_RELEASE,
    VAULT_RESOURCE, VAULT_SECRET_ANSWERS, answers_secret, calls_answering_a_secret,
    calls_by_address, item_param, takes_item, vault_target,
};
pub mod press_points;
mod providers;
mod resource_read;
pub mod secret_arguments;
mod session_state;
mod shared_provider;
mod store_commands;
mod surfaces;
#[cfg(any(test, feature = "test-support"))]
mod test_provider;
pub use session_state::{SessionState, SyncState, WorkspaceState};
mod wait;
mod watch;
pub use watch::{CHANGED_UNAVAILABLE, Here, HereWindow, KEY_GRANTS, PRESENCE, WatchScope};
mod window_actions;
mod within;
pub mod workspace_activity;

pub use application::{
    APPLICATION_PROVIDER, application_action_target, application_open_target, application_provider,
    application_provider_resource, application_provider_token, application_resource_target,
    valid_file_name,
};
pub use confirmation::{
    ASK, ASK_PROVIDER, ASK_RESOURCE, ASK_WITH_CHOICES, Confirmation, ConfirmationQuestion,
    ConfirmationReply, MAX_ASK_CHARS, MAX_ASK_CHOICES, MAX_CHOICE_CHARS, PersonAnswer, PersonAsk,
    argument_digest, ask_target, is_ask,
};
pub use providers::{
    APPLICATION_OPEN_ACTION, APPLICATION_RESOURCE_KIND, APPLICATION_RESOURCE_PREFIX,
    APPLICATION_START_ACTION, DEVICE_FILES_FOLDER, DEVICE_FILES_PROVIDER, OWN_PROVIDER,
    RESOURCE_PROVIDER, SHARE_LINK_ACTION, WORKSPACE_PROVIDER, is_resource_provider, resource_parts,
};

pub use catalogue::{
    CanonicalActionRoute, CatalogueLimits, CataloguePage, CatalogueProvider, CatalogueQuery,
    CatalogueResource, CatalogueRow, MAX_BY_RESOURCE_PAGE, MAX_CATALOGUE_PAGE,
    MAX_CATALOGUE_PAGE_BYTES, Offered, ProvidedPackage, ProvidedResource, ResourceViewLocator,
    RowVisibility, ViewResourceQuery, compact, expand, rows_weight, stem_word, truncate_bytes,
    truncate_resources, truncate_rows,
};
pub use changes::{CHANGE_FEED_UNAVAILABLE, ChangeFeed, ChangePage, ResourceChanged, What};
pub use content_get::{CONTENT_GETS_UNAVAILABLE, ContentGetAnswer, ContentGets, ContentPiece};
pub use content_link::{
    CONTENT_LINK_TTL_SECS, CONTENT_LINKS_UNAVAILABLE, ContentLink, ContentLinkAsk, ContentLinkFile,
    MAX_CONTENT_LINK_FILES, viewable,
};
pub use content_put::{
    CONTENT_PUTS_UNAVAILABLE, CONTENT_REFERENCE, ContentPut, ContentPutAnswer, ContentPutStep,
    ContentPuts, HostedContentPuts, MAX_CONTENT_PUT_AHEAD, MAX_CONTENT_PUT_CHUNK, MAX_HAVE_HASHES,
    MAX_HOSTED_CONTENT_PUTS, MAX_OPEN_CONTENT_PUTS, MAX_PUT_MANY_BYTES, MAX_PUT_MANY_FILES,
    content_hash,
};
pub use store_commands::{STORE_COMMANDS_UNAVAILABLE, StoreCommands};
mod execution_lease;
pub use execution_lease::ExecutionLease;
pub use pending::{Abandoned, Completer, Pending, PendingPoll, pending};
pub use resource_read::{
    DEVICE_JOBS, DEVICE_SETTINGS, DEVICE_SETTINGS_REFUSED, Decided, HeldCopies, ListedResource,
    RESOURCE_READ_REFUSED, RESOURCE_READS_FOR_AGENTS, RESOURCE_READS_UNAVAILABLE,
    RESOURCE_WRITE_REFUSED, ReadingAnswer, ReadsAnswer, ResourceAddress, ResourceAsk, ResourceCopy,
    ResourceReadings, ResourceReads, ResourceWake, answer_read, answered, device_job_address,
    device_job_path, device_record_address, device_record_space, parse_device_record_space,
    parse_job_path, read_resources, readings_from, readings_of, reads_answer,
};
#[cfg(any(test, feature = "test-support"))]
pub use test_provider::TestProvider;
pub use wait::{MAX_REMOTE_WAIT, MAX_REMOTE_WAIT_MS, UpdateMark, settle_with};

use crate::api::ActionAddress;
use crate::context::ActionContext;
use crate::outcome::{ActionFailure, ActionOutput, InvocationId, InvocationUpdate};
use crate::params::ARGUMENTS_JSON_PREFIX;

/// Version of the [`RemoteActionFrame`] schema this build speaks.
///
/// Additive changes keep the version; a change an older peer would misread
/// bumps it, and [`RemoteActionFrame::decode`] refuses a version it does not know.
pub const REMOTE_ACTIONS_VERSION: u16 = 5;

/// Upper bound on one encoded frame: a provider pages its catalogue rather than raise this.
pub const MAX_REMOTE_ACTION_FRAME_BYTES: usize = 1024 * 1024;

/// The most raw bytes one piece of content carries, into a workspace's store
/// ([`ContentPutStep::Append`]) or out of it ([`ContentGetAnswer`]): hex doubles
/// them, and a caller splits anything larger.
pub const MAX_CONTENT_FRAME_BYTES: usize = 384 * 1024;

/// Default number of invocations an [`InvocationLog`] remembers.
pub const DEFAULT_LOG_CAPACITY: usize = 1024;

/// Which published action an invocation names on the provider.
///
/// `provider` is an opaque token the provider issued in a [`CataloguePage`]
/// (which live app published the action); `address` is the app's own stable
/// resource/action pair. A caller copies both from a catalogue entry and
/// never constructs a provider itself.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RemoteActionTarget {
    pub provider: String,
    pub address: ActionAddress,
}

/// The provider a workspace's own governance actions (membership, roles, grants,
/// bans) are answered under. It is the provider's, not an app's, so it is the
/// one provider a caller names without reading it from a catalogue page.
pub const WORKSPACE_GOVERNANCE_PROVIDER: &str = tilo_action_policy::agent_answers::WORKSPACE_APP;
/// The resource kind of a workspace's governance resource.
pub const WORKSPACE_GOVERNANCE_KIND: &str = "workspace.permissions";

impl RemoteActionTarget {
    /// The governance action granted as `verb` (one of
    /// `tilo_action_policy::roles::governance`, `server.add` and the like) on
    /// the workspace `workspace`, at the address its tree publishes it
    /// ([`workspace_governance_address`]).
    #[must_use]
    pub fn workspace_governance(workspace: &str, verb: &str) -> Self {
        Self {
            provider: WORKSPACE_GOVERNANCE_PROVIDER.to_owned(),
            address: workspace_governance_address(workspace, verb),
        }
    }
}

/// The root of a workspace's governance tree: the workspace itself, the
/// resource an agent's path `workspace` names.
#[must_use]
pub fn workspace_governance_resource(workspace: &str) -> String {
    format!("{WORKSPACE_GOVERNANCE_KIND}:{workspace}")
}

/// The servers keeping a workspace, under its governance root
/// (`workspace/servers`).
pub const WORKSPACE_SERVERS: &str = "servers";
/// The apps and bots a workspace uses, under its governance root
/// (`workspace/apps`).
pub const WORKSPACE_APPS: &str = "apps";
/// The attestors a workspace trusts and the publisher keys it refuses, under
/// its governance root (`workspace/trust`).
pub const WORKSPACE_TRUST: &str = "trust";
/// The registries a workspace fetches apps from, under its governance root
/// (`workspace/registries`).
pub const WORKSPACE_REGISTRIES: &str = "registries";
/// The limits a workspace's owners set on what members post there, under its
/// governance root (`workspace/content`): the largest file a host keeps and
/// what one member's files may take, now and in any hour. Read by every
/// member as the Workspace package's `content` root.
pub const WORKSPACE_CONTENT: &str = "content";
/// One app a workspace runs (`workspace/apps/<app>`, its id): what updates, pins and uninstalls
/// it is published on it.
pub const WORKSPACE_APP: &str = "apps/*";
/// The mail accounts a workspace keeps on its server, under its governance
/// root (`workspace/mail-accounts`): `tilo.accounts`'s, reached by path.
pub const WORKSPACE_MAIL_ACCOUNTS: &str = "mail-accounts";
/// The items of a workspace's vault, under its governance root
/// (`workspace/vault`): `tilo.vault`'s, reached by path.
pub const WORKSPACE_VAULT: &str = "vault";
/// The model providers a workspace keeps on its server, under its governance
/// root (`workspace/models`): `tilo.models`'s, reached by path.
pub const WORKSPACE_MODELS: &str = "models";
/// The people in a workspace, under its governance root (`workspace/members`).
pub const WORKSPACE_MEMBERS: &str = "members";
/// One person among a workspace's people (`workspace/members/<person>`, their user public key
/// in hex): what changes their role and removes them is published on them.
pub const WORKSPACE_MEMBER: &str = "members/*";
/// The workspace's action that issues an invitation: letting someone in put off until they
/// redeem it, so the workspace's `add-member` grants decide it for the role it hands out, as they
/// decide redeeming it.
pub const WORKSPACE_INVITE: &str = "invite";
/// The action `workspace/members#admit` publishes: admit a person to the workspace at a place,
/// whether or not they held one, as [`WORKSPACE_MEMBER_PLACED`] would a member's. The change that
/// admits them keeps their membership record with it.
pub const WORKSPACE_MEMBER_ADMITTED: &str = "admit";
/// The action `workspace/members/<person>#role` publishes: change the place of a person the
/// workspace holds. A person it does not hold is added by [`WORKSPACE_MEMBER_ADMITTED`], never
/// given a place here.
pub const WORKSPACE_MEMBER_PLACED: &str = "role";
/// The action `workspace/members/<person>#remove` publishes: remove the person, as the
/// workspace's grants on removing let whoever asks, or themselves.
pub const WORKSPACE_MEMBER_REMOVED: &str = "remove";
/// The invitations a workspace has open, under its governance root
/// (`workspace/invitations`).
pub const WORKSPACE_INVITATIONS: &str = "invitations";
/// The addresses left at a workspace's entry while it takes people by
/// invitation, under its governance root (`workspace/waiting`).
pub const WORKSPACE_WAITING: &str = "waiting";
/// The grants of a workspace's policy, under its governance root (`workspace/permissions`).
pub const WORKSPACE_PERMISSIONS: &str = "permissions";
/// One grant of a workspace's policy (`workspace/permissions/<grant>`, by its id): what takes
/// it back is published on it.
pub const WORKSPACE_PERMISSION: &str = "permissions/*";
/// The operation a workspace's grant is taken back by, published as
/// `workspace/permissions/<grant>#revoke`: by the person who gave it, or by whoever the
/// workspace's policy lets revoke grants.
pub const WORKSPACE_GRANT_REVOKE: &str = "grant.revoke";
/// The operation that lets a person or a role read one resource (`workspace/members#grant-read`):
/// a grant on the resource's own node, admitted by the workspace's grant on granting. Who belongs
/// to a channel, a shared folder or any resource is who reads it, so this is how one is let in
/// (`tilo_action_policy::reading`).
pub const WORKSPACE_READ_GRANT: &str = "reading.grant";
/// The operation that keeps a person or a role from reading one resource
/// (`workspace/members#revoke-read`), admitted by the workspace's grant on revoking.
pub const WORKSPACE_READ_REVOKE: &str = "reading.revoke";
/// The workspace's record of its agents, under its governance root (`workspace/agents`): who
/// works in the workspace, changed only by the three actions published there.
pub const WORKSPACE_AGENTS: &str = "agents";
/// Make an agent of the workspace (`workspace/agents#create`): the record's `create_agent`, its
/// arguments as that action takes them. Answers `{agent}`, the agent's id.
pub const WORKSPACE_AGENT_CREATE: &str = "agent.create";
/// Change one of the workspace's agents (`workspace/agents#update`): `{action, arguments}`, any
/// action of the record but making and retiring one, by its id and with its arguments.
pub const WORKSPACE_AGENT_UPDATE: &str = "agent.update";
/// Retire one of the workspace's agents (`workspace/agents#delete`): `{agent}`, its id. What it
/// did stays readable under its name.
pub const WORKSPACE_AGENT_DELETE: &str = "agent.delete";
/// The app that keeps a workspace's record of its agents: the workspace's own service.
pub const WORKSPACE_AGENTS_APP: &str = "tilo.workspace";
/// The kind of the workspace's record of its agents: what [`WORKSPACE_AGENT_CREATE`],
/// [`WORKSPACE_AGENT_UPDATE`] and [`WORKSPACE_AGENT_DELETE`] write.
pub const WORKSPACE_AGENTS_KIND: &str = "tilo.workspace.agent";
/// The steps of the record of agents [`WORKSPACE_AGENT_UPDATE`] takes: every one but making and
/// retiring an agent, and where an agent waits or runs, which the device that runs it writes.
pub const WORKSPACE_AGENT_CHANGES: [&str; 15] = [
    "set-agent-spend-limit",
    "record-agent-spend",
    "rename-agent",
    "set-agent-avatar",
    "set-agent-model",
    "set-agent-instruction",
    "pause-agent",
    "resume-agent",
    "start-sub-agent",
    "note-sub-agent",
    "stop-sub-agent",
    "sub-agent-stands",
    "sub-agent-produced",
    "sub-agent-coding",
    "set-sub-agent-limits",
];

/// What the agents' action `operation` (one of [`WORKSPACE_AGENT_CREATE`],
/// [`WORKSPACE_AGENT_UPDATE`] and [`WORKSPACE_AGENT_DELETE`]) writes: the steps the workspace's
/// host takes in its record of its agents when it answers the call. Nothing for any other
/// operation.
#[must_use]
pub fn workspace_agent_effects(operation: &str) -> Vec<crate::ActionEffect> {
    let step =
        |verb: &str| crate::ActionEffect::new(WORKSPACE_AGENTS_APP, WORKSPACE_AGENTS_KIND, verb);
    match operation {
        WORKSPACE_AGENT_CREATE => vec![step("create-agent")],
        WORKSPACE_AGENT_UPDATE => WORKSPACE_AGENT_CHANGES
            .iter()
            .map(|verb| step(verb))
            .collect(),
        WORKSPACE_AGENT_DELETE => vec![step("retire-agent")],
        _ => Vec::new(),
    }
}
/// Where a workspace's governance tree publishes the actions it grants by
/// another name: the operation a grant and a policy name it by, the resource
/// under the root it is on (none for the root itself) and its id there, as a
/// person names it. An operation not listed is published on the root under its
/// own name; one listed on [`WORKSPACE_MEMBER`] is published on each person, who
/// is its `person`, and one listed on [`WORKSPACE_APP`] on each app the workspace runs, which
/// is its `app`. One listed on [`WORKSPACE_PERMISSION`] is published on each of the
/// workspace's grants.
pub const WORKSPACE_MEMBER_LIST_PUBLISHED: [(&str, Option<&str>, &str); 47] = [
    ("member.list", Some(WORKSPACE_MEMBERS), "list"),
    (
        "member.add",
        Some(WORKSPACE_MEMBERS),
        WORKSPACE_MEMBER_ADMITTED,
    ),
    (
        "member.add",
        Some(WORKSPACE_MEMBER),
        WORKSPACE_MEMBER_PLACED,
    ),
    (
        "remove-member",
        Some(WORKSPACE_MEMBER),
        WORKSPACE_MEMBER_REMOVED,
    ),
    ("member.name", Some(WORKSPACE_MEMBERS), "name"),
    // Banning and lifting a ban name a person who need not be a member any more (a ban
    // removes them), so both are the members' verbs, taking the person, not one member's.
    ("ban", Some(WORKSPACE_MEMBERS), "ban"),
    ("unban", Some(WORKSPACE_MEMBERS), "unban"),
    ("invite", Some(WORKSPACE_INVITATIONS), "invite"),
    ("invitation.list", Some(WORKSPACE_INVITATIONS), "list"),
    ("invitation.cancel", Some(WORKSPACE_INVITATIONS), "cancel"),
    ("wait-list.list", Some(WORKSPACE_WAITING), "list"),
    ("wait-list.remove", Some(WORKSPACE_WAITING), "unlist"),
    ("wait-list.mail", Some(WORKSPACE_WAITING), "mail"),
    ("server.list", Some(WORKSPACE_SERVERS), "list"),
    ("server.add", Some(WORKSPACE_SERVERS), "add"),
    ("server.remove", Some(WORKSPACE_SERVERS), "remove"),
    ("server.move", Some(WORKSPACE_SERVERS), "move"),
    ("copies.set", Some(WORKSPACE_SERVERS), "copies"),
    ("copies.read", Some(WORKSPACE_SERVERS), "keeps"),
    ("content.held", Some(WORKSPACE_SERVERS), "content"),
    ("content.policy", Some(WORKSPACE_CONTENT), "policy"),
    ("content.set-policy", Some(WORKSPACE_CONTENT), "set-policy"),
    ("trust.list", Some(WORKSPACE_TRUST), "list"),
    ("trust.revoked", Some(WORKSPACE_TRUST), "revoked"),
    ("trust.add", Some(WORKSPACE_TRUST), "add"),
    ("trust.remove", Some(WORKSPACE_TRUST), "remove"),
    ("trust.revoke", Some(WORKSPACE_TRUST), "revoke"),
    ("registry.list", Some(WORKSPACE_REGISTRIES), "list"),
    ("registry.add", Some(WORKSPACE_REGISTRIES), "add"),
    ("registry.remove", Some(WORKSPACE_REGISTRIES), "remove"),
    ("registry.enable", Some(WORKSPACE_REGISTRIES), "enable"),
    ("registry.disable", Some(WORKSPACE_REGISTRIES), "disable"),
    ("registry.channel", Some(WORKSPACE_REGISTRIES), "channel"),
    ("install-app", Some(WORKSPACE_APPS), "install"),
    ("upload-app-file", Some(WORKSPACE_APPS), "upload"),
    ("app.offers", Some(WORKSPACE_APPS), "offers"),
    ("install-app", Some(WORKSPACE_APP), "update"),
    ("app.pin", Some(WORKSPACE_APP), "pin"),
    ("app.unpin", Some(WORKSPACE_APP), "unpin"),
    ("uninstall-app", Some(WORKSPACE_APP), "uninstall"),
    ("app.earlier", Some(WORKSPACE_APP), "earlier"),
    (WORKSPACE_GRANT_REVOKE, Some(WORKSPACE_PERMISSION), "revoke"),
    (WORKSPACE_READ_GRANT, Some(WORKSPACE_MEMBERS), "grant-read"),
    (
        WORKSPACE_READ_REVOKE,
        Some(WORKSPACE_MEMBERS),
        "revoke-read",
    ),
    (WORKSPACE_AGENT_CREATE, Some(WORKSPACE_AGENTS), "create"),
    (WORKSPACE_AGENT_UPDATE, Some(WORKSPACE_AGENTS), "update"),
    (WORKSPACE_AGENT_DELETE, Some(WORKSPACE_AGENTS), "delete"),
];

/// The provider a workspace's invocations answer under: the record of what was invoked
/// there, and the asked records a call waits in.
pub const WORKSPACE_INVOCATIONS_PROVIDER: &str = "tilo.invocations";

/// The provider that answers a person's install machines.
pub const MACHINES_PROVIDER: &str = "tilo.machines";

/// The provider a server answers its accounts under.
pub const SERVER_ACCOUNT_PROVIDER: &str = "tilo.server";

/// The provider that answers a workspace's events under.
pub const WORKSPACE_EVENTS_PROVIDER: &str = "tilo.events";

/// The provider a moderation turn reaches a person's recorded changes under.
pub const MODERATION_PROVIDER: &str = "tilo.moderation";
/// The resource its read and its undo are actions of.
pub const MODERATION_HISTORY: &str = "moderation.history";
/// Its action that takes a person's changes back.
pub const MODERATION_UNDO: &str = "undo";
/// The app whose record a moderation turn reads and takes changes back in: the workspace's chat.
pub const MODERATED_APP: &str = "so.tilo.chat";

/// The provider a workspace's model providers answer under. Their provider declares their
/// actions (`tilo_workspace_records::models`); what this crate knows of them is that a
/// workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`) and what each writes in the
/// workspace's vault (`tilo_workspace_records::models::MODEL_VAULT_STEPS`).
pub const MODELS_PROVIDER: &str = "tilo.models";

/// The provider a person's log of what they were told answers under. Its provider declares its
/// actions (`tilo_person_services::person_telling`); what this crate knows of it is that a
/// workspace's host keeps it (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`).
pub const TELLING_PROVIDER: &str = "tilo.telling";

/// The provider a workspace's connected accounts answer under. Their provider declares their
/// actions (`tilo_workspace_records::accounts`); what this crate knows of them is that
/// a workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`), what each writes
/// (`tilo_workspace_records::accounts::ACCOUNT_STEPS`) and which answer a secret
/// (`tilo_workspace_records::accounts::ACCOUNT_SECRET_ANSWERS`).
pub const ACCOUNTS_PROVIDER: &str = "tilo.accounts";

/// The provider a person's connected services answer under. Their provider declares their
/// actions (`tilo_workspace_records::connections`); what this crate knows of them is
/// that a workspace's host keeps them (`tilo_action_services::WORKSPACE_KEPT_PROVIDERS`), what each writes in the
/// workspace's vault and whose answers carry the service's own words
/// (`tilo_workspace_records::connections`).
pub const CONNECTIONS_PROVIDER: &str = "tilo.connections";

/// The resource `child` of `workspace`'s governance tree: the root for `None`.
#[must_use]
pub fn workspace_governance_child(workspace: &str, child: Option<&str>) -> String {
    let root = workspace_governance_resource(workspace);
    match child {
        Some(child) => format!("{root}/{child}"),
        None => root,
    }
}

/// The resource of the grant `grant` (its id) among `workspace`'s permissions.
#[must_use]
pub fn workspace_permission(workspace: &str, grant: &str) -> String {
    format!(
        "{}/{grant}",
        workspace_governance_child(workspace, Some(WORKSPACE_PERMISSIONS))
    )
}

/// The resource of the person `person` (their user public key in hex) among `workspace`'s people.
#[must_use]
pub fn workspace_member(workspace: &str, person: &str) -> String {
    format!(
        "{}/{person}",
        workspace_governance_child(workspace, Some(WORKSPACE_MEMBERS))
    )
}

/// The app `app` (its id) among the apps `workspace` runs.
#[must_use]
pub fn workspace_app(workspace: &str, app: &str) -> String {
    format!(
        "{}/{app}",
        workspace_governance_child(workspace, Some(WORKSPACE_APPS))
    )
}

/// The address `workspace`'s governance tree publishes the operation
/// `operation` at, where it is not one person's or one app's.
#[must_use]
pub fn workspace_governance_address(workspace: &str, operation: &str) -> ActionAddress {
    match WORKSPACE_MEMBER_LIST_PUBLISHED
        .iter()
        .find(|(granted, child, _)| {
            *granted == operation
                && *child != Some(WORKSPACE_MEMBER)
                && *child != Some(WORKSPACE_APP)
                && *child != Some(WORKSPACE_PERMISSION)
        }) {
        Some((_, child, action)) => {
            ActionAddress::new(workspace_governance_child(workspace, *child), *action)
        }
        None => ActionAddress::new(workspace_governance_resource(workspace), operation),
    }
}

/// The workspace and the operation `address` asks of that workspace's
/// governance, when its tree publishes one there: what
/// [`workspace_governance_address`] maps back. An operation published
/// elsewhere, asked by its grant's name, is none.
#[must_use]
pub fn workspace_governance_operation(address: &ActionAddress) -> Option<(&str, &str)> {
    let named = address
        .resource
        .strip_prefix(workspace_governance_resource("").as_str())?;
    let (workspace, child) = match named.split_once('/') {
        Some((workspace, child)) => (workspace, Some(child)),
        None => (named, None),
    };
    if workspace.is_empty() {
        return None;
    }
    let action = address.action.as_str();
    let child = if workspace_person(address).is_some() {
        Some(WORKSPACE_MEMBER)
    } else if workspace_app_named(address).is_some() {
        Some(WORKSPACE_APP)
    } else if workspace_grant(address).is_some() {
        Some(WORKSPACE_PERMISSION)
    } else {
        child
    };
    let published = WORKSPACE_MEMBER_LIST_PUBLISHED
        .iter()
        .find(|(_, at, published)| *at == child && *published == action);
    match published {
        Some((granted, _, _)) => Some((workspace, granted)),
        None if child.is_none()
            && !WORKSPACE_MEMBER_LIST_PUBLISHED
                .iter()
                .any(|(granted, _, _)| *granted == action) =>
        {
            Some((workspace, action))
        }
        None => None,
    }
}

/// The person (their user public key in hex) `address` names among its workspace's people
/// (`workspace/members/<person>`), when it names one.
#[must_use]
pub fn workspace_person(address: &ActionAddress) -> Option<&str> {
    let named = address
        .resource
        .strip_prefix(workspace_governance_resource("").as_str())?;
    let (members, person) = named.split_once('/')?.1.split_once('/')?;
    (members == WORKSPACE_MEMBERS
        && person.len() == 64
        && person.bytes().all(|byte| byte.is_ascii_hexdigit()))
    .then_some(person)
}

/// The app (its id) `address` names among the apps its workspace runs
/// (`workspace/apps/<app>`), when it names one.
#[must_use]
pub fn workspace_app_named(address: &ActionAddress) -> Option<&str> {
    let named = address
        .resource
        .strip_prefix(workspace_governance_resource("").as_str())?;
    let (apps, app) = named.split_once('/')?.1.split_once('/')?;
    (apps == WORKSPACE_APPS
        && !app.is_empty()
        && app
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')))
    .then_some(app)
}

/// The grant `address` is on, by its id, when it is one of a workspace's permissions
/// (`workspace/permissions/<grant>`).
#[must_use]
pub fn workspace_grant(address: &ActionAddress) -> Option<&str> {
    let named = address
        .resource
        .strip_prefix(workspace_governance_resource("").as_str())?;
    let (permissions, grant) = named.split_once('/')?.1.split_once('/')?;
    (permissions == WORKSPACE_PERMISSIONS && !grant.is_empty()).then_some(grant)
}

/// The person's settings, kept by the provider whether or not the app that shows
/// them is open: each section a record published with its field edits and
/// verbs (`settings:<kind>`), changed through them as that app's window
/// changes them. It is answered under the settings provider.
pub mod settings_resources {
    /// The provider that answers the person's settings.
    pub const PROVIDER: &str = "tilo.settings";
    /// The surface every section is typed by, whichever app shows it.
    pub const SURFACE_APP: &str = "so.tilo.settings.sections";

    /// Whether `path` (a resource, or an action of one) is a section of the person's settings
    /// (`settings/<section>`) or a device's (`devices/<id>/settings/<section>`).
    #[must_use]
    pub fn is_section(path: &str) -> bool {
        let resource = path.split('#').next().unwrap_or_default();
        let parts: Vec<&str> = resource.split('/').collect();
        matches!(parts.as_slice(), ["settings", section] if !section.is_empty())
            || matches!(parts.as_slice(), ["devices", device, "settings", section]
                if !device.is_empty() && !section.is_empty())
    }
}

/// Why a provider refuses a directory action that asks for confirmation when
/// the request names no revision: the confirmation covers the action as the
/// person was shown it, which only that revision identifies. A caller that
/// confirms on its own policy rather than a person's reads the current
/// revision and retries.
pub const CONFIRMED_ACTION_NEEDS_REVISION: &str =
    "a confirmed action needs the revision it was shown at";

/// What an invocation carries for the action's declared input.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvokeArgument {
    /// The action takes nothing.
    #[default]
    None,
    /// The single text input a prompted action collects.
    Text(String),
    /// The typed argument object checked against the action's parameters.
    Json(serde_json::Map<String, serde_json::Value>),
}

impl InvokeArgument {
    /// The single-slot form the local invocation path accepts: text as is,
    /// a typed object behind [`ARGUMENTS_JSON_PREFIX`].
    #[must_use]
    pub fn to_slot(&self) -> Option<String> {
        match self {
            Self::None => None,
            Self::Text(text) => Some(text.clone()),
            Self::Json(object) => Some(format!(
                "{ARGUMENTS_JSON_PREFIX}{}",
                serde_json::Value::Object(object.clone())
            )),
        }
    }

    /// What [`Self::to_slot`] carries, as the wire field it came from. A
    /// slot no typed object is written behind is text, which is what an
    /// action taking a prompt collects.
    #[must_use]
    pub fn from_slot(slot: Option<&str>) -> Self {
        match slot {
            None => Self::None,
            Some(text) => match text
                .strip_prefix(ARGUMENTS_JSON_PREFIX)
                .and_then(|json| serde_json::from_str(json).ok())
            {
                Some(object) => Self::Json(object),
                None => Self::Text(text.to_owned()),
            },
        }
    }
}

/// A request to run one published action.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvokeRequest {
    /// Chosen by the caller and reused verbatim on retry; the provider runs the
    /// action at most once per id.
    pub invocation: InvocationId,
    pub target: RemoteActionTarget,
    #[serde(default)]
    pub argument: InvokeArgument,
    /// Human provenance carried into history. It never grants authority.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<ActionContext>,
    /// The caller's explicit confirmation, for an action whose contract
    /// requires one. The provider checks it against the contract; it is
    /// evidence, not authority.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmation: Option<Confirmation>,
    /// The catalogue revision the caller chose the target from, for a
    /// provider whose actions are resolved live at that revision. A provider
    /// refuses a target that no longer exists at it rather than guessing.
    ///
    /// Omitted, a directory target resolves against the directory as it is
    /// now, and the admission is bound to the revision the provider
    /// resolved it at: an executing provider still refuses the action once the
    /// directory moved on before it ran. An action whose contract asks for
    /// confirmation needs the revision it was shown at; without one the
    /// provider refuses with [`CONFIRMED_ACTION_NEEDS_REVISION`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
    /// The live invocation this request continues: an edit an effect
    /// submits while running for someone else. The provider admits it as that
    /// invocation's original caller, with their grants, never as the app.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_behalf_of: Option<InvocationId>,
    /// Hold the receipt until the invocation settles or this many
    /// milliseconds pass (at most [`MAX_REMOTE_WAIT`]), so a quick action
    /// answers in one round trip. How the answer travels, not what runs:
    /// [`serve`] takes it off the request before the provider sees it, and
    /// [`InvocationLog`] ignores it. A provider that predates it answers at
    /// admission, as before.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_ms: Option<u32>,
    /// The name and avatar a bot asks to show for this action. Only an API
    /// that can check the caller is a bot allowed it admits one
    /// (the workspace-action API a bot drives); every other API refuses the request
    /// ([`crate::appearance::refuse_here`]) rather than dropping the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub appearance: Option<crate::Appearance>,
    /// The caller's own signature over who asks for which action on which
    /// resource with which arguments ([`SignedInvocation`]). A host that runs
    /// an invocation for a caller on another device requires it and acts as
    /// its verified signer; a request that never leaves its device (an app
    /// asking its own session) carries none.
    ///
    /// A call an app makes while it runs someone's invocation carries that invocation here
    /// instead, the one its [`Self::on_behalf_of`] names ([`SignedInvocation::serves`]): the
    /// original caller's signature is its proof, and the device running the app signs the
    /// request that brings it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signed: Option<Box<SignedInvocation>>,
}

impl InvokeRequest {
    /// The resource this call is made from, as its caller named it in its arguments
    /// ([`crate::params::FROM_ARGUMENT`]): what the resources it makes are made from, and what
    /// a turn it starts answers. The dispatch admits a call made from a resource only for a
    /// caller who may read that resource.
    #[must_use]
    pub fn made_from(&self) -> Option<crate::params::MadeFrom> {
        let InvokeArgument::Json(arguments) = &self.argument else {
            return None;
        };
        crate::params::MadeFrom::from_json(arguments.get(crate::params::FROM_ARGUMENT)?)
    }

    /// The person's approve of the asked record this call was kept as, when
    /// the dispatch admitted it again on their answer: what a provider that
    /// waits for their yes reads instead of asking.
    #[must_use]
    pub fn approval(&self) -> Option<&asked::Approval> {
        match &self.confirmation {
            Some(Confirmation::Asked(approval)) => Some(approval),
            _ => None,
        }
    }

    /// What the agent's harness calls the session this request was sent in ("Release prep"), as
    /// the client's agent-session group says it: display only, the name people see the agent by
    /// ([`Caller::in_named_session`]). `None` when the client named no session.
    #[must_use]
    pub fn said_session_name(&self) -> Option<String> {
        let group = self
            .context
            .as_ref()?
            .group
            .as_ref()
            .filter(|group| group.kind == crate::context::AGENT_SESSION_GROUP)?;
        crate::context::one_line(group.session.as_deref()?, crate::context::MAX_LABEL_CHARS)
    }

    /// Whether `other` asks for the same invocation: every field but the
    /// transport-only [`wait_ms`](Self::wait_ms), so a retry that waits
    /// differently is still a retry.
    #[must_use]
    pub fn same_invocation(&self, other: &Self) -> bool {
        let Self {
            invocation,
            target,
            argument,
            context,
            confirmation,
            revision,
            on_behalf_of,
            wait_ms: _,
            appearance,
            // Evidence of who asked, checked on its own: a retry the caller
            // signed again is still a retry.
            signed: _,
        } = self;
        *invocation == other.invocation
            && *target == other.target
            && *argument == other.argument
            && *context == other.context
            && *confirmation == other.confirmation
            && *revision == other.revision
            && *on_behalf_of == other.on_behalf_of
            && *appearance == other.appearance
    }

    /// An invocation of `target` with `arguments` and nothing else: no context, revision or
    /// signature, answered once it is admitted.
    #[must_use]
    pub fn plain(
        target: RemoteActionTarget,
        arguments: serde_json::Map<String, serde_json::Value>,
    ) -> Self {
        Self {
            invocation: InvocationId::new(),
            target,
            argument: if arguments.is_empty() {
                InvokeArgument::None
            } else {
                InvokeArgument::Json(arguments)
            },
            context: None,
            confirmation: None,
            revision: None,
            on_behalf_of: None,
            wait_ms: None,
            appearance: None,
            signed: None,
        }
    }
}

/// Action id that closes a running application's windows in a workspace.
pub const APPLICATION_CLOSE_ACTION: &str = "close";

/// The provider token for the actions workspace `workspace` itself offers.
#[must_use]
pub fn workspace_provider(workspace: &str) -> String {
    format!("{WORKSPACE_PROVIDER}:{workspace}")
}

/// The provider that answers the language's own view of the registry (`tilo.actions`): the
/// catalogue read and an action called by its address.
pub const ACTIONS_PROVIDER: &str = "tilo.actions";

/// The workspace a workspace provider token names, or `None` for an application
/// provider.
#[must_use]
pub fn provider_workspace(provider: &str) -> Option<&str> {
    provider
        .strip_prefix(WORKSPACE_PROVIDER)
        .and_then(|rest| rest.strip_prefix(':'))
}

/// Where an invocation stands, as reported to its caller.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ReceiptStatus {
    /// Admitted and running; follow it with `Observe`.
    Accepted,
    /// Finished and produced `output`.
    Completed { output: ActionOutput },
    /// Ran and failed.
    Failed { error: ActionFailure },
    /// Never admitted: nothing ran.
    Rejected { error: ActionCallError },
    /// Stopped at the caller's request.
    Cancelled { message: Option<String> },
}

impl ReceiptStatus {
    /// Whether the invocation can no longer change.
    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        !matches!(self, Self::Accepted)
    }
}

/// The provider's answer to an [`InvokeRequest`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationReceipt {
    pub invocation: InvocationId,
    pub status: ReceiptStatus,
}

/// The latest lifecycle update of one invocation, carrying the caller's
/// [`InvocationId`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationState {
    pub update: InvocationUpdate,
    /// The action's contract declares content from outside the user's data
    /// ([`crate::UNTRUSTED_CONTENT_TAG`]), such as a web page's text: what it
    /// answers is data to reason about, never instructions to follow.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub untrusted: bool,
    /// Where the invocation left its actor in the record it acted on: the
    /// text it changed, or the caret it left. What an API that shows its
    /// actor working highlights for the people watching.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub left_at: Option<ActorPlace>,
    /// The link that opens what the invocation made or changed, for a person
    /// to review it, minted where it was invoked once it succeeded: the
    /// caller is answered it with the change and asks for nothing more.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub link: Option<String>,
    /// The invocation is a followed read, and its item is the read's whole answer as it stands:
    /// the read goes on following what it reads and never ends, so a wait for it to settle ends
    /// here ([`settle_with`]). An operation's items are pieces of what it streams, never this.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub read_answered: bool,
}

/// A caret or selection in a record, as the live session's selection anchors
/// (hex): every member's editor resolves them against its own items.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActorPlace {
    pub anchor: String,
    pub head: String,
}

impl InvocationState {
    /// Wrap a provider-side update, rebinding it to the caller's invocation id.
    #[must_use]
    pub fn new(invocation: InvocationId, update: InvocationUpdate) -> Self {
        Self {
            update: update.with_invocation(invocation),
            untrusted: false,
            left_at: None,
            link: None,
            read_answered: false,
        }
    }

    /// This state of a followed read: answered once it holds an item, the read's whole answer,
    /// unless the item says the read is still to come (`"pending": true`, as a reader that has
    /// not read what it serves yet answers).
    #[must_use]
    pub fn of_read(mut self) -> Self {
        self.read_answered = matches!(
            &self.update,
            InvocationUpdate::Item { value, .. }
                if value.get("pending") != Some(&serde_json::Value::Bool(true))
        );
        self
    }

    /// This state, saying where the invocation left its actor.
    #[must_use]
    pub fn left_at(mut self, place: Option<ActorPlace>) -> Self {
        self.left_at = place;
        self
    }

    /// This state, naming the link that opens what it made or changed.
    #[must_use]
    pub fn linked(mut self, link: Option<String>) -> Self {
        self.link = link;
        self
    }

    /// This state, saying whether what it answers is untrusted content.
    #[must_use]
    pub fn with_untrusted(mut self, untrusted: bool) -> Self {
        self.untrusted = untrusted;
        self
    }

    #[must_use]
    pub fn invocation(&self) -> InvocationId {
        self.update.invocation()
    }

    #[must_use]
    pub fn is_terminal(&self) -> bool {
        self.update.is_terminal()
    }

    /// The receipt this state amounts to: accepted while running, the
    /// outcome once terminal.
    #[must_use]
    pub fn receipt(&self) -> InvocationReceipt {
        let status = match &self.update {
            InvocationUpdate::Accepted { .. }
            | InvocationUpdate::Progress { .. }
            | InvocationUpdate::Item { .. } => ReceiptStatus::Accepted,
            InvocationUpdate::Succeeded { output, .. } => ReceiptStatus::Completed {
                output: output.clone(),
            },
            // An action that reached something only the person may allow
            // stopped before it ran: their answer is what it waits on, which
            // is a refusal to the caller, not a failure of the action.
            InvocationUpdate::Failed { error, .. } if error.code == CONFIRMATION_REQUIRED_CODE => {
                ReceiptStatus::Rejected {
                    error: ActionCallError::asks(asked::AskedFacts::from_details(
                        error.details.as_ref(),
                    )),
                }
            }
            InvocationUpdate::Failed { error, .. } => ReceiptStatus::Failed {
                error: error.clone(),
            },
            InvocationUpdate::Cancelled { message, .. } => ReceiptStatus::Cancelled {
                message: message.clone(),
            },
        };
        InvocationReceipt {
            invocation: self.invocation(),
            status,
        }
    }
}

/// The failure code an action answers while it runs when what it reached
/// waits for the person's word ([`ApiError::ConfirmationRequired`]): the
/// caller's invocation is refused for want of their answer, and their
/// answer runs it again.
///
/// [`ApiError::ConfirmationRequired`]: crate::api::ApiError::ConfirmationRequired
pub const CONFIRMATION_REQUIRED_CODE: &str = "action_confirmation_required";

/// The code a caller reads for a call that waits for its person to approve it on a device that
/// holds their identity, which its state says ([`asked::ASKED_PHASE`]): it goes on once they
/// allow it.
pub const AWAITING_APPROVAL: &str = "awaiting_approval";

/// The code a server refuses a person it does not know yet with: its operator has not declared
/// them an owner, and no invitation of a workspace there brought them in.
pub const NOT_ON_THIS_SERVER: &str = "not_on_this_server";

/// The code a host that keeps no workspaces of people's own refuses making, deleting or
/// branching one with: the operations are the same on every host, and this one says why it does
/// not carry them out, in a code a page reads.
pub const HOSTS_NONE_FOR_PEOPLE: &str = "hosts_none_for_people";

/// The code a workspace refuses a key its person revoked with: nothing it asks is answered
/// until they approve another.
pub const KEY_REVOKED: &str = "key_revoked";

/// What a key that no longer acts (revoked, expired, or no longer granted in its workspace) is
/// told to do: the one command that approves a key again.
pub const APPROVE_AGAIN: &str = "approve a new key: the person types `tilo do account/keys#create name=\"<name>\"` \
     and approves it in their Tilo tab (on their own computer, `tilo login` again)";

/// The refusal of a server that does not know `person` (their root key) yet, saying what to do:
/// its operator declares them an owner, or they join with an invitation link.
#[must_use]
pub fn not_on_this_server(person: &[u8; 32]) -> ActionCallError {
    let key = hex::encode(person);
    ActionCallError::Refused {
        reason: format!(
            "{NOT_ON_THIS_SERVER}: This server doesn't know you yet: its operator hasn't made you \
             an owner, and no invitation brought you into a workspace here. Ask the operator to \
             declare your key {key} an owner (on a local stack: `stack.sh owner {key}`), or join \
             with an invitation link someone here sends you."
        ),
    }
}

/// Why a provider would not do what was asked. Every variant but [`Self::Unanswered`] means
/// nothing ran.
///
/// On the wire it keeps the shape peers decoded before
/// [`Self::StaleRevision`] existed: that variant travels as the
/// [`Self::InvalidRequest`] those peers sent and understand, and such a
/// refusal from them reads back as it. A variant an older peer cannot
/// decode would fail its whole frame.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(from = "WireActionCallError", into = "WireActionCallError")]
pub enum ActionCallError {
    /// The provider serves no actions right now (no live apps, service off).
    #[error("remote actions are unavailable: {reason}")]
    Unavailable { reason: String },
    /// The target is not offered to this caller — unknown and forbidden are
    /// deliberately the same answer.
    #[error("no such action is offered")]
    UnknownAction,
    /// The caller's authority does not cover the action.
    #[error("the caller may not invoke this action")]
    NotPermitted,
    /// The action waits for a person's yes this request did not carry: what
    /// they are shown ([`asked::AskedFacts`]). The dispatch keeps the call as
    /// an asked invocation record, and their approve admits it again.
    #[error("the action requires confirmation")]
    ConfirmationRequired(Box<asked::AskedFacts>),
    /// The request is malformed for this action (arguments, input).
    #[error("invalid request: {reason}")]
    InvalidRequest { reason: String },
    /// The target changed since the revision the request named, or the one
    /// its provider resolved it against: list it again and invoke what is
    /// offered now.
    #[error("invalid request: {}", STALE_REVISION_REASON)]
    StaleRevision,
    /// The invocation id is unknown to this caller.
    #[error("no such invocation")]
    UnknownInvocation,
    /// The invocation id was already used for a different request.
    #[error("the invocation id was already used for a different request")]
    InvocationConflict,
    /// The invocation cannot be cancelled (finished, or never cancellable).
    #[error("the invocation cannot be cancelled: {reason}")]
    NotCancellable { reason: String },
    /// The provider refused for a reason of its own.
    #[error("refused: {reason}")]
    Refused { reason: String },
    /// The workspace is not serving this caller here yet: the same call
    /// works once it is (its `serving` state).
    #[error("the workspace is not ready for this call yet")]
    NotReady,
    /// The device or provider that runs the call did not answer in time. Unlike
    /// every other variant this one does not say that nothing ran: the same
    /// call under the same invocation id is answered by what it did, and runs
    /// it once if it never arrived.
    #[error("the action's provider did not answer in time")]
    Unanswered,
}

impl ActionCallError {
    /// A refusal of the action API ([`crate::api`]) as the action wire says it: the API's own
    /// code, so a caller tells "no such action" apart from "not now" and "not shaped like that"
    /// without reading prose. An API that refused for a reason of its own says it in words, its
    /// code leading them.
    #[must_use]
    pub fn from_api(error: &crate::ApiError) -> Self {
        use crate::ApiError;
        match error {
            ApiError::Unknown(_) | ApiError::UnregisteredType(_) => Self::UnknownAction,
            ApiError::MissingArgument(_)
            | ApiError::UnexpectedArgument(_)
            | ApiError::InvalidArguments(_)
            | ApiError::ArgumentOutOfRange { .. } => Self::InvalidRequest {
                reason: error.to_string(),
            },
            ApiError::ConfirmationRequired => Self::confirmation_required(),
            ApiError::Unavailable { .. } | ApiError::Refused { .. } | ApiError::Failed(_) => {
                Self::Refused {
                    reason: error.to_string(),
                }
            }
        }
    }

    /// The refusal for want of the person's answer, for an action whose
    /// name says all the person is shown.
    #[must_use]
    pub fn confirmation_required() -> Self {
        Self::asks(asked::AskedFacts::default())
    }

    /// The refusal for want of the person's answer, showing them `facts`.
    #[must_use]
    pub fn asks(facts: asked::AskedFacts) -> Self {
        Self::ConfirmationRequired(Box::new(facts))
    }

    /// The provider refused for a reason of its own.
    #[must_use]
    pub fn refused(reason: impl Into<String>) -> Self {
        Self::Refused {
            reason: reason.into(),
        }
    }

    /// What the provider said in its own words, for the person reading it: the reason a refusal
    /// of its own carries, without the code a caller matches on, else the sentence of its variant.
    #[must_use]
    pub fn own_words(&self) -> String {
        match self {
            Self::Refused { reason } => reason.clone(),
            other => other.to_string(),
        }
    }

    /// The request is malformed for this action.
    #[must_use]
    pub fn invalid_request(reason: impl Into<String>) -> Self {
        Self::InvalidRequest {
            reason: reason.into(),
        }
    }

    /// The provider serves no actions right now.
    #[must_use]
    pub fn unavailable(reason: impl Into<String>) -> Self {
        Self::Unavailable {
            reason: reason.into(),
        }
    }

    /// Stable machine-readable code.
    #[must_use]
    pub const fn code(&self) -> &'static str {
        match self {
            Self::Unavailable { .. } => "remote_actions_unavailable",
            Self::UnknownAction => "unknown_action",
            Self::NotPermitted => "not_permitted",
            Self::ConfirmationRequired(_) => "action_confirmation_required",
            Self::InvalidRequest { .. } => "invalid_arguments",
            Self::StaleRevision => "stale_revision",
            Self::UnknownInvocation => "unknown_invocation",
            Self::InvocationConflict => "invocation_conflict",
            Self::NotCancellable { .. } => "not_cancellable",
            Self::Refused { .. } => "refused",
            Self::NotReady => "not_ready",
            Self::Unanswered => "unanswered",
        }
    }

    /// This refusal as a caller is told it: the code the API documents
    /// (`docs/tilo-sh/errors.md`), then what happened, so a caller reading the
    /// typed answer gets the code and one reading the text still reads a
    /// sentence that says what to do.
    #[must_use]
    pub fn said(&self) -> String {
        match self {
            // A caller that retries the same stale revision fails the same way:
            // what to do instead is said.
            Self::StaleRevision => "stale_revision: the resource changed since you read it. \
                Call the action again with tilo_do, which runs it against the resource as it \
                is now, or tilo_read the resource first to see what changed"
                .to_owned(),
            // Refused by the workspace's permissions: said as that, with where it is
            // changed, never as an action the caller cannot name.
            Self::NotPermitted => {
                format!("not_permitted: {}", crate::Availability::NOT_ALLOWED_HERE)
            }
            // What the host could not run now is `unavailable`, the code the API
            // documents; the host's own words follow rather than a restatement.
            Self::Unavailable { reason } => format!("unavailable: {reason}"),
            // No answer is not an answer that nothing is there: a workspace that just
            // started may still be opening its documents, and answers when asked again.
            Self::Unanswered => "unanswered: the workspace did not answer in time; it may \
                still be opening its documents after it started, so ask again"
                .to_owned(),
            Self::InvalidRequest { reason } | Self::Refused { reason } => {
                format!("{}: {reason}", self.code())
            }
            other => format!("{}: {other}", other.code()),
        }
    }

    /// Whether the same call, under the same invocation id, is worth making
    /// again: once the workspace serves the caller ([`Self::NotReady`]), or at
    /// once ([`Self::Unanswered`]).
    #[must_use]
    pub const fn ask_again(&self) -> bool {
        matches!(self, Self::NotReady | Self::Unanswered)
    }

    /// Whether `code` is the [`code`](Self::code) of a refusal the same call is asked again
    /// for ([`Self::ask_again`]), as a failed invocation carries it.
    #[must_use]
    pub fn ask_again_code(code: &str) -> bool {
        code == Self::NotReady.code() || code == Self::Unanswered.code()
    }

    /// Whether the provider refused a directory action that asks for
    /// confirmation because the request named no revision
    /// ([`CONFIRMED_ACTION_NEEDS_REVISION`]).
    #[must_use]
    pub fn needs_revision(&self) -> bool {
        matches!(self, Self::InvalidRequest { reason } if reason == CONFIRMED_ACTION_NEEDS_REVISION)
    }
}

/// What [`ActionCallError::StaleRevision`] says, and the reason it carries
/// on the wire as an [`ActionCallError::InvalidRequest`].
pub const STALE_REVISION_REASON: &str = "the target changed since that revision; list it again";

/// [`ActionCallError`] as it travels: only variants every peer decodes.
#[derive(Serialize, Deserialize)]
#[serde(rename = "ActionCallError")]
enum WireActionCallError {
    Unavailable { reason: String },
    UnknownAction,
    NotPermitted,
    ConfirmationRequired(Box<asked::AskedFacts>),
    InvalidRequest { reason: String },
    UnknownInvocation,
    InvocationConflict,
    NotCancellable { reason: String },
    Refused { reason: String },
    NotReady,
    Unanswered,
}

impl From<ActionCallError> for WireActionCallError {
    fn from(error: ActionCallError) -> Self {
        match error {
            ActionCallError::Unavailable { reason } => Self::Unavailable { reason },
            ActionCallError::UnknownAction => Self::UnknownAction,
            ActionCallError::NotPermitted => Self::NotPermitted,
            ActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
            ActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
            ActionCallError::StaleRevision => Self::InvalidRequest {
                reason: STALE_REVISION_REASON.to_owned(),
            },
            ActionCallError::UnknownInvocation => Self::UnknownInvocation,
            ActionCallError::InvocationConflict => Self::InvocationConflict,
            ActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
            ActionCallError::Refused { reason } => Self::Refused { reason },
            ActionCallError::NotReady => Self::NotReady,
            ActionCallError::Unanswered => Self::Unanswered,
        }
    }
}

impl From<WireActionCallError> for ActionCallError {
    fn from(error: WireActionCallError) -> Self {
        match error {
            WireActionCallError::InvalidRequest { reason } if reason == STALE_REVISION_REASON => {
                Self::StaleRevision
            }
            WireActionCallError::Unavailable { reason } => Self::Unavailable { reason },
            WireActionCallError::UnknownAction => Self::UnknownAction,
            WireActionCallError::NotPermitted => Self::NotPermitted,
            WireActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
            WireActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
            WireActionCallError::UnknownInvocation => Self::UnknownInvocation,
            WireActionCallError::InvocationConflict => Self::InvocationConflict,
            WireActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
            WireActionCallError::Refused { reason } => Self::Refused { reason },
            WireActionCallError::NotReady => Self::NotReady,
            WireActionCallError::Unanswered => Self::Unanswered,
        }
    }
}

/// What `provider` says of `invocation`, read off the runtime's worker when one drives the
/// caller. A provider that asks a device waits for the runtime to carry its answer, and a wait on
/// a worker stops that task: enough callers waiting at once deadlock until each deadline.
#[cfg_attr(
    any(target_arch = "wasm32", not(feature = "off-worker")),
    expect(
        clippy::unused_async,
        reason = "only a host with `off-worker` runs a runtime whose worker there is to leave"
    )
)]
pub async fn observed_off_the_worker<P>(
    provider: P,
    caller: Caller,
    invocation: InvocationId,
) -> Option<InvocationState>
where
    P: ActionProvider + Send + 'static,
{
    #[cfg(all(not(target_arch = "wasm32"), feature = "off-worker"))]
    if tokio::runtime::Handle::try_current().is_ok() {
        return tokio::task::spawn_blocking(move || provider.observe(&caller, &invocation))
            .await
            .ok()
            .flatten();
    }
    provider.observe(&caller, &invocation)
}

/// A tool call an agent's session runs, as the host keeps it
/// ([`ActionProvider::tool_started`]): the invocation its person reads while the
/// call runs and may stop. The session holds it around the tool's own work and
/// tells the host how that ended.
pub struct RunningTool {
    /// Resolves when the person stops the call.
    pub stopped: Pending<Result<(), ActionCallError>>,
    /// The stop their record noted, read by a session whose call answered before it saw
    /// `stopped`: a call the person stopped ends cancelled all the same.
    stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
    end: Option<Box<dyn FnOnce(bool) + Send + Sync>>,
}

impl RunningTool {
    /// A tool call whose `stopped` resolves when its person stops it, `stop_noted` says
    /// whether the stop reached its record, and `end` the host runs once the call ended,
    /// `true` where it was stopped.
    #[must_use]
    pub fn new(
        stopped: Pending<Result<(), ActionCallError>>,
        stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
        end: impl FnOnce(bool) + Send + Sync + 'static,
    ) -> Self {
        Self {
            stopped,
            stop_noted,
            end: Some(Box::new(end)),
        }
    }

    /// Whether its person's stop reached its record.
    #[must_use]
    pub fn was_stopped(&self) -> bool {
        self.stop_noted.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Note that the call ended: run to its end, or stopped by its person.
    pub fn ended(mut self, stopped: bool) {
        if let Some(end) = self.end.take() {
            end(stopped);
        }
    }
}

impl Drop for RunningTool {
    /// A call nobody waited for any more (its client disconnected) ended unwatched: its record
    /// says so rather than staying running forever.
    fn drop(&mut self) {
        if let Some(end) = self.end.take() {
            end(false);
        }
    }
}

/// A peer that runs actions on behalf of authenticated remote callers.
///
/// Implementations resolve authority from `caller` alone and must be
/// idempotent per [`InvocationId`]: invoking an id again with the same
/// request reports the original invocation, with a different request fails
/// with [`ActionCallError::InvocationConflict`]. [`InvocationLog`]
/// implements that rule.
pub trait ActionProvider {
    /// End this admitted transport run without cancelling its app jobs.
    fn retire_execution(&self, caller: &Caller) {
        caller.retire_execution();
    }

    /// Whether this provider answers the actions published under `provider`, the name a request
    /// targets. A device's dispatcher answers its workspace's own, and a provider a device's
    /// action service serves beside it (`ActionService::add_provider`) answers the one it names,
    /// so one request reaches the provider it was meant for.
    fn serves(&self, provider: &str) -> bool {
        let _ = provider;
        false
    }

    /// The resources this provider publishes under fixed addresses, with every action it
    /// answers on them: what a device registers with it, so a call naming one of those
    /// addresses reaches it whichever app the caller named, and what another language compiles
    /// its calls against ([`ProvidedPackage`]). Empty for a provider whose resources are
    /// found only by querying it.
    fn published(&self) -> Vec<crate::ResourceSpec> {
        Vec::new()
    }

    /// One page of what `caller` is offered. An action the caller may not
    /// invoke is absent, not flagged.
    fn query(
        &self,
        caller: &Caller,
        query: CatalogueQuery,
    ) -> Pending<Result<CataloguePage, ActionCallError>>;

    /// Admit and start one invocation, or report the one already admitted
    /// under the same id. Never blocks: the answer is the admission (an
    /// accepted receipt, an immediate outcome, or a refusal) once the provider
    /// has it; completion is followed with [`Self::observe`].
    fn invoke(
        &self,
        caller: &Caller,
        request: InvokeRequest,
    ) -> Pending<Result<InvocationReceipt, ActionCallError>>;

    /// `caller`'s session starts the tool call `tool` under `id`: what a host that
    /// records its invocations keeps as one of the agent's, so the person reads it
    /// while it runs and may stop it. The session holds the answer around the
    /// tool's own work. `None` for a host that keeps no such record, or none for
    /// this caller.
    fn tool_started(&self, caller: &Caller, id: &InvocationId, tool: &str) -> Option<RunningTool> {
        let _ = (caller, id, tool);
        None
    }

    /// The latest state of an invocation `caller` started, or `None` for an
    /// id this caller does not own.
    fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState>;

    /// The state [`Self::observe`] answered for `id` was read for `caller`'s call, on the
    /// caller's own thread: what a provider that counts the looks a tool makes of it keeps here.
    fn observed(&self, caller: &Caller, id: &InvocationId, state: Option<&InvocationState>) {
        let _ = (caller, id, state);
    }

    /// Resolves the next time invocation `id` (owned by `caller`) may have
    /// changed state, so a waiter observes it again then instead of on a
    /// timer. `None` when this provider cannot tell; the caller then observes on
    /// its own schedule.
    ///
    /// Wakeups may be spurious: the waiter must [`observe`](Self::observe)
    /// again and tolerate finding nothing new. A provider that answers `Some`
    /// must resolve it within a bounded interval even when nothing changes
    /// (the broker's is a second), so a change it failed to signal costs
    /// latency, never a stalled waiter: a waiting answer ([`settle_with`])
    /// checks its deadline only when woken.
    fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
        let _ = (caller, id);
        None
    }

    /// Where `caller`'s workspace and this device's writes stand on the session that serves
    /// it; `None` for a provider that serves from no session.
    fn session_state(&self, caller: &Caller) -> Option<SessionState> {
        let _ = caller;
        None
    }

    /// Resolves the next time [`Self::session_state`] changed, so a waiter reads it again then
    /// instead of on a timer; `None` when this provider cannot tell. It may never resolve when
    /// nothing changes: a waiter bounds its own wait.
    fn session_state_changed(&self, caller: &Caller) -> Option<Pending<()>> {
        let _ = caller;
        None
    }

    /// Resolves the next time what a watch of the workspace follows under `scope` may have
    /// changed, so a waiter reads it again then instead of on a timer; `None` when this provider
    /// cannot tell, and the waiter then waits until its own deadline.
    ///
    /// Wakeups may be spurious: the waiter reads again and tolerates finding nothing new. A provider
    /// that answers `Some` must resolve it within a bounded interval even when nothing changes,
    /// so a change it failed to signal costs latency rather than a stalled waiter. A wait the
    /// provider finds it cannot follow after all (the device it asks refuses it, or cannot be
    /// asked) resolves at once with why: the waiter is told, never left to its deadline.
    fn changed(
        &self,
        caller: &Caller,
        scope: WatchScope,
    ) -> Option<Pending<Result<(), ActionCallError>>> {
        let _ = (caller, scope);
        None
    }

    /// Ask a running invocation to stop, answered once the provider has kept
    /// the request as durably as it keeps the invocation.
    ///
    /// # Errors
    ///
    /// Returns [`ActionCallError::UnknownInvocation`] for an id this caller
    /// does not own, or [`ActionCallError::NotCancellable`].
    fn cancel(&self, caller: &Caller, id: &InvocationId) -> Pending<Result<(), ActionCallError>>;

    /// Where this provider's callers put content into their workspace's content
    /// store ([`ContentPuts`]); `None` for a provider without one.
    fn content_puts(&self) -> Option<std::sync::Arc<dyn ContentPuts>> {
        None
    }

    /// Where this provider's callers put content the action `target` names reads: an action of
    /// the caller's own device keeps what it reads there, and its provider says so with a store
    /// of its own. Everything else a put is for reads the store [`Self::content_puts`] names,
    /// which is what a provider that keeps no store of its own answers.
    fn content_puts_for(
        &self,
        target: Option<&RemoteActionTarget>,
    ) -> Option<std::sync::Arc<dyn ContentPuts>> {
        let _ = target;
        self.content_puts()
    }

    /// Where this provider's callers read content back out of their workspace's
    /// content store ([`ContentGets`]); `None` for a provider without one.
    fn content_gets(&self) -> Option<std::sync::Arc<dyn ContentGets>> {
        None
    }

    /// The client of a connection this provider admits named itself `client` in its
    /// `initialize` (its product's name, `Claude Code`): a host that keeps the workspace's agents
    /// answers what that names from then on, and a host that names its own connections has
    /// nothing to do here.
    fn introduced(&self, caller: &Caller, client: &str) {
        let _ = (caller, client);
    }

    /// Who is in the workspace now, as this provider's collaboration knows it:
    /// its people and the agents its roster names. `None` for a provider that
    /// keeps no roster, which reports no presence rather than an empty one.
    fn here(&self, caller: &Caller) -> Option<Vec<Here>> {
        let _ = caller;
        None
    }

    /// Where an agent task reads its workspace's records outside their apps ([`ResourceReads`]);
    /// `None` for a provider without them. The resources a provider publishes itself (a desktop's
    /// device, its windows, its styles, Settings' sections) are read on the same API, as a
    /// [`ResourceCopy::Reading`], so a program and the shell's parts read one resource one way.
    fn resource_reads(&self) -> Option<std::sync::Arc<dyn ResourceReads>> {
        None
    }

    /// Where the process this provider serves reads and writes its app's records
    /// ([`StoreCommands`]): an app's own connection to its device. `None` for every other
    /// provider.
    fn store_commands(&self) -> Option<std::sync::Arc<dyn StoreCommands>> {
        None
    }

    /// Every change to the records of a caller's workspace, as this provider
    /// keeps them ([`ChangeFeed`]): what a watch of the whole workspace
    /// reads. `None` for a provider that keeps no records.
    fn change_feed(&self) -> Option<std::sync::Arc<dyn ChangeFeed>> {
        None
    }

    /// The surface the signed package `app_id` the workspace installed
    /// publishes, running or not: what an agent reads its types from, and a
    /// change of its records is decided against, before the app opens.
    fn installed_surface(&self, app_id: &str) -> Pending<Option<Vec<u8>>> {
        let _ = app_id;
        Pending::ready(None)
    }

    /// The action at `address` as one invocation with `argument` (its slot form) is: `None` for the
    /// action as this provider's catalogue describes it. A provider whose action is riskier for
    /// some values than others (a setting that weakens the person's security) answers it as that
    /// value makes it, so the dispatch asks the person first.
    fn invocation(
        &self,
        address: &crate::ActionAddress,
        argument: Option<&str>,
    ) -> Option<crate::api::ActionDescriptor> {
        let _ = (address, argument);
        None
    }

    /// Carry out `request`, which this device's dispatch admitted for `caller`, with what the
    /// dispatch knows of the call ([`Admitted`]). By default it is [`Self::invoke`]d.
    fn run(
        &self,
        caller: &Caller,
        request: InvokeRequest,
        admitted: Admitted,
    ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
        let _ = admitted;
        self.invoke(caller, request)
    }

    /// Before the dispatch takes `request`, a call nobody approved yet: whether it waits for its
    /// person's yes ([`asked::approved_or_asks`]), where this provider knows that only by looking
    /// at the call itself (a program, by running it provisionally). The dispatch takes the call
    /// once this answers `Ok`, and keeps one refused for want of the yes as its asked record, which
    /// an approve sends here again, carrying [`InvokeRequest::approval`]. `admitted` is what the
    /// dispatch knows of the call. `None` for a provider that decides nothing before it runs.
    fn asks_first(
        &self,
        caller: &Caller,
        request: &InvokeRequest,
        admitted: &Admitted,
    ) -> Option<Pending<Result<(), ActionCallError>>> {
        let _ = (caller, request, admitted);
        None
    }

    /// Follow `request`, an admitted call of an action whose contract is
    /// [`ExecutionMode::Live`](crate::ExecutionMode::Live): how to read its result as it is now,
    /// and when that may have changed.
    ///
    /// # Errors
    ///
    /// The action has no live result here, or `caller` may not follow it.
    fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
        let _ = (caller, request);
        Err("this action has no live result".into())
    }
}

/// Whether `value` is the zero an asker that names no ask uses: left out of
/// the bytes, as it always was.
#[allow(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde hands a skipped field to it by reference"
)]
const fn is_zero(value: &u64) -> bool {
    *value == 0
}

/// An answer to an [`RemoteActionMessage::Observe`], naming the ask it answers.
fn updated(
    correlation: u64,
    invocation: InvocationId,
    state: Option<InvocationState>,
) -> RemoteActionMessage {
    RemoteActionMessage::Update {
        invocation,
        state,
        correlation: Some(correlation),
    }
}

/// Everything that crosses the wire for remote action use.
#[allow(
    clippy::large_enum_variant,
    reason = "a message is built, encoded once and dropped; boxing would only add noise to every constructor and match"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RemoteActionMessage {
    /// A retired ask for a feedback report's receipt: nothing answers it but
    /// [`Self::RetiredFeedbackResponse`]. A report is filed as Chat's
    /// `report`, answered as any action is.
    RetiredFeedbackRequest { correlation: u64 },
    /// The answer to a [`Self::RetiredFeedbackRequest`], refusing it.
    RetiredFeedbackResponse { correlation: u64 },
    /// Ask for one page of the actions offered to the caller.
    CatalogueRequest {
        correlation: u64,
        #[serde(default)]
        query: CatalogueQuery,
    },
    /// Answer to a [`Self::CatalogueRequest`] with the same correlation.
    CatalogueResponse {
        correlation: u64,
        result: Result<CataloguePage, ActionCallError>,
    },
    /// Invocation one action.
    Invoke(InvokeRequest),
    /// Answer to [`Self::Invoke`]; a refusal is [`ReceiptStatus::Rejected`].
    Receipt(InvocationReceipt),
    /// Ask for an invocation's latest state.
    Observe {
        /// Names this ask, so its [`Self::Update`] answers it and no other: a
        /// caller that gave up on one ask and sent another must not mistake
        /// the first one's late answer — which may carry the state it already
        /// saw — for its own. An asker that names none keeps the bytes it
        /// always sent.
        #[serde(default, skip_serializing_if = "is_zero")]
        correlation: u64,
        invocation: InvocationId,
        /// Hold the answer until the invocation moves past `seen` (or, with
        /// no `seen`, settles) or this many milliseconds pass, at most
        /// [`MAX_REMOTE_WAIT`]; then answer with the state as it is. A provider
        /// that predates it answers at once, as before.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        wait_ms: Option<u32>,
        /// How far the caller has already seen the invocation get.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        seen: Option<UpdateMark>,
    },
    /// Answer to [`Self::Observe`]; `None` for an id the caller does not own.
    /// A provider may also push this unprompted as an invocation progresses.
    Update {
        invocation: InvocationId,
        state: Option<InvocationState>,
        /// The ask this answers, as it named itself; absent for a push, and
        /// for a provider that predates named asks.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        correlation: Option<u64>,
    },
    /// Ask a running invocation to stop.
    Cancel { invocation: InvocationId },
    /// Answer to [`Self::Cancel`].
    CancelResponse {
        invocation: InvocationId,
        result: Result<(), ActionCallError>,
    },
    /// Ask the person, on one of their own devices ([`ConfirmationQuestion`]).
    ConfirmationRequest {
        correlation: u64,
        question: ConfirmationQuestion,
    },
    /// Answer to [`Self::ConfirmationRequest`], same correlation.
    ConfirmationResponse {
        correlation: u64,
        result: Result<ConfirmationReply, ActionCallError>,
    },
    /// What the surface offers changed: the page it lists now, sent without
    /// being asked, so the provider that placed it reads what the surface can do
    /// as it is rather than as it was when it first joined.
    CatalogueChanged { page: CataloguePage },
    /// One step of putting bytes into the content store of the device's
    /// workspace ([`ContentPutStep`]): how a client of another device's
    /// actions (an agent's MCP session through its own device) hands it a
    /// file an action then names by `tilo.content:<hash>`.
    ContentPutRequest {
        correlation: u64,
        step: ContentPutStep,
    },
    /// Answer to [`Self::ContentPutRequest`] with the same correlation.
    ContentPutResponse {
        correlation: u64,
        result: Result<ContentPutAnswer, ActionCallError>,
    },
    /// Ask the device for a piece of content in its workspace's store: what a
    /// client of another device's actions (an agent's MCP session through its
    /// own device) downloads a file by, having the file's
    /// `tilo.content:<hash>` reference.
    ContentGetRequest {
        correlation: u64,
        /// The content's reference, `tilo.content:<hash>`.
        content: String,
        /// Where in the content the piece starts.
        offset: u64,
        /// How many bytes the piece may carry; zero asks for one piece's
        /// worth ([`MAX_CONTENT_FRAME_BYTES`]).
        length: u64,
    },
    /// Answer to [`Self::ContentGetRequest`] with the same correlation.
    ContentGetResponse {
        correlation: u64,
        result: Result<ContentGetAnswer, ActionCallError>,
    },
    /// Read a record of the workspace `read` names through the one record API
    /// ([`ResourceReads`]), decided there as every reader of it is; continuing
    /// `on_behalf_of`, an invocation the provider delivered to the caller, it is
    /// that invocation's caller's read. Where its answer is a decision
    /// ([`ReadAnswer::Decision`], [`ReadAnswer::WriteDecision`]), it asks only whether the caller
    /// may read or change the record.
    ResourceRead {
        correlation: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        on_behalf_of: Option<InvocationId>,
        read: ResourceReadRequest,
    },
    /// Answer to [`Self::ResourceRead`], same correlation: the readings as
    /// JSON text (`ResourceReadings::readable`).
    ResourceReading {
        correlation: u64,
        result: Result<String, ActionCallError>,
    },
    /// Ask for the changes to the caller's workspace's records after
    /// `after`, a cursor an earlier answer gave ([`ActionProvider::change_feed`]).
    ChangesRequest {
        correlation: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        after: Option<String>,
    },
    /// Answer to [`Self::ChangesRequest`], same correlation.
    ChangesResponse {
        correlation: u64,
        result: Result<ChangePage, ActionCallError>,
    },
    /// Ask for the surface `app`'s signed package publishes, as its text.
    SurfaceRequest { correlation: u64, app: String },
    /// Answer to [`Self::SurfaceRequest`]: the text, when the workspace has it.
    SurfaceResponse {
        correlation: u64,
        result: Result<Option<String>, ActionCallError>,
    },
    /// Ask the device for a link its web origin serves the content of
    /// `link.files` at, for a little while ([`ContentLink`]): what a page
    /// drags a file out by, and saves a large one through.
    ContentLinkRequest {
        correlation: u64,
        link: ContentLinkAsk,
    },
    /// Answer to [`Self::ContentLinkRequest`] with the same correlation.
    ContentLinkResponse {
        correlation: u64,
        result: Result<ContentLink, ActionCallError>,
    },
    /// Ask the device to answer when what a watch follows under `scope` may have
    /// changed ([`ActionProvider::changed`]): a write landed in the workspace's records,
    /// or who is in it moved.
    ChangedRequest { correlation: u64, scope: WatchScope },
    /// Answer to [`Self::ChangedRequest`], same correlation: it may have changed, or
    /// why this provider cannot tell when it does.
    ChangedResponse {
        correlation: u64,
        result: Result<(), ActionCallError>,
    },
    /// Ask the device to carry an outside service's call into a workspace call from now on, or,
    /// with no pair, to let go of the one it carries ([`call`]). Decided by the app's grants and
    /// held to the call's rule; a device that carries no call for this app refuses.
    CallCarryRequest {
        correlation: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pair: Option<call::BridgedCall>,
    },
    /// Answer to [`Self::CallCarryRequest`], same correlation.
    CallCarryResponse {
        correlation: u64,
        result: Result<(), ActionCallError>,
    },
    /// What the app's service says of its calls: who is in each, where the bridge stands, and
    /// the line its people see.
    CallReport {
        correlation: u64,
        report: call::CallReport,
    },
    /// Answer to [`Self::CallReport`], same correlation.
    CallReportResponse {
        correlation: u64,
        result: Result<(), ActionCallError>,
    },
    /// One Opus frame an outside person said, for the workspace call.
    CallHeard(call::CallAudio),
    /// One Opus frame a workspace participant said, for the outside call. Sent by the device,
    /// never asked for.
    CallSaid(call::CallAudio),
    /// What the device says the outside call should show of who is on the workspace's side.
    /// Sent by the device, never asked for.
    CallStatus(call::CallStatus),
    /// One command for the device's sound output, on the line an app's launcher handed it. A
    /// write's PCM follows the frame as its binary body ([`audio_output::Request::body_len`]).
    AudioOutputRequest {
        correlation: u64,
        command: audio_output::Request,
    },
    /// Answer to [`Self::AudioOutputRequest`], same correlation.
    AudioOutputResponse {
        correlation: u64,
        result: Result<audio_output::Snapshot, ActionCallError>,
    },
    /// One command to the records of the app the connection is, in the device's one store
    /// ([`StoreCommands`]): `collab_types::store::wire::Command` as JSON. What an app's process
    /// reads and writes its records by. The app is the one the device started the connection's
    /// process as, never one the frame names, and the workspace is the frame's
    /// ([`RemoteActionFrame::workspace`]).
    StoreRequest {
        correlation: u64,
        command: serde_json::Value,
        /// The kind a record the command founds is of, as the app names it; a record of a kind
        /// its manifest does not declare is not founded.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        kind: Option<String>,
    },
    /// Answer to [`Self::StoreRequest`], same correlation: the store's
    /// `collab_types::store::wire::Reply` as JSON.
    StoreResponse {
        correlation: u64,
        result: Result<serde_json::Value, ActionCallError>,
    },
    /// One command of the call the app takes part in itself, on the line its launcher handed it
    /// ([`native_media::Request`]): joining a workspace's call, muting, the camera and screen it
    /// sends, which pictures its view draws, and the status it shows.
    CallMediaRequest {
        correlation: u64,
        request: native_media::Request,
    },
    /// Answer to [`Self::CallMediaRequest`], same correlation.
    CallMediaResult {
        correlation: u64,
        result: Result<native_media::Snapshot, ActionCallError>,
    },
    /// What an app says of its person in its workspace, on the line its launcher handed it: one
    /// word under the key it is said under, as `collab_types::presence::Said` JSON. The device
    /// says it for the connection's app, workspace and member in the workspace's live session,
    /// where the shell's own words go, so every other device of the workspace hears it.
    PresenceSaid { correlation: u64, said: String },
    /// Answer to [`Self::PresenceSaid`], same correlation: whether the device's live presence
    /// said the word, and why it refused it when it did not.
    PresenceSaidResult {
        correlation: u64,
        result: Result<(), ActionCallError>,
    },
    /// What another member said in the app's workspace, as the workspace's live session heard
    /// it from another device: one `collab_types::presence::Heard` as JSON, pushed, never asked.
    PresenceHeard { heard: String },
    /// Ask the device to open a shell its shell runtime runs, carried on this connection from
    /// now on ([`shell`]). Decided by the app's signed manifest; a connection that is no app's
    /// own carries no shell.
    ShellOpenRequest {
        correlation: u64,
        open: shell::ShellOpen,
    },
    /// Answer to [`Self::ShellOpenRequest`], same correlation.
    ShellOpenResponse {
        correlation: u64,
        result: Result<shell::ShellOpened, ActionCallError>,
    },
    /// What the app typed into one of its shells.
    ShellInput(shell::ShellBytes),
    /// One of the app's shells' windows is now this size, in cells.
    ShellResize { shell: u64, cols: u16, rows: u16 },
    /// The app lets one of its shells go.
    ShellClose { shell: u64 },
    /// What one of the app's shells printed. Sent by the device, never asked for.
    ShellOutput(shell::ShellBytes),
    /// How one of the app's shells ended: the last the device says of it. Sent by the device,
    /// never asked for.
    ShellEnded(shell::ShellEnded),
}

/// One record a reader asks for over the action API: alone, or `joined`
/// as the chain of parts whose base it is, once it differs from the revision
/// `after` or `wait_ms` passed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceReadRequest {
    /// The workspace the record is in: part of its address, so a read is decided at that
    /// workspace's record node, never by which workspace the connection was admitted to.
    pub workspace: String,
    /// The app whose record it is.
    pub app: String,
    /// Its id there; empty for the app's record of the workspace.
    pub record: String,
    #[serde(default)]
    pub joined: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// How long to wait for a write past `after`, at most [`MAX_REMOTE_WAIT`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait_ms: Option<u32>,
    /// What the read answers: the record as every reader reads it, or one of the other answers
    /// [`ReadAnswer`] names.
    #[serde(default, skip_serializing_if = "ReadAnswer::is_reading")]
    pub answer: ReadAnswer,
}

/// What a [`ResourceReadRequest`] is answered with.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReadAnswer {
    /// Each resource as every reader reads it (`ResourceReadings::readable`).
    #[default]
    Reading,
    /// Each resource as its document, whole: what a reader that merges or hydrates the resource
    /// itself reads ([`ResourceReadings::documents`]).
    Document,
    /// The resources of the request's workspace the caller may read rather than one: its app's,
    /// or every app's where the app is empty ([`ResourceReads::list`]). Its record is not read.
    Listing,
    /// Only whether the caller may read the record now, decided as its read is, without the copy
    /// ([`ResourceReads::may_read`]): what a reader that keeps the record another way asks.
    Decision,
    /// Only whether the caller may change the record now, decided as its write is, without the
    /// change ([`ResourceReads::may_write`]): what a route asks before it changes the record.
    WriteDecision,
}

impl ReadAnswer {
    /// Whether this is the default answer, which the wire leaves out.
    #[must_use]
    pub const fn is_reading(&self) -> bool {
        matches!(self, Self::Reading)
    }
}

impl RemoteActionMessage {
    /// Ask for `invocation`'s state as it is now.
    #[must_use]
    pub const fn observe(invocation: InvocationId) -> Self {
        Self::Observe {
            correlation: 0,
            invocation,
            wait_ms: None,
            seen: None,
        }
    }

    /// Whether this request asks its provider to hold the answer until the
    /// invocation moves, a person answers, or a record is written past what its reader saw, so
    /// whatever carries it must not wait behind it, and nothing that watches for stuck calls
    /// takes the wait it asked for as one.
    #[must_use]
    pub const fn waits(&self) -> bool {
        matches!(
            self,
            Self::Observe {
                wait_ms: Some(_),
                ..
            } | Self::Invoke(InvokeRequest {
                wait_ms: Some(_),
                ..
            }) | Self::ChangedRequest { .. }
                | Self::ResourceRead {
                    read: ResourceReadRequest {
                        wait_ms: Some(_),
                        ..
                    },
                    ..
                }
        )
    }

    /// Whether a provider answers this message (as opposed to a caller
    /// receiving it).
    #[must_use]
    pub const fn is_request(&self) -> bool {
        matches!(
            self,
            Self::CatalogueRequest { .. }
                | Self::Invoke(_)
                | Self::Observe { .. }
                | Self::Cancel { .. }
                | Self::ResourceRead { .. }
                | Self::RetiredFeedbackRequest { .. }
                | Self::ConfirmationRequest { .. }
                | Self::ContentPutRequest { .. }
                | Self::ContentGetRequest { .. }
                | Self::ContentLinkRequest { .. }
                | Self::ChangesRequest { .. }
                | Self::ChangedRequest { .. }
                | Self::SurfaceRequest { .. }
                | Self::AudioOutputRequest { .. }
                | Self::StoreRequest { .. }
                | Self::CallMediaRequest { .. }
                | Self::PresenceSaid { .. }
        )
    }
}

/// The refusal of a request [`serve`] keeps nothing for: a retired feedback
/// ask; uploads over a session, kept by a
/// provider that keeps them open between steps ([`HostedContentPuts`]); and
/// content, read from a store a device keeps. `None` for any other message.
fn not_kept(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
    let reason = match message {
        RemoteActionMessage::RetiredFeedbackRequest { .. } => "feedback receipts are retired",
        RemoteActionMessage::ContentPutRequest { .. } => CONTENT_PUTS_UNAVAILABLE,
        RemoteActionMessage::ContentGetRequest { .. } => CONTENT_GETS_UNAVAILABLE,
        RemoteActionMessage::ContentLinkRequest { .. } => CONTENT_LINKS_UNAVAILABLE,
        _ => return None,
    };
    refuse(
        message,
        ActionCallError::Unavailable {
            reason: reason.into(),
        },
    )
}

/// `command` to the records of `caller`'s app, answered by `provider`'s store
/// ([`ActionProvider::store_commands`]) for `correlation`.
fn store_answered<H: ActionProvider>(
    provider: &H,
    caller: &Caller,
    correlation: u64,
    (command, kind): (serde_json::Value, Option<String>),
) -> Pending<RemoteActionMessage> {
    let result = match provider.store_commands() {
        Some(store) => store.command(caller, command, kind),
        None => Pending::ready(Err(ActionCallError::Unavailable {
            reason: STORE_COMMANDS_UNAVAILABLE.into(),
        })),
    };
    result.map(move |result| RemoteActionMessage::StoreResponse {
        correlation,
        result,
    })
}

/// The changes to `caller`'s workspace's records after `after`, from
/// `provider`'s feed, answered for `correlation` ([`ActionProvider::change_feed`]).
fn changed<H: ActionProvider>(
    provider: &H,
    caller: &Caller,
    correlation: u64,
    after: Option<&str>,
) -> Pending<RemoteActionMessage> {
    let result = match provider.change_feed() {
        Some(feed) => feed.since(caller, after),
        None => Pending::ready(Err(ActionCallError::Unavailable {
            reason: CHANGE_FEED_UNAVAILABLE.into(),
        })),
    };
    result.map(move |result| RemoteActionMessage::ChangesResponse {
        correlation,
        result,
    })
}

/// A versioned [`RemoteActionMessage`], the unit a transport carries.
///
/// The encoding is self-describing JSON: action arguments and outputs are
/// open JSON values, and a server forwarding the bytes need not understand
/// them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RemoteActionFrame {
    pub version: u16,
    pub message: RemoteActionMessage,
    /// The workspace the request is asked in, on a transport that serves every workspace its
    /// device holds (the daemon's native endpoint), as a shell link's call names its own: none
    /// asks in the device's own. A read names its workspace in its address instead
    /// ([`Self::workspace`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// The input serial the person's press that ran this request travelled with, as the
    /// compositor issued it to the window the app's connection is: what a host checks to admit
    /// the request as the person, once. Only an app whose window received the press can name
    /// it: a synthetic or replayed serial proves nothing, and a request naming none followed no
    /// press. It is transport, never part of the invocation's identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub press: Option<u32>,
    /// Where in the window the control that press answered stands, as the window says of a key
    /// press ([`press_points`]): what the person's question stands at when the compositor's
    /// record of the press has no point. Like `press`, transport only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub press_at: Option<asked::PressPoint>,
}

/// Why bytes are not a usable [`RemoteActionFrame`].
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum RemoteFrameError {
    #[error("remote action frame of {len} bytes exceeds the limit")]
    TooLarge { len: usize },
    #[error("remote action frame version {version} is not supported")]
    UnsupportedVersion { version: u16 },
    #[error("malformed remote action frame: {0}")]
    Malformed(String),
}

impl RemoteActionFrame {
    /// Wrap `message` at this build's [`REMOTE_ACTIONS_VERSION`].
    #[must_use]
    pub const fn new(message: RemoteActionMessage) -> Self {
        Self {
            version: REMOTE_ACTIONS_VERSION,
            message,
            workspace: None,
            press: None,
            press_at: None,
        }
    }

    /// The same request, asked by the person's press the compositor issued `serial` with, and
    /// carrying where the control it answered stands when its window said.
    #[must_use]
    pub fn pressed(mut self, press: Option<u32>) -> Self {
        self.press = press;
        self.press_at = press.and_then(press_points::of);
        self
    }

    /// The same request, asked in `workspace` (none: the device's own).
    #[must_use]
    pub fn in_workspace(mut self, workspace: Option<String>) -> Self {
        self.workspace = workspace;
        self
    }

    /// The workspace the request is asked in: the one a read's address names, else the one the
    /// frame names; `None` for the device's own.
    #[must_use]
    pub fn workspace(&self) -> Option<&str> {
        match &self.message {
            RemoteActionMessage::ResourceRead { read, .. } => Some(&read.workspace),
            _ => self.workspace.as_deref(),
        }
    }

    /// Encode for a transport.
    ///
    /// # Errors
    ///
    /// Returns [`RemoteFrameError::TooLarge`] past
    /// [`MAX_REMOTE_ACTION_FRAME_BYTES`], or `Malformed` if a value cannot
    /// be encoded.
    pub fn encode(&self) -> Result<Vec<u8>, RemoteFrameError> {
        let bytes = serde_json::to_vec(self)
            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
        if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
            return Err(RemoteFrameError::TooLarge { len: bytes.len() });
        }
        Ok(bytes)
    }

    /// Decode bytes from a transport. The version is checked before the
    /// message, so a frame from a newer peer is refused by version rather
    /// than misread.
    pub fn decode(bytes: &[u8]) -> Result<Self, RemoteFrameError> {
        #[derive(Deserialize)]
        struct Version {
            version: u16,
        }
        if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
            return Err(RemoteFrameError::TooLarge { len: bytes.len() });
        }
        let Version { version } = serde_json::from_slice(bytes)
            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
        if version != REMOTE_ACTIONS_VERSION {
            return Err(RemoteFrameError::UnsupportedVersion { version });
        }
        serde_json::from_slice(bytes)
            .map_err(|error| RemoteFrameError::Malformed(error.to_string()))
    }
}

/// A resource read, answered by the provider's own reader through its trait object: what a
/// reading is made of loads with the code that reads records, not with every provider's API.
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
fn read_answered<H: ActionProvider>(
    provider: &H,
    caller: &Caller,
    correlation: u64,
    read: ResourceReadRequest,
) -> Pending<RemoteActionMessage> {
    provider.resource_reads().map_or_else(
        || resource_read::unanswered(correlation),
        |reads| resource_read::answered_where_it_ends(reads.answer_read(caller, correlation, read)),
    )
}

/// A build with no runtime to answer on (a model module, or one that reads no records) answers
/// every posted read as a provider that reads no records does.
#[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
fn read_answered<H: ActionProvider>(
    _provider: &H,
    _caller: &Caller,
    correlation: u64,
    _read: ResourceReadRequest,
) -> Pending<RemoteActionMessage> {
    resource_read::unanswered(correlation)
}

/// A call media lane is its own host's, never a provider's: one asked here says it carries none.
fn no_call_media_lane() -> ActionCallError {
    ActionCallError::Unavailable {
        reason: "this connection carries no call media lane".into(),
    }
}

/// The answer to a shell asked of a provider's connection, which carries none: a shell is the
/// device's own, on an app's connection.
fn no_shell(correlation: u64) -> RemoteActionMessage {
    RemoteActionMessage::ShellOpenResponse {
        correlation,
        result: Err(ActionCallError::Unavailable {
            reason: "this connection carries no shell".into(),
        }),
    }
}

/// A presence lane is its own host's, never a provider's: one asked here says it carries none.
fn no_presence_lane() -> ActionCallError {
    ActionCallError::Unavailable {
        reason: "this connection carries no presence lane".into(),
    }
}

/// A sound output lane is its own host's, never a provider's: one asked here says it carries none.
fn no_audio_output_lane() -> ActionCallError {
    ActionCallError::Unavailable {
        reason: "this connection carries no sound output lane".into(),
    }
}

/// A call lane is its own host's, never a provider's: one asked here says it carries none.
fn no_call_lane() -> ActionCallError {
    ActionCallError::Unavailable {
        reason: "this connection carries no call lane".into(),
    }
}

/// Answer one request from `caller` against `provider`.
///
/// Returns `None` for a message that is not a request (a response arriving
/// at a provider is dropped, never answered). A refused invocation becomes a
/// [`ReceiptStatus::Rejected`] receipt so the caller always learns the fate
/// of the id it chose; an answer the provider abandons becomes a refusal too.
///
/// A request that asks to wait (`wait_ms` on [`RemoteActionMessage::Observe`]
/// or [`InvokeRequest`]) is answered once the invocation moves, through
/// [`ActionProvider::next_change`] and without holding a thread; see
/// [`settle_with`]. A provider that cannot signal changes answers at once.
pub fn serve<H: ActionProvider + Clone + Send + 'static>(
    provider: &H,
    caller: &Caller,
    message: RemoteActionMessage,
) -> Option<Pending<RemoteActionMessage>> {
    let abandoned = refuse(
        &message,
        ActionCallError::Unavailable {
            reason: "the provider dropped the request".into(),
        },
    )?;
    if let Some(answer) = unprovided(&message) {
        return Some(Pending::ready(answer));
    }
    let answer = match message {
        RemoteActionMessage::CatalogueRequest { correlation, query } => provider
            .query(caller, query)
            .map(move |result| RemoteActionMessage::CatalogueResponse {
                correlation,
                result,
            }),
        RemoteActionMessage::Invoke(request) => {
            invoked(provider, caller, request).map(RemoteActionMessage::Receipt)
        }
        RemoteActionMessage::Observe {
            correlation,
            invocation,
            wait_ms: Some(wait_ms),
            seen,
        } => settle_with(provider, caller, invocation, seen, wait::deadline(wait_ms))
            .map(move |state| updated(correlation, invocation, state)),
        RemoteActionMessage::Observe {
            correlation,
            invocation,
            ..
        } => Pending::ready(updated(
            correlation,
            invocation,
            provider.observe(caller, &invocation),
        )),
        RemoteActionMessage::Cancel { invocation } => provider
            .cancel(caller, &invocation)
            .map(move |result| RemoteActionMessage::CancelResponse { invocation, result }),
        // Read by a provider's own reader, which answers through its trait object: what a reading is
        // made of loads with the code that reads records, not with every provider's API.
        RemoteActionMessage::ResourceRead {
            correlation, read, ..
        } => read_answered(provider, caller, correlation, read),
        RemoteActionMessage::ChangesRequest { correlation, after } => {
            changed(provider, caller, correlation, after.as_deref())
        }
        RemoteActionMessage::ChangedRequest { correlation, scope } => {
            watch::noticed(provider, caller, correlation, scope)
        }
        RemoteActionMessage::SurfaceRequest { correlation, app } => {
            surfaces::surfaced(provider, correlation, &app)
        }
        RemoteActionMessage::StoreRequest {
            correlation,
            command,
            kind,
        } => store_answered(provider, caller, correlation, (command, kind)),
        // An answer is never a request: `refuse` classified every message before this match and
        // answered `None` for an answer, and `unprovided` answered what no provider takes, so
        // neither reaches here.
        _ => return None,
    };
    // An abandoned answer still answers: the caller hears a refusal.
    let (completer, answered) = pending();
    answer.then(move |answer| completer.complete(answer.unwrap_or(abandoned)));
    Some(answered)
}

/// The answer to a request that no provider takes, or `None` for any other message. What a
/// stateless provider keeps none of, it refuses; a question is the person's to answer, on the
/// device they are at; and a lane (calls, sound output, call media, presence, shells) is its own
/// host's, so one asked here says it carries none.
fn unprovided(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
    Some(match *message {
        RemoteActionMessage::RetiredFeedbackRequest { .. }
        | RemoteActionMessage::ContentPutRequest { .. }
        | RemoteActionMessage::ContentGetRequest { .. }
        | RemoteActionMessage::ContentLinkRequest { .. } => not_kept(message)?,
        RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
            confirmation::unanswered(correlation, ActionCallError::confirmation_required())
        }
        RemoteActionMessage::CallCarryRequest { correlation, .. } => {
            RemoteActionMessage::CallCarryResponse {
                correlation,
                result: Err(no_call_lane()),
            }
        }
        RemoteActionMessage::CallReport { correlation, .. } => {
            RemoteActionMessage::CallReportResponse {
                correlation,
                result: Err(no_call_lane()),
            }
        }
        RemoteActionMessage::AudioOutputRequest { correlation, .. } => {
            RemoteActionMessage::AudioOutputResponse {
                correlation,
                result: Err(no_audio_output_lane()),
            }
        }
        RemoteActionMessage::CallMediaRequest { correlation, .. } => {
            RemoteActionMessage::CallMediaResult {
                correlation,
                result: Err(no_call_media_lane()),
            }
        }
        RemoteActionMessage::PresenceSaid { correlation, .. } => {
            RemoteActionMessage::PresenceSaidResult {
                correlation,
                result: Err(no_presence_lane()),
            }
        }
        RemoteActionMessage::ShellOpenRequest { correlation, .. } => no_shell(correlation),
        _ => return None,
    })
}

/// Run `request` at `provider`, answering its receipt once it is ready, or once it moves when it
/// asks to wait. How the answer travels is not part of what runs.
fn invoked<H: ActionProvider + Clone + Send + 'static>(
    provider: &H,
    caller: &Caller,
    mut request: InvokeRequest,
) -> Pending<InvocationReceipt> {
    let until = request.wait_ms.take().map(wait::deadline);
    let invocation = request.invocation;
    let receipt = provider.invoke(caller, request).map(move |result| {
        result.unwrap_or_else(|error| InvocationReceipt {
            invocation,
            status: ReceiptStatus::Rejected { error },
        })
    });
    match until {
        Some(until) => wait::settle_receipt(provider, caller, receipt, until),
        None => receipt,
    }
}

/// The answer that refuses request `message` with `error` — for a provider that
/// cannot be reached or is not running. Returns `None` for a message that
/// is not a request.
#[must_use]
pub fn refuse(
    message: &RemoteActionMessage,
    error: ActionCallError,
) -> Option<RemoteActionMessage> {
    Some(match message {
        RemoteActionMessage::RetiredFeedbackRequest { correlation } => {
            RemoteActionMessage::RetiredFeedbackResponse {
                correlation: *correlation,
            }
        }
        RemoteActionMessage::CatalogueRequest { correlation, .. } => {
            RemoteActionMessage::CatalogueResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::Invoke(request) => RemoteActionMessage::Receipt(InvocationReceipt {
            invocation: request.invocation,
            status: ReceiptStatus::Rejected { error },
        }),
        RemoteActionMessage::Observe {
            correlation,
            invocation,
            ..
        } => updated(*correlation, *invocation, None),
        RemoteActionMessage::Cancel { invocation } => RemoteActionMessage::CancelResponse {
            invocation: *invocation,
            result: Err(error),
        },
        RemoteActionMessage::ResourceRead { correlation, .. } => {
            RemoteActionMessage::ResourceReading {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
            confirmation::unanswered(*correlation, error)
        }
        RemoteActionMessage::ContentPutRequest { correlation, .. } => {
            RemoteActionMessage::ContentPutResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ContentGetRequest { correlation, .. } => {
            RemoteActionMessage::ContentGetResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ContentLinkRequest { correlation, .. } => {
            RemoteActionMessage::ContentLinkResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ChangesRequest { correlation, .. } => {
            RemoteActionMessage::ChangesResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ChangedRequest { correlation, .. } => {
            RemoteActionMessage::ChangedResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::SurfaceRequest { correlation, .. } => {
            RemoteActionMessage::SurfaceResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::StoreRequest { correlation, .. } => {
            RemoteActionMessage::StoreResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::PresenceSaid { correlation, .. } => {
            RemoteActionMessage::PresenceSaidResult {
                correlation: *correlation,
                result: Err(error),
            }
        }
        RemoteActionMessage::ShellOpenRequest { correlation, .. } => {
            RemoteActionMessage::ShellOpenResponse {
                correlation: *correlation,
                result: Err(error),
            }
        }
        // Every other message answers a request: there is nothing to refuse.
        _ => return None,
    })
}

struct LogEntry<T> {
    caller: Caller,
    request: InvokeRequest,
    /// `None` while a start begun with [`InvocationLog::reserve`] is in
    /// flight.
    handle: Option<T>,
}

/// The idempotency log behind [`ActionProvider::invoke`].
///
/// Maps each admitted [`InvocationId`] to the caller and request that
/// admitted it and to the provider's own handle for the running job. A retry
/// with the same caller and request returns the existing handle without
/// starting anything; any other reuse of the id is a conflict. Only admitted
/// invocations are remembered — a refused one ran nothing, so retrying it
/// may be admitted later. At `capacity`, the oldest entry whose admission
/// completed is forgotten. In-flight reservations are never evicted.
pub struct InvocationLog<T> {
    entries: HashMap<InvocationId, LogEntry<T>>,
    order: VecDeque<InvocationId>,
    capacity: usize,
}

impl<T> Default for InvocationLog<T> {
    fn default() -> Self {
        Self::with_capacity(DEFAULT_LOG_CAPACITY)
    }
}

/// What [`InvocationLog::reserve`] found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reservation {
    /// The id is newly claimed; the caller must now start the job.
    Reserved,
    /// The same caller and request were already admitted.
    Admitted,
}

/// Whether [`InvocationLog::admit`] started a job or found one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Admission {
    Started,
    Retried,
}

impl<T> InvocationLog<T> {
    /// A log remembering at most `capacity` invocations (at least one).
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: HashMap::new(),
            order: VecDeque::new(),
            capacity: capacity.max(1),
        }
    }

    /// Admit `request` for `caller`, calling `start` only if the id is new.
    ///
    /// # Errors
    ///
    /// Returns [`ActionCallError::InvocationConflict`] when the id was
    /// admitted for another caller or request, [`ActionCallError::Unavailable`]
    /// when all slots are reserved, or whatever `start` returns.
    pub fn admit(
        &mut self,
        caller: &Caller,
        request: &InvokeRequest,
        start: impl FnOnce() -> Result<T, ActionCallError>,
    ) -> Result<(&T, Admission), ActionCallError> {
        let id = request.invocation;
        let admission = match self.reserve(caller, request)? {
            Reservation::Admitted => Admission::Retried,
            Reservation::Reserved => match start() {
                Ok(handle) => {
                    self.complete(&id, handle);
                    Admission::Started
                }
                Err(error) => {
                    self.abandon(&id);
                    return Err(error);
                }
            },
        };
        self.entries
            .get(&id)
            .and_then(|entry| entry.handle.as_ref())
            .map(|handle| (handle, admission))
            .ok_or(ActionCallError::UnknownInvocation)
    }

    /// First half of an admission whose start completes later (for example
    /// across an asynchronous resolution): claim the id for `caller` and
    /// `request`, then [`complete`](Self::complete) or
    /// [`abandon`](Self::abandon) it.
    ///
    /// # Errors
    ///
    /// Returns [`ActionCallError::InvocationConflict`] when the id belongs to
    /// another caller or request, [`ActionCallError::Unanswered`] while an
    /// earlier start of the same invocation is still in flight, and
    /// [`ActionCallError::Unavailable`] while every slot is held by an
    /// in-flight reservation.
    pub fn reserve(
        &mut self,
        caller: &Caller,
        request: &InvokeRequest,
    ) -> Result<Reservation, ActionCallError> {
        let id = request.invocation;
        if let Some(entry) = self.entries.get_mut(&id) {
            if !caller.continues(&entry.caller) || !entry.request.same_invocation(request) {
                return Err(ActionCallError::InvocationConflict);
            }
            // Asked again on the connection that replaced its own: it is this one's from now on.
            entry.caller.clone_from(caller);
            // Its first start has not ended: a workspace action that runs whole as it starts
            // (a server taking in a workspace's gigabytes) is still going. Nothing is known of
            // what it did yet, so the caller asks the same invocation again, as for one whose
            // answer was lost.
            return if entry.handle.is_some() {
                Ok(Reservation::Admitted)
            } else {
                Err(ActionCallError::Unanswered)
            };
        }
        while self.order.len() >= self.capacity {
            let oldest_completed = self.order.iter().position(|candidate| {
                self.entries
                    .get(candidate)
                    .is_some_and(|entry| entry.handle.is_some())
            });
            let Some(index) = oldest_completed else {
                return Err(ActionCallError::Unavailable {
                    reason: "all invocation slots are still being admitted; retry".into(),
                });
            };
            if let Some(oldest) = self.order.remove(index) {
                self.entries.remove(&oldest);
            }
        }
        self.order.push_back(id);
        self.entries.insert(
            id,
            LogEntry {
                caller: caller.clone(),
                request: InvokeRequest {
                    wait_ms: None,
                    appearance: None,
                    ..request.clone()
                },
                handle: None,
            },
        );
        Ok(Reservation::Reserved)
    }

    /// Admit `request` again under its id where its person approved the asked record it waits
    /// in: the entry `caller` admitted for the same target and arguments, whose handle `waits`
    /// says is still asked, is reserved again carrying their answer, and the caller completes or
    /// abandons it as after [`Self::reserve`]. `waits` is handed `None` while the entry's first
    /// start is still in flight. False where nothing of that waits, which a reserve then refuses
    /// as another invocation.
    pub fn readmit(
        &mut self,
        caller: &Caller,
        request: &InvokeRequest,
        waits: impl FnOnce(Option<&T>) -> bool,
    ) -> bool {
        let Some(entry) = self.entries.get_mut(&request.invocation) else {
            return false;
        };
        let again = request.approval().is_some()
            && caller.continues(&entry.caller)
            && asked::same_call(&entry.request, request)
            && waits(entry.handle.as_ref());
        if again {
            entry.request = InvokeRequest {
                wait_ms: None,
                appearance: None,
                ..request.clone()
            };
            entry.handle = None;
        }
        again
    }

    /// Record the provider's handle for a reserved invocation.
    pub fn complete(&mut self, id: &InvocationId, handle: T) {
        if let Some(entry) = self.entries.get_mut(id) {
            entry.handle = Some(handle);
        }
    }

    /// Release a reservation whose start failed: nothing ran, so the id may
    /// be admitted later.
    pub fn abandon(&mut self, id: &InvocationId) {
        if self
            .entries
            .get(id)
            .is_some_and(|entry| entry.handle.is_none())
        {
            self.entries.remove(id);
            self.order.retain(|candidate| candidate != id);
        }
    }

    /// The request that admitted invocation `id`, for the provider that keeps this log: what an
    /// app it runs the invocation in carries as the proof of a call it makes for it.
    #[must_use]
    pub fn request_of(&self, id: &InvocationId) -> Option<&InvokeRequest> {
        self.entries.get(id).map(|entry| &entry.request)
    }

    /// The handle for an invocation `caller` admitted, or the caller it continues
    /// ([`Caller::continues`]).
    #[must_use]
    pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<&T> {
        self.entries
            .get(id)
            .filter(|entry| caller.follows(&entry.caller))
            .and_then(|entry| entry.handle.as_ref())
    }

    /// The invocation `caller` admitted under `id`, as its handle: `Some(None)` while its start
    /// is still in flight, `None` where `caller` admitted nothing under `id`.
    #[must_use]
    pub fn admitted(&self, caller: &Caller, id: &InvocationId) -> Option<Option<&T>> {
        self.entries
            .get(id)
            .filter(|entry| caller.follows(&entry.caller))
            .map(|entry| entry.handle.as_ref())
    }

    /// Mutable access to the handle for an invocation `caller` admitted.
    pub fn get_mut(&mut self, caller: &Caller, id: &InvocationId) -> Option<&mut T> {
        self.entries
            .get_mut(id)
            .filter(|entry| caller.follows(&entry.caller))
            .and_then(|entry| entry.handle.as_mut())
    }
}

/// The accounts actions whose answer is a secret ([`crate::SECRET_ANSWER_TAG`]): a cloud mount's
/// sign-in, and the sign-ins whose answers carry a one-time code.
pub const ACCOUNT_SECRET_ANSWERS: [&str; 3] =
    ["cloud-credential", "begin-sign-in", "begin-cloud-sign-in"];

/// Whether the action `action` answers a secret ([`crate::SECRET_ANSWER_TAG`]): handed to its
/// caller in the answer alone and kept in no record. The actions that declare it are the vault's
/// reveal and the code of this moment, a cloud mount's sign-in, and the sign-ins whose answers
/// carry a one-time code, wherever a host publishes them.
#[must_use]
pub fn answers_a_secret(action: &str) -> bool {
    VAULT_SECRET_ANSWERS.contains(&action) || ACCOUNT_SECRET_ANSWERS.contains(&action)
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU32, Ordering};

    use super::*;
    use crate::{ActionContract, ActionDescriptor, ExecutionLocus, InputSpec, OperationKind};

    tilo_test_env::scenario! {
        fn a_caller_keeps_its_identity_and_authority;

        phase a_bot_is_its_own_member_acting_for_its_installer;
        {
            let installer = [7u8; 32];
            let caller = Caller::bot("6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6", installer, [9u8; 32]);
            assert_eq!(
                caller.acting().member_id(),
                Some(&tilo_action_policy::MemberId::bot(
                    "6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6"
                ))
            );
            assert_eq!(
                caller.acting().acted_for_person(),
                Some(hex::encode(installer).as_str())
            );
            assert!(caller.acting().is_bot());
            assert!(caller.acting().delegated());
        }

        phase an_app_caller_acts_as_the_person_whose_session_runs_it;
        {
            let caller = Caller::local_app("so.tilo.example").acting_for("ada");
            assert_eq!(caller.acting().person_id(), Some("ada"));
            assert_eq!(
                caller.acting().app().map(ToString::to_string).as_deref(),
                Some("so.tilo.example")
            );
            assert_eq!(caller.acting_for_person(), Some("ada"));
        }

        phase execution_lifetime_is_shared_without_changing_caller_identity;
        {
            let first = Caller::local_person("owner").in_new_execution();
            let retained = first.clone();
            let second = first.clone().in_new_execution();
            let hash = |caller: &Caller| {
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                std::hash::Hash::hash(caller, &mut hasher);
                std::hash::Hasher::finish(&hasher)
            };
            let before = hash(&first);
            first.retire_execution();
            assert!(!retained.execution_is_live());
            assert!(second.execution_is_live());
            assert_eq!(first, retained);
            assert_eq!(hash(&first), before);
            let reconnected = retained.in_new_execution();
            assert!(reconnected.execution_is_live());
            assert_ne!(reconnected.execution_id(), first.execution_id());
        }

        phase projected_execution_retains_transport_retirement_without_changing_authority;
        {
            let original = Caller::local_person("projected-person").in_new_execution();
            let projected = Caller::authenticated([1; 32], [2; 32])
                .in_execution(original.execution_lease().unwrap());
            assert_eq!(projected.execution_id(), original.execution_id());
            assert_eq!(projected.user_public_key(), Some(&[1; 32]));
            assert_eq!(original.user_public_key(), None);
            original.retire_execution();
            assert!(!projected.execution_is_live());
        }
    }

    fn alice() -> Caller {
        Caller::authenticated([1; 32], [2; 32])
    }

    fn mallory() -> Caller {
        Caller::authenticated([9; 32], [8; 32])
    }

    tilo_test_env::scenario! {
        fn an_application_action_names_its_destination;

        phase an_application_action_target_names_its_workspace_and_app;
        {
            let target =
                application_action_target("workspace-1", "so.tilo.chat", "chat.workspace", "call");
            assert_eq!(
                application_provider(&target.provider),
                Some(("workspace-1", "so.tilo.chat"))
            );
            assert_eq!(target.address, ActionAddress::new("chat.workspace", "call"));
            for other in [
                "7",
                "workspace:workspace-1",
                "application:workspace-1",
                "application::so.tilo.chat",
                "application:workspace-1:",
                "application:workspace-1:a:",
            ] {
                assert_eq!(application_provider(other), None, "{other}");
            }
            assert_eq!(application_provider_resource(&target.provider), None);

            let target = application_resource_target(
                "workspace-1",
                "so.tilo.notes",
                "uuid:7",
                "notes.page:1",
                "open",
            );
            assert_eq!(
                application_provider(&target.provider),
                Some(("workspace-1", "so.tilo.notes"))
            );
            assert_eq!(
                application_provider_resource(&target.provider),
                Some("uuid:7")
            );
            assert_eq!(target.address, ActionAddress::new("notes.page:1", "open"));
        }
    }

    fn descriptor(resource: &str, action: &str) -> ActionDescriptor {
        ActionDescriptor {
            did: None,
            state: crate::ActionState::default(),
            semantic_identity: None,
            address: ActionAddress::new(resource, action),
            resource_kind: "notes.note".into(),
            resource_label: "Groceries".into(),
            action_label: "Archive".into(),
            keywords: Vec::new(),
            icon: None,
            description: Some("Move the note to the archive".into()),
            locus: ExecutionLocus::ClientLocal,
            kind: OperationKind::Document,
            contract: ActionContract::default(),
            input: InputSpec::None,
            params: Vec::new(),
            view: None,
        }
    }

    /// A provider with one action whose runs are counted, so a test can prove
    /// how many times the action actually started.
    struct CountingHost {
        runs: AtomicU32,
        log: Mutex<InvocationLog<Mutex<InvocationUpdate>>>,
    }

    impl CountingHost {
        fn new() -> Self {
            Self {
                runs: AtomicU32::new(0),
                log: Mutex::new(InvocationLog::default()),
            }
        }

        fn runs(&self) -> u32 {
            self.runs.load(Ordering::SeqCst)
        }

        fn finish(&self, caller: &Caller, id: &InvocationId) {
            if let Some(update) = self.log.lock().unwrap().get(caller, id) {
                *update.lock().unwrap() = InvocationUpdate::Succeeded {
                    invocation: *id,
                    output: ActionOutput::default(),
                };
            }
        }
    }

    impl CountingHost {
        fn cancel_now(&self, caller: &Caller, id: &InvocationId) -> Result<(), ActionCallError> {
            let log = self.log.lock().unwrap();
            let mut update = log
                .get(caller, id)
                .ok_or(ActionCallError::UnknownInvocation)?
                .lock()
                .unwrap();
            if update.is_terminal() {
                return Err(ActionCallError::NotCancellable {
                    reason: "finished".into(),
                });
            }
            *update = InvocationUpdate::Cancelled {
                invocation: *id,
                message: None,
            };
            drop(update);
            drop(log);
            Ok(())
        }
    }

    impl ActionProvider for CountingHost {
        fn query(
            &self,
            _caller: &Caller,
            query: CatalogueQuery,
        ) -> Pending<Result<CataloguePage, ActionCallError>> {
            Pending::ready(Ok(CataloguePage::from_rows(
                "1".into(),
                vec![catalogue_row("note:1", "archive")],
                &query,
            )))
        }

        fn invoke(
            &self,
            caller: &Caller,
            request: InvokeRequest,
        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
            Pending::ready((|| {
                if request.target.address != ActionAddress::new("note:1", "archive") {
                    return Err(ActionCallError::UnknownAction);
                }
                let update = {
                    let mut log = self.log.lock().unwrap();
                    let (update, _) = log.admit(caller, &request, || {
                        self.runs.fetch_add(1, Ordering::SeqCst);
                        Ok(Mutex::new(InvocationUpdate::Accepted {
                            invocation: request.invocation,
                        }))
                    })?;
                    let update = update.lock().unwrap().clone();
                    drop(log);
                    update
                };
                Ok(InvocationState::new(request.invocation, update).receipt())
            })())
        }

        fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
            self.log
                .lock()
                .unwrap()
                .get(caller, id)
                .map(|update| InvocationState::new(*id, update.lock().unwrap().clone()))
        }

        fn cancel(
            &self,
            caller: &Caller,
            id: &InvocationId,
        ) -> Pending<Result<(), ActionCallError>> {
            Pending::ready(self.cancel_now(caller, id))
        }
    }

    fn catalogue_row(resource: &str, action: &str) -> CatalogueRow {
        CatalogueRow {
            offered: None,
            provider: "7".into(),
            app_id: "notes".into(),
            parent_resource: String::new(),
            resource: CatalogueResource {
                id: resource.into(),
                kind: "notes.note".into(),
                label: "Groceries".into(),
                presentation: None,
            },
            action: Some(descriptor(resource, action)),
            has_children: false,
            visibility: None,
            surface: None,
        }
    }

    /// The answer of a provider that answers immediately.
    fn now<T>(mut answer: Pending<T>) -> T {
        match answer.poll_ready() {
            PendingPoll::Ready(value) => value,
            PendingPoll::Waiting | PendingPoll::Abandoned => panic!("the provider answers at once"),
        }
    }

    /// A provider offering more actions than one frame holds: twelve thousand,
    /// each described at length, as a large app's surface publishes them.
    #[derive(Clone)]
    struct HugeCatalogue;

    const HUGE_CATALOGUE: usize = 12_000;

    impl ActionProvider for HugeCatalogue {
        fn query(
            &self,
            _caller: &Caller,
            query: CatalogueQuery,
        ) -> Pending<Result<CataloguePage, ActionCallError>> {
            let rows = (0..HUGE_CATALOGUE)
                .map(|n| {
                    let mut row = catalogue_row(&format!("note:{n}"), &format!("archive-{n}"));
                    if let Some(action) = row.action.as_mut() {
                        action.description = Some("Moves the note out of the list. ".repeat(8));
                    }
                    row
                })
                .collect();
            Pending::ready(Ok(CataloguePage::from_rows("1".into(), rows, &query)))
        }

        fn invoke(
            &self,
            _caller: &Caller,
            _request: InvokeRequest,
        ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
            Pending::ready(Err(ActionCallError::UnknownAction))
        }

        fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
            None
        }

        fn cancel(
            &self,
            _caller: &Caller,
            _id: &InvocationId,
        ) -> Pending<Result<(), ActionCallError>> {
            Pending::ready(Err(ActionCallError::UnknownInvocation))
        }
    }

    /// The workspace's own app keeps its governance and its record of agents under one name: a
    /// caller that writes `workspace` reaches it, instead of being asked which of two apps it
    /// meant.
    #[test]
    fn the_workspaces_own_app_keeps_one_name() {
        assert_eq!(
            WORKSPACE_AGENTS_APP, WORKSPACE_GOVERNANCE_PROVIDER,
            "a workspace's agents are the workspace's own app's record"
        );
        assert_eq!(
            crate::tree::app_meant("workspace", &[(WORKSPACE_GOVERNANCE_PROVIDER, "Workspace")]),
            Ok(Some(WORKSPACE_GOVERNANCE_PROVIDER.to_owned())),
            "`workspace` names the workspace's own app"
        );
    }

    /// A caller paging a catalogue larger than a frame, through the provider's
    /// answer and the frame each page travels in, reads every action once, and
    /// no frame is over the limit: a page ends at its size as well as its count,
    /// whatever count was asked for, plain or a resource at a time.
    #[test]
    fn a_catalogue_larger_than_a_frame_travels_in_pages_that_each_fit_one() {
        for by_resource in [false, true] {
            let mut query = CatalogueQuery {
                max_results: u32::MAX,
                by_resource,
                ..CatalogueQuery::default()
            };
            let mut listed = Vec::new();
            let mut pages = 0usize;
            loop {
                let asked = RemoteActionMessage::CatalogueRequest {
                    correlation: 1,
                    query: query.clone(),
                };
                let answer =
                    now(serve(&HugeCatalogue, &alice(), asked).expect("a request is answered"));
                let bytes = RemoteActionFrame::new(answer)
                    .encode()
                    .expect("every page fits one frame");
                assert!(bytes.len() <= MAX_REMOTE_ACTION_FRAME_BYTES);
                let RemoteActionMessage::CatalogueResponse {
                    result: Ok(page), ..
                } = RemoteActionFrame::decode(&bytes).unwrap().message
                else {
                    panic!("a catalogue request is answered with its page");
                };
                pages += 1;
                listed.extend(
                    expand(page.rows)
                        .into_iter()
                        .filter_map(|row| row.action.map(|action| action.address.action)),
                );
                if page.exhausted {
                    break;
                }
                query.cursor = page.next_cursor;
                query.revision = Some(page.revision);
            }
            assert!(pages > 1, "the catalogue is larger than one frame");
            let expected: Vec<String> = (0..HUGE_CATALOGUE)
                .map(|n| format!("archive-{n}"))
                .collect();
            assert_eq!(listed, expected, "every action is listed once, in order");
        }
    }

    fn archive(invocation: InvocationId) -> InvokeRequest {
        InvokeRequest {
            on_behalf_of: None,
            invocation,
            target: RemoteActionTarget {
                provider: "7".into(),
                address: ActionAddress::new("note:1", "archive"),
            },
            argument: InvokeArgument::None,
            context: None,
            confirmation: None,
            revision: None,
            wait_ms: None,
            appearance: None,
            signed: None,
        }
    }

    fn round_trip(message: RemoteActionMessage) -> RemoteActionMessage {
        let bytes = RemoteActionFrame::new(message).encode().unwrap();
        RemoteActionFrame::decode(&bytes).unwrap().message
    }

    /// One of each catalogue and invoke message shape.
    fn request_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
        let mut arguments = serde_json::Map::new();
        arguments.insert("title".into(), serde_json::json!("Weekly"));
        vec![
            RemoteActionMessage::CatalogueRequest {
                correlation: 3,
                query: CatalogueQuery::default(),
            },
            RemoteActionMessage::CatalogueRequest {
                correlation: 5,
                query: CatalogueQuery {
                    provider: Some("7".into()),
                    parent_resource: Some("folder:a".into()),
                    needle: "gro".into(),
                    cursor: vec![1, 2],
                    revision: Some("r1".into()),
                    max_results: 8,
                    limits: Some(CatalogueLimits {
                        max_bytes: Some(4096),
                        max_work: None,
                        max_depth: Some(1),
                    }),
                    ..CatalogueQuery::default()
                },
            },
            RemoteActionMessage::CatalogueResponse {
                correlation: 3,
                result: now(CountingHost::new().query(&alice(), CatalogueQuery::default())),
            },
            RemoteActionMessage::CatalogueResponse {
                correlation: 4,
                result: Err(ActionCallError::Unavailable {
                    reason: "no apps".into(),
                }),
            },
            RemoteActionMessage::Invoke(InvokeRequest {
                on_behalf_of: None,
                argument: InvokeArgument::Json(arguments),
                context: Some(ActionContext::for_resource(
                    "note:1",
                    "notes.note",
                    "Groceries",
                )),
                ..archive(invocation)
            }),
            RemoteActionMessage::Invoke(InvokeRequest {
                on_behalf_of: None,
                argument: InvokeArgument::Text("hello".into()),
                ..archive(invocation)
            }),
            RemoteActionMessage::Invoke(InvokeRequest {
                on_behalf_of: None,
                confirmation: Some(Confirmation::Phrase("delete it".into())),
                ..archive(invocation)
            }),
            RemoteActionMessage::Invoke(InvokeRequest {
                wait_ms: Some(2_000),
                appearance: None,
                ..archive(invocation)
            }),
        ]
    }

    /// One of each receipt, update and cancel message shape.
    fn outcome_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
        vec![
            RemoteActionMessage::Receipt(InvocationReceipt {
                invocation,
                status: ReceiptStatus::Completed {
                    output: ActionOutput {
                        value: Some(serde_json::json!({"archived": true})),
                        resources: vec!["notes.note:1".into()],
                    },
                },
            }),
            RemoteActionMessage::Receipt(InvocationReceipt {
                invocation,
                status: ReceiptStatus::Failed {
                    error: ActionFailure {
                        code: "disk_full".into(),
                        message: "no space".into(),
                        details: None,
                        retryable: true,
                    },
                },
            }),
            RemoteActionMessage::Receipt(InvocationReceipt {
                invocation,
                status: ReceiptStatus::Rejected {
                    error: ActionCallError::InvocationConflict,
                },
            }),
            RemoteActionMessage::Receipt(InvocationReceipt {
                invocation,
                status: ReceiptStatus::Cancelled {
                    message: Some("stopped".into()),
                },
            }),
            RemoteActionMessage::observe(invocation),
            RemoteActionMessage::Observe {
                correlation: 7,
                invocation,
                wait_ms: Some(10_000),
                seen: Some(UpdateMark::Progress { sequence: 2 }),
            },
            RemoteActionMessage::Update {
                invocation,
                state: Some(InvocationState::new(
                    invocation,
                    InvocationUpdate::Progress {
                        invocation,
                        sequence: 2,
                        phase: "copying".into(),
                        completed: Some(1),
                        total: Some(4),
                        message: None,
                    },
                )),
                correlation: Some(7),
            },
            RemoteActionMessage::Update {
                invocation,
                state: None,
                correlation: Some(7),
            },
            RemoteActionMessage::Cancel { invocation },
            RemoteActionMessage::CancelResponse {
                invocation,
                result: Err(ActionCallError::NotCancellable {
                    reason: "finished".into(),
                }),
            },
        ]
    }

    tilo_test_env::scenario! {
        fn remote_messages_and_failures_read_back_typed;

        phase a_stale_revision_is_typed_and_travels_as_older_peers_read_it;
        // A stale revision is typed in this build and travels in the shape
        // every peer decodes: an older peer reads the invalid request it always
        // sent, and the reasons older providers gave it read back as the variant.
        {
            let encoded = serde_json::to_value(ActionCallError::StaleRevision).unwrap();
            assert_eq!(
                encoded,
                serde_json::json!({"InvalidRequest": {"reason": STALE_REVISION_REASON}})
            );
            assert_eq!(
                serde_json::from_value::<ActionCallError>(encoded).unwrap(),
                ActionCallError::StaleRevision
            );
            assert_eq!(ActionCallError::StaleRevision.code(), "stale_revision");
            // Only that exact reason: a refusal that merely mentions a revision
            // is the refusal it is.
            let other = ActionCallError::Refused {
                reason: "the call changed since that revision, honestly".into(),
            };
            let round_trip: ActionCallError =
                serde_json::from_value(serde_json::to_value(&other).unwrap()).unwrap();
            assert_eq!(round_trip, other);
            let needs = ActionCallError::InvalidRequest {
                reason: CONFIRMED_ACTION_NEEDS_REVISION.into(),
            };
            assert!(needs.needs_revision());
            assert!(!ActionCallError::StaleRevision.needs_revision());
        }

        phase a_failure_with_details_round_trips;
        // A failure's structured details travel beside its message.
        {
            let update = InvocationUpdate::Failed {
                invocation: InvocationId::new(),
                error: ActionFailure {
                    code: "invalid_arguments".into(),
                    message: "argument `pageSize` must be at most 64".into(),
                    details: Some(serde_json::json!({
                        "param": "pageSize",
                        "violation": {"kind": "maximum", "bound": 64}
                    })),
                    retryable: false,
                },
            };
            let encoded = serde_json::to_string(&update).unwrap();
            assert_eq!(
                serde_json::from_str::<InvocationUpdate>(&encoded).unwrap(),
                update
            );
        }

        phase a_refusal_for_want_of_the_person_carries_what_they_are_shown;
        // A run that reached something only the person may allow is refused for
        // want of their answer, and that refusal carries what the run stated
        // about it: the page departure it holds, as it travels to whoever asks them.
        {
            let facts = asked::AskedFacts::default()
                .with_fact("kind", "submit")
                .with_fact("destination", "https://visa.example")
                .with_fact("picture", "tilo.content:5f2b");
            let invocation = InvocationId::new();
            let state = InvocationState::new(
                invocation,
                InvocationUpdate::Failed {
                    invocation,
                    error: ActionFailure {
                        code: CONFIRMATION_REQUIRED_CODE.into(),
                        message: "the person has to allow this".into(),
                        details: Some(facts.to_details()),
                        retryable: false,
                    },
                },
            );
            let receipt = state.receipt();
            let ReceiptStatus::Rejected {
                error: ActionCallError::ConfirmationRequired(stated),
            } = &receipt.status
            else {
                panic!("a run waiting on the person is a refusal: {receipt:?}");
            };
            assert_eq!(**stated, facts);
            // The refusal travels with it, so whoever asks the person in another process
            // shows what leaves and not a name for it.
            let error = ActionCallError::asks(facts);
            let wire = serde_json::to_value(&error).unwrap();
            assert_eq!(
                serde_json::from_value::<ActionCallError>(wire).unwrap(),
                error
            );
            let wire = postcard::to_allocvec(&error).unwrap();
            assert_eq!(postcard::from_bytes::<ActionCallError>(&wire).unwrap(), error);
        }

        phase the_remote_wire_is_versioned_and_explicit;
        // Every message round-trips through a frame, frames from another version are refused not
        // misread, and the wire names versions and messages explicitly.
        // Invocations each phase below in order; every phase builds its own fixture.
        {
            every_message_round_trips_through_a_frame();
            frames_from_another_version_are_refused_not_misread();
            the_wire_names_versions_and_messages_explicitly();
        }
    }

    fn every_message_round_trips_through_a_frame() {
        let invocation = InvocationId(uuid::Uuid::from_u128(7));
        let messages = request_messages(invocation)
            .into_iter()
            .chain(outcome_messages(invocation));
        for message in messages {
            assert_eq!(round_trip(message.clone()), message);
        }
    }

    fn frames_from_another_version_are_refused_not_misread() {
        let mut frame = serde_json::to_value(RemoteActionFrame::new(
            RemoteActionMessage::CatalogueRequest {
                correlation: 1,
                query: CatalogueQuery::default(),
            },
        ))
        .unwrap();
        frame["version"] = serde_json::json!(REMOTE_ACTIONS_VERSION + 1);
        // A newer peer may also use a message this build has never seen.
        frame["message"] = serde_json::json!({"Subscribe": {"topic": 1}});
        let bytes = serde_json::to_vec(&frame).unwrap();
        assert_eq!(
            RemoteActionFrame::decode(&bytes),
            Err(RemoteFrameError::UnsupportedVersion {
                version: REMOTE_ACTIONS_VERSION + 1
            })
        );
        assert!(matches!(
            RemoteActionFrame::decode(
                format!(r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Subscribe":{{}}}}}}"#)
                    .as_bytes()
            ),
            Err(RemoteFrameError::Malformed(_))
        ));
        assert!(matches!(
            RemoteActionFrame::decode(&vec![b' '; MAX_REMOTE_ACTION_FRAME_BYTES + 1]),
            Err(RemoteFrameError::TooLarge { .. })
        ));
    }

    fn the_wire_names_versions_and_messages_explicitly() {
        let bytes = RemoteActionFrame::new(RemoteActionMessage::Cancel {
            invocation: InvocationId(uuid::Uuid::nil()),
        })
        .encode()
        .unwrap();
        assert_eq!(
            String::from_utf8(bytes).unwrap(),
            format!(
                r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Cancel":{{"invocation":"00000000-0000-0000-0000-000000000000"}}}}}}"#
            )
        );
    }

    fn a_retried_invocation_reports_the_original_and_runs_once() {
        let provider = CountingHost::new();
        let id = InvocationId::new();
        let first = now(provider.invoke(&alice(), archive(id))).unwrap();
        assert_eq!(first.status, ReceiptStatus::Accepted);
        let retry = now(provider.invoke(&alice(), archive(id))).unwrap();
        assert_eq!(retry, first);
        assert_eq!(provider.runs(), 1, "a retry never starts a second run");

        provider.finish(&alice(), &id);
        let after = now(provider.invoke(&alice(), archive(id))).unwrap();
        assert!(matches!(after.status, ReceiptStatus::Completed { .. }));
        assert_eq!(provider.runs(), 1, "a retry after completion reports it");
    }

    fn an_invocation_id_cannot_be_reused_or_borrowed() {
        let provider = CountingHost::new();
        let id = InvocationId::new();
        now(provider.invoke(&alice(), archive(id))).unwrap();

        let mut different = archive(id);
        different.argument = InvokeArgument::Text("other".into());
        assert_eq!(
            now(provider.invoke(&alice(), different)),
            Err(ActionCallError::InvocationConflict)
        );
        assert_eq!(
            now(provider.invoke(&mallory(), archive(id))),
            Err(ActionCallError::InvocationConflict),
            "another actor cannot attach to someone else's invocation"
        );
        assert_eq!(provider.observe(&mallory(), &id), None);
        assert_eq!(
            now(provider.cancel(&mallory(), &id)),
            Err(ActionCallError::UnknownInvocation)
        );
        assert_eq!(provider.runs(), 1);
    }

    fn a_refused_invocation_is_not_remembered() {
        let mut log = InvocationLog::<u32>::default();
        let request = archive(InvocationId::new());
        assert_eq!(
            log.admit(&alice(), &request, || Err(ActionCallError::NotPermitted)),
            Err(ActionCallError::NotPermitted)
        );
        let (handle, admission) = log.admit(&alice(), &request, || Ok(5)).unwrap();
        assert_eq!((*handle, admission), (5, Admission::Started));
    }

    fn the_log_forgets_oldest_invocations_past_capacity() {
        let mut log = InvocationLog::<u32>::with_capacity(2);
        let requests: Vec<_> = (0..3).map(|_| archive(InvocationId::new())).collect();
        for (n, request) in (0u32..).zip(&requests) {
            log.admit(&alice(), request, || Ok(n)).unwrap();
        }
        assert_eq!(log.get(&alice(), &requests[0].invocation), None);
        assert_eq!(log.get(&alice(), &requests[2].invocation), Some(&2));
    }

    fn serve_answers_requests_and_ignores_responses() {
        let provider = std::sync::Arc::new(CountingHost::new());
        let id = InvocationId::new();
        let Some(RemoteActionMessage::Receipt(receipt)) = serve(
            &provider,
            &alice(),
            RemoteActionMessage::Invoke(archive(id)),
        )
        .map(now) else {
            panic!("an invoke is answered with a receipt");
        };
        assert_eq!(receipt.status, ReceiptStatus::Accepted);

        let mut unknown = archive(InvocationId::new());
        unknown.target.address = ActionAddress::new("note:2", "delete");
        assert_eq!(
            serve(
                &provider,
                &alice(),
                RemoteActionMessage::Invoke(unknown.clone())
            )
            .map(now),
            Some(RemoteActionMessage::Receipt(InvocationReceipt {
                invocation: unknown.invocation,
                status: ReceiptStatus::Rejected {
                    error: ActionCallError::UnknownAction
                },
            }))
        );
        assert_eq!(
            serve(
                &provider,
                &alice(),
                RemoteActionMessage::Cancel { invocation: id }
            )
            .map(now),
            Some(RemoteActionMessage::CancelResponse {
                invocation: id,
                result: Ok(()),
            })
        );
        let Some(RemoteActionMessage::Update {
            state: Some(state), ..
        }) = serve(&provider, &alice(), RemoteActionMessage::observe(id)).map(now)
        else {
            panic!("an observe is answered with the invocation state");
        };
        assert!(matches!(
            state.receipt().status,
            ReceiptStatus::Cancelled { .. }
        ));
        assert!(serve(&provider, &alice(), RemoteActionMessage::Receipt(receipt)).is_none());
    }

    fn typed_arguments_use_the_local_invocation_slot() {
        let mut object = serde_json::Map::new();
        object.insert("n".into(), serde_json::json!(2));
        assert_eq!(InvokeArgument::None.to_slot(), None);
        assert_eq!(
            InvokeArgument::Text("hi".into()).to_slot().as_deref(),
            Some("hi")
        );
        assert_eq!(
            InvokeArgument::Json(object.clone()).to_slot(),
            Some(format!("{ARGUMENTS_JSON_PREFIX}{{\"n\":2}}"))
        );
        // A slot read back names the argument it was written from, so a
        // device that sends an invocation on runs what it admitted.
        for argument in [
            InvokeArgument::None,
            InvokeArgument::Text("hi".into()),
            InvokeArgument::Json(object),
        ] {
            assert_eq!(
                InvokeArgument::from_slot(argument.to_slot().as_deref()),
                argument
            );
        }
    }

    fn a_remote_device_is_the_person_its_root_names() {
        let caller = Caller::authenticated([0xAB; 32], [1; 32]);
        assert_eq!(
            caller.acting().member_id(),
            Some(&tilo_action_policy::MemberId::person("ab".repeat(32))),
            "every device of one person is the same member"
        );
        assert_eq!(caller.workspace(), None);
        let agent = Caller::local_agent("helper", "ada").in_workspace("workspace-1");
        assert_eq!(
            agent.acting().member_id(),
            Some(&tilo_action_policy::MemberId::agent("helper", "ada"))
        );
        assert_eq!(agent.workspace(), Some("workspace-1"));
        assert_eq!(agent.device_public_key(), None);
    }

    fn a_refusal_answers_every_request_and_nothing_else() {
        let error = ActionCallError::Unavailable {
            reason: "down".into(),
        };
        let id = InvocationId::new();
        assert_eq!(
            refuse(&invoke_message(id), error.clone()),
            Some(RemoteActionMessage::Receipt(InvocationReceipt {
                invocation: id,
                status: ReceiptStatus::Rejected {
                    error: error.clone()
                },
            }))
        );
        assert_eq!(
            refuse(&RemoteActionMessage::observe(id), error.clone()),
            Some(RemoteActionMessage::Update {
                invocation: id,
                state: None,
                correlation: Some(0),
            })
        );
        assert_eq!(
            refuse(
                &RemoteActionMessage::Update {
                    invocation: id,
                    state: None,
                    correlation: None,
                },
                error
            ),
            None
        );
    }

    fn invoke_message(id: InvocationId) -> RemoteActionMessage {
        RemoteActionMessage::Invoke(archive(id))
    }

    /// A change feed, asked across the API.
    mod change_wire;

    tilo_test_env::scenario! {
        fn a_host_serves_each_invocation_once_as_its_caller;

        phase a_retry_with_another_appearance_is_another_invocation;
        {
            let request = archive(InvocationId(uuid::Uuid::from_u128(9)));
            let appearing = InvokeRequest {
                appearance: Some(crate::Appearance::new("alice", None, None).unwrap()),
                ..request.clone()
            };
            assert!(!request.same_invocation(&appearing));
            assert!(appearing.same_invocation(&InvokeRequest {
                wait_ms: Some(10),
                ..appearing.clone()
            }));
            let json = serde_json::to_string(&request).unwrap();
            assert!(!json.contains("appearance"), "{json}");
        }

        phase remote_invocations_run_at_most_once_per_owned_id;
        // A retried invocation reports the original and runs once; ids cannot be reused or borrowed;
        // refusals are not remembered; the log forgets the oldest past capacity; a reservation holds
        // the id until the start completes.
        // Invocations each phase below in order; every phase builds its own fixture.
        {
            a_retried_invocation_reports_the_original_and_runs_once();
            an_invocation_id_cannot_be_reused_or_borrowed();
            a_refused_invocation_is_not_remembered();
            the_log_forgets_oldest_invocations_past_capacity();
            a_reservation_holds_the_id_until_the_start_completes();
        }

        phase admitted_executions_share_authority_but_cannot_borrow_invocations;
        {
            let first = alice().in_new_execution();
            let second = alice().in_new_execution();
            assert_eq!(first.acting(), second.acting());
            assert_eq!(first.workspace(), second.workspace());
            assert_ne!(first.execution_id(), second.execution_id());
            let provider = CountingHost::new();
            let id = InvocationId::new();
            let admitted = now(provider.invoke(&first, archive(id))).unwrap();
            assert_eq!(now(provider.invoke(&first, archive(id))).unwrap(), admitted);
            assert_eq!(
                now(provider.invoke(&second, archive(id))),
                Err(ActionCallError::InvocationConflict)
            );
            assert_eq!(provider.observe(&second, &id), None);
            assert_eq!(
                now(provider.cancel(&second, &id)),
                Err(ActionCallError::UnknownInvocation)
            );
            let retained = first.clone();
            let hash = |caller: &Caller| {
                let mut hasher = std::collections::hash_map::DefaultHasher::new();
                std::hash::Hash::hash(caller, &mut hasher);
                std::hash::Hasher::finish(&hasher)
            };
            let before = hash(&first);
            provider.retire_execution(&first);
            assert!(!retained.execution_is_live());
            assert!(second.execution_is_live());
            assert_eq!(first, retained);
            assert_eq!(hash(&first), before);
            let reconnected = retained.in_new_execution();
            assert!(reconnected.execution_is_live());
            assert_ne!(reconnected.execution_id(), first.execution_id());
            provider.finish(&first, &id);
            assert!(matches!(
                now(provider.invoke(&first, archive(id))).unwrap().status,
                ReceiptStatus::Completed { .. }
            ));
            assert!(provider.observe(&first, &id).is_some());
            assert!(provider.observe(&second, &id).is_none());
            // The connection that replaced the ended one is the same caller going on: it follows
            // and asks again what it started there, and the invocation is carried out once. The
            // one open beside it borrows nothing, even now.
            assert!(reconnected.continues(&first));
            assert!(!second.continues(&first));
            assert!(provider.observe(&reconnected, &id).is_some());
            assert!(matches!(
                now(provider.invoke(&reconnected, archive(id))).unwrap().status,
                ReceiptStatus::Completed { .. }
            ));
            assert_eq!(provider.runs(), 1);
            let someone_else = Caller::authenticated([3; 32], [4; 32]).in_new_execution();
            assert!(!someone_else.continues(&first), "another device continues nothing");
        }

        phase serving_answers_each_request_as_the_person_the_device_belongs_to;
        // Serve answers requests and ignores responses, typed arguments use the local invocation slot,
        // a remote device is the person its root names, and a refusal answers every request and nothing
        // else.
        // Invocations each phase below in order; every phase builds its own fixture.
        {
            serve_answers_requests_and_ignores_responses();
            typed_arguments_use_the_local_invocation_slot();
            a_remote_device_is_the_person_its_root_names();
            a_refusal_answers_every_request_and_nothing_else();
        }

        phase capacity_churn_preserves_in_flight_deduplication;
        {
            let caller = alice();
            let mut log = InvocationLog::<u32>::with_capacity(3);
            let pending = archive(InvocationId::new());
            assert_eq!(log.reserve(&caller, &pending), Ok(Reservation::Reserved));
            let mut completed = VecDeque::new();
            for n in 0..8 {
                let request = archive(InvocationId::new());
                assert_eq!(
                    log.admit(&caller, &request, || Ok(n)),
                    Ok((&n, Admission::Started))
                );
                completed.push_back(request.invocation);
                if completed.len() > 2 {
                    let evicted = completed.pop_front().unwrap();
                    assert_eq!(log.get(&caller, &evicted), None);
                }
                for id in &completed {
                    assert!(log.get(&caller, id).is_some());
                }
                assert!(matches!(
                    log.admit(&caller, &pending, || panic!("duplicate dispatch")),
                    Err(ActionCallError::Unanswered)
                ));
                assert_eq!(
                    log.reserve(&mallory(), &pending),
                    Err(ActionCallError::InvocationConflict)
                );
            }
            log.complete(&pending.invocation, 99);
            assert_eq!(
                log.admit(&caller, &pending, || panic!("duplicate dispatch")),
                Ok((&99, Admission::Retried))
            );
            let next = archive(InvocationId::new());
            assert_eq!(log.reserve(&caller, &next), Ok(Reservation::Reserved));
            assert_eq!(log.get(&caller, &pending.invocation), None);
        }

        phase capacity_churn_refuses_new_ids_when_every_slot_is_reserved;
        {
            let caller = alice();
            // Zero capacity is clamped to one, which must still protect its reservation.
            for capacity in 0..=2 {
                let mut log = InvocationLog::<u32>::with_capacity(capacity);
                let pending: Vec<_> = (0..capacity.max(1))
                    .map(|_| archive(InvocationId::new()))
                    .collect();
                for request in &pending {
                    assert_eq!(log.reserve(&caller, request), Ok(Reservation::Reserved));
                }
                let refused = archive(InvocationId::new());
                for _ in 0..4 {
                    assert!(matches!(
                        log.admit(&caller, &refused, || panic!("dispatch at capacity")),
                        Err(ActionCallError::Unavailable { .. })
                    ));
                    for request in &pending {
                        assert!(matches!(
                            log.admit(&caller, request, || panic!("duplicate dispatch")),
                            Err(ActionCallError::Unanswered)
                        ));
                    }
                }
                for (n, request) in pending.iter().enumerate() {
                    let n = u32::try_from(n).unwrap();
                    log.complete(&request.invocation, n);
                    assert_eq!(
                        log.admit(&caller, request, || panic!("duplicate dispatch")),
                        Ok((&n, Admission::Retried))
                    );
                }
                // Capacity refusals are not remembered and can be retried later.
                assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
                log.abandon(&refused.invocation);
                assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
            }
        }
    }

    fn a_reservation_holds_the_id_until_the_start_completes() {
        let mut log = InvocationLog::<u32>::default();
        let request = archive(InvocationId::new());
        assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Reserved));
        assert!(
            matches!(
                log.reserve(&alice(), &request),
                Err(ActionCallError::Unanswered)
            ),
            "a retry during the start neither runs twice nor pretends to be admitted: it is \
             asked again, as an answer lost on its way is"
        );
        assert_eq!(log.get(&alice(), &request.invocation), None);
        log.complete(&request.invocation, 9);
        assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Admitted));
        assert_eq!(log.get(&alice(), &request.invocation), Some(&9));

        let failed = archive(InvocationId::new());
        assert_eq!(log.reserve(&alice(), &failed), Ok(Reservation::Reserved));
        log.abandon(&failed.invocation);
        assert_eq!(
            log.reserve(&alice(), &failed),
            Ok(Reservation::Reserved),
            "an abandoned start ran nothing and may be admitted again"
        );
    }

    #[test]
    fn action_call_error_constructors_build_the_exact_variants() {
        let refused = ActionCallError::refused("not allowed now");
        assert_eq!(
            refused,
            ActionCallError::Refused {
                reason: "not allowed now".to_owned(),
            }
        );
        assert_eq!(refused.code(), "refused");
        assert_eq!(refused.said(), "refused: not allowed now");
        let owned_refusal = String::from("not allowed now");
        assert_eq!(ActionCallError::refused(owned_refusal), refused);

        let invalid = ActionCallError::invalid_request("missing field");
        assert_eq!(
            invalid,
            ActionCallError::InvalidRequest {
                reason: "missing field".to_owned(),
            }
        );
        assert_eq!(invalid.code(), "invalid_arguments");
        assert_eq!(invalid.said(), "invalid_arguments: missing field");
        let owned_invalid = String::from("missing field");
        assert_eq!(ActionCallError::invalid_request(owned_invalid), invalid);

        let unavailable = ActionCallError::unavailable("service off");
        assert_eq!(
            unavailable,
            ActionCallError::Unavailable {
                reason: "service off".to_owned(),
            }
        );
        assert_eq!(unavailable.code(), "remote_actions_unavailable");
        assert_eq!(unavailable.said(), "unavailable: service off");
        let owned_unavailable = String::from("service off");
        assert_eq!(ActionCallError::unavailable(owned_unavailable), unavailable);
    }
}