tilo-actions 0.5.3

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
//! 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; `tilo_action_calls::serve`
//!   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.
//! - `tilo_action_calls::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 serde::{Deserialize, Serialize};

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

pub mod admitted;
/// Tilo's HTTP API, asked on a connection to the device's daemon.
pub mod api;
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 argument_parts;
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;
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;
#[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, unanswered as confirmation_unanswered,
};
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, answered, device_job_address, device_job_path,
    device_record_address, device_record_space, parse_device_record_space, parse_job_path,
    reads_answer, unanswered,
};
#[cfg(any(test, feature = "test-support"))]
pub use test_provider::TestProvider;
pub use wait::{MAX_REMOTE_WAIT, MAX_REMOTE_WAIT_MS, UpdateMark, deadline as wait_deadline};

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;

/// 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 roles a workspace's people hold over its parts, under its member list
/// (`workspace/grants`).
pub const WORKSPACE_GRANTS: &str = "grants";
/// Give a person, or everyone, a role over one part of the workspace, or take that share back
/// (`workspace/grants#set`): `person` (their root key in hex, or `everyone`), `address` (such as
/// `<workspace>/files/**`) and `role` (none takes the share back).
pub const WORKSPACE_GRANT_SET: &str = "grant.set";
/// 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.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_GRANT_SET, Some(WORKSPACE_GRANTS), "set"),
    (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 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:
    /// `tilo_action_calls::serve` takes it off the request before the provider sees it, and
    /// `tilo_action_calls::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>>,
    /// The person's own press of the action waits for their yes, as the window or the shell
    /// that took the press decided it ([`crate::ActionContract::confirms`]): the dispatch asks
    /// them first, as it does where the action's contract asks. It only ever adds an ask; left
    /// out (`false`), the call is asked exactly as its contract and the caller's grants say.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub asks: bool,
}

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: _,
            asks,
        } = 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
            && *asks == other.asks
    }

    /// 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,
            asks: false,
        }
    }
}

/// 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 (`tilo_action_calls::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);
        }
    }
}

/// What answers one request to a provider, as the provider's host answers a request that
/// arrives on a connection: `tilo_action_calls::serve`.
///
/// A crate that hands requests to a provider takes this as a value from whoever runs it, so it
/// links none of the machinery that answers calls: the toolkit's in-process windows, and a shell
/// that serves its own providers on the device's dispatch.
pub type Serve = fn(
    &std::sync::Arc<dyn ActionProvider + Send + Sync>,
    &Caller,
    RemoteActionMessage,
) -> Option<Pending<RemoteActionMessage>>;

/// 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`]. `tilo_action_calls::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 (`tilo_action_calls::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.
#[must_use]
pub 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),
    /// Ask the device to answer one request of its API (`/v1`) as this connection is admitted
    /// ([`api`]), its body following the frame.
    ApiRequest {
        correlation: u64,
        request: api::ApiRequest,
    },
    /// Answer to [`Self::ApiRequest`], same correlation: its status and headers, its body to
    /// follow as `ApiBody` pieces and last `ApiEnd`.
    ApiResponse {
        correlation: u64,
        result: Result<api::ApiHead, ActionCallError>,
    },
    /// One piece of an answer's body. Sent by the device, never asked for.
    ApiBody(api::ApiBytes),
    /// An answer's body ended. Sent by the device, never asked for.
    ApiEnd { correlation: u64 },
}

/// 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 { .. }
        )
    }
}

/// 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>,
    /// The control the press answered, where the window knew it ([`press_points`]): the rect of
    /// the button, row or key, which the person's question stands beside. Like `press`,
    /// transport only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub press_control: Option<asked::PressRect>,
}

/// 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_control: None,
        }
    }

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

/// 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),
            }
        }
        RemoteActionMessage::ApiRequest { correlation, .. } => RemoteActionMessage::ApiResponse {
            correlation: *correlation,
            result: Err(error),
        },
        // Every other message answers a request: there is nothing to refuse.
        _ => return None,
    })
}

/// 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 super::*;

    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_member_types::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());
        }
    }

    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"));
        }
    }

    /// 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"
        );
    }

    #[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);
    }
}