cua-sdk 0.7.0

The cua SDK: the MIT #[uniffi::export] crate. One Cua object (embedded or connected to `cua daemon`) exposing env, sandboxes, local and spaces modules to Python, TypeScript, Swift and Kotlin.
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
//! Daemon-agnostic sandboxes: one API over the embedded runtime and the
//! daemon client.

use super::{Backend, SpacesdClient, ms, run};
use crate::types::{ExitInfo, ImageFormat, ProcessOutput, Screenshot};
use crate::{CuaError, Result};
use cua_daemon::{CreateRequest, SandboxRecord};
use cua_sandbox_core::{Probe, ProviderKind as CoreProvider, Status};
use std::{collections::HashMap, sync::Arc};

/// Coarse lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum SandboxStatus {
    /// Running (or bound).
    Running,
    /// Suspended or scaled to zero.
    Suspended,
    /// Stopped.
    Stopped,
    /// Starting.
    Provisioning,
    /// Unknown; see `SandboxInfo.status_detail`.
    Unknown,
}

/// Portable lifecycle phase, the same words on every provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum SandboxPhase {
    /// Being created.
    Provisioning,
    /// Booting; readiness probes have not passed yet.
    Starting,
    /// Running and ready.
    Ready,
    /// Stopped or suspended.
    Stopped,
}

impl SandboxPhase {
    fn of(status: SandboxStatus) -> Self {
        match status {
            SandboxStatus::Running => SandboxPhase::Ready,
            SandboxStatus::Provisioning => SandboxPhase::Provisioning,
            SandboxStatus::Suspended | SandboxStatus::Stopped => SandboxPhase::Stopped,
            SandboxStatus::Unknown => SandboxPhase::Starting,
        }
    }
}

/// The image a sandbox runs, as resolved and pinned at create time.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ImageInfo {
    /// The reference as requested, normalised
    /// (`docker.io/library/python:3.12-slim`).
    pub reference: String,
    /// `registry/repo@sha256:...` of the variant that runs.
    pub pinned_ref: String,
    /// The digest in `pinned_ref`.
    pub digest: String,
    /// `rootfs`, `containerdisk` or `lume`.
    pub variant: String,
    /// Architecture that runs (`amd64`/`arm64`), when known.
    pub arch: Option<String>,
    /// Guest OS: `linux`, `windows` or `macos`.
    pub os: String,
    /// Whether it runs emulated (no build for the requested architecture).
    pub emulated: bool,
    /// Whether the image carries cua-spacesd (`ai.cua.spacesd` label or a
    /// published 3211); `None` when it does not say.
    #[uniffi(default = None)]
    pub spacesd: Option<bool>,
}

impl From<cua_sandbox_core::ImageInfo> for ImageInfo {
    fn from(i: cua_sandbox_core::ImageInfo) -> Self {
        Self {
            reference: i.reference,
            pinned_ref: i.pinned_ref,
            digest: i.digest,
            variant: i.variant,
            arch: i.arch,
            os: i.os,
            emulated: i.emulated,
            spacesd: i.spacesd,
        }
    }
}

/// A sandbox as listed.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct SandboxInfo {
    /// Name.
    pub name: String,
    /// What kind of machine: `container` or `vm` (empty when not known:
    /// an existing machine).
    pub kind: String,
    /// The engine that runs it: `gvisor`, `runc`, `qemu`, `lume` or a
    /// provider's own (empty when not known).
    pub runtime: String,
    /// `runtime_type` as persisted (`direct`, `gvisor`, `qemu`, ...); prefer
    /// `location`, `kind` and `runtime`.
    pub runtime_type: String,
    /// Status.
    pub status: SandboxStatus,
    /// Provider's word for an unknown status.
    pub status_detail: Option<String>,
    /// No state file; torn down on delete.
    pub ephemeral: bool,
    /// Declared services: name → guest port (0 = only the name is known).
    pub services: HashMap<String, u16>,
    /// Service base URLs by name.
    pub endpoints: HashMap<String, String>,
    /// Image, when known.
    pub image: Option<String>,
    /// Qualified ref: `local:<name>`, `direct:<host:port>` or
    /// `<provider>:<name>`. Every call that takes a sandbox name accepts it.
    pub id: String,
    /// Portable phase: provisioning, starting, ready or stopped.
    pub phase: SandboxPhase,
    /// Where it runs: `local`, `direct` (a machine by address), `relay` or a
    /// provider.
    pub location: String,
    /// When it expires unless kept alive (unix seconds), when known.
    pub expires_at_unix: Option<i64>,
    /// Provider internals (local: `backend`, `container_id`). Not part of
    /// the portable API.
    pub provider_details: HashMap<String, String>,
    /// The image as resolved and pinned at create time (digest, variant).
    /// `None` for direct connections, images not resolved from a registry,
    /// and the daemon topology.
    #[uniffi(default = None)]
    pub image_info: Option<ImageInfo>,
    /// Why a local sandbox stopped without being asked to, in plain words
    /// ("out of memory", "killed", "exited with code 1"); `None` otherwise.
    #[uniffi(default = None)]
    pub stop_reason: Option<String>,
}

impl From<SandboxRecord> for SandboxInfo {
    fn from(r: SandboxRecord) -> Self {
        let (status, detail) = match r.status {
            Status::Running => (SandboxStatus::Running, None),
            Status::Suspended => (SandboxStatus::Suspended, None),
            Status::Stopped => (SandboxStatus::Stopped, None),
            Status::Provisioning => (SandboxStatus::Provisioning, None),
            Status::Unknown(u) => (SandboxStatus::Unknown, Some(u)),
        };
        SandboxInfo {
            id: r.id,
            phase: SandboxPhase::of(status),
            location: r.location,
            expires_at_unix: r.expires_at.map(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0)
            }),
            provider_details: r.provider_details.into_iter().collect(),
            name: r.name,
            kind: r.kind,
            runtime: r.runtime,
            runtime_type: r.runtime_type,
            status,
            status_detail: detail,
            ephemeral: r.ephemeral,
            services: r.services.into_iter().collect(),
            endpoints: r.endpoints.into_iter().collect(),
            image: r.image,
            image_info: r.image_info.map(Into::into),
            stop_reason: r.stop_reason,
        }
    }
}

/// A user-declared readiness probe. With no probes a sandbox is ready as
/// soon as its provider reports it running; nothing assumes a guest daemon.
///
/// Name a declared service (`service = "mcp"`) or a guest port.
#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
pub struct ReadinessProbe {
    /// Guest port (0 with `service`).
    #[uniffi(default = 0)]
    pub port: u16,
    /// HTTP path; `None` is a TCP connect probe.
    #[uniffi(default = None)]
    pub http_path: Option<String>,
    /// Exact HTTP status to wait for; `None` accepts any 2xx.
    #[uniffi(default = None)]
    pub http_status: Option<u16>,
    /// A declared service whose guest port to probe (instead of `port`).
    #[uniffi(default = None)]
    pub service: Option<String>,
}

impl ReadinessProbe {
    /// A TCP probe on a declared service.
    pub fn tcp(service: impl Into<String>) -> Self {
        Self {
            service: Some(service.into()),
            ..Default::default()
        }
    }

    /// `GET path` on a declared service returns 2xx.
    pub fn http(service: impl Into<String>, path: impl Into<String>) -> Self {
        Self {
            service: Some(service.into()),
            http_path: Some(path.into()),
            ..Default::default()
        }
    }

    /// The core probe; `services` resolves `service` (`env` defaults to
    /// 3211).
    pub(crate) fn resolve(&self, services: &HashMap<String, u16>) -> Result<Probe> {
        let port = match self.service.as_deref().filter(|s| !s.is_empty()) {
            Some(name) => match services.get(name).copied().filter(|p| *p > 0) {
                Some(p) => p,
                None if name == "env" => cua_sandbox_core::ENV_PORT,
                None => {
                    return Err(CuaError::InvalidArgument(format!(
                        "readiness probe names service {name:?}, which has no known port \
                         (declared: {:?})",
                        services.keys().collect::<Vec<_>>()
                    )));
                }
            },
            None => self.port,
        };
        if port == 0 {
            return Err(CuaError::InvalidArgument(
                "probe needs a port > 0 or a declared service".into(),
            ));
        }
        Ok(match &self.http_path {
            None => Probe::Tcp(port),
            Some(path) => Probe::Http {
                port,
                path: if path.starts_with('/') {
                    path.clone()
                } else {
                    format!("/{path}")
                },
                status: self.http_status,
            },
        })
    }
}

/// An extra container next to a sandbox (a compose-style sidecar),
/// addressed by name on every runtime: the sandbox reaches it at its
/// `name` (on its `ports`), it reaches the sandbox at `main`, and
/// `services` may name its ports (`{"db": 5432}`). Local containers run it
/// in the sandbox's network namespace (`localhost` works too; needs
/// `runtime="runc"`). Local VM sandboxes refuse sidecars. With sidecars the
/// service names `main`, `sidecars` and `sc` are reserved.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct Container {
    /// Image reference.
    pub image: String,
    /// argv replacing the image's entrypoint.
    #[uniffi(default = None)]
    pub command: Option<Vec<String>>,
    /// Environment (plain values, not secrets).
    #[uniffi(default)]
    pub env: HashMap<String, String>,
    /// Ports it listens on.
    #[uniffi(default = [])]
    pub ports: Vec<u16>,
    /// Name, unique within the sandbox, and its hostname (not `main`).
    /// Unset: from the image (`redis`).
    #[uniffi(default = None)]
    pub name: Option<String>,
}

impl Container {
    pub(crate) fn to_core(&self) -> cua_sandbox_core::Sidecar {
        let mut s = cua_sandbox_core::Sidecar::new(self.image.clone());
        if let Some(n) = self.name.clone().filter(|n| !n.is_empty()) {
            s.name = n;
        }
        s.command = self.command.clone().filter(|c| !c.is_empty());
        s.env = self.env.clone().into_iter().collect();
        s.ports = self.ports.clone();
        s
    }
}

/// Credentials for a private registry image, used for the pull. Never
/// logged or persisted.
#[derive(Clone, PartialEq, Eq, uniffi::Enum)]
pub enum RegistrySecret {
    /// A user name and password (or access token).
    Basic {
        /// User name.
        username: String,
        /// Password or token.
        password: String,
        /// Registry host; `None` means the image's.
        registry: Option<String>,
    },
    /// Read from environment variables of this process at create time.
    FromEnv {
        /// Variable holding the user name.
        username_var: String,
        /// Variable holding the password or token.
        password_var: String,
        /// Registry host; `None` means the image's.
        registry: Option<String>,
    },
    /// A private Amazon ECR image: a login token from the AWS CLI
    /// (`aws ecr get-login-password`) with the caller's AWS credentials.
    AwsEcr {
        /// Region; `None` takes it from the image's ECR host.
        region: Option<String>,
    },
}

impl std::fmt::Debug for RegistrySecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RegistrySecret::Basic {
                username, registry, ..
            } => f
                .debug_struct("Basic")
                .field("username", username)
                .field("password", &"<redacted>")
                .field("registry", registry)
                .finish(),
            RegistrySecret::FromEnv {
                username_var,
                password_var,
                registry,
            } => f
                .debug_struct("FromEnv")
                .field("username_var", username_var)
                .field("password_var", password_var)
                .field("registry", registry)
                .finish(),
            RegistrySecret::AwsEcr { region } => {
                f.debug_struct("AwsEcr").field("region", region).finish()
            }
        }
    }
}

impl RegistrySecret {
    /// The credentials for `image`.
    pub(crate) async fn credentials(
        &self,
        image: &str,
    ) -> Result<cua_sandbox_core::RegistryCredentials> {
        use cua_sandbox_core::RegistryCredentials as C;
        let scope = |c: C, registry: &Option<String>| match registry.as_deref() {
            Some(r) if !r.is_empty() => c.for_registry(r),
            _ => c,
        };
        match self {
            RegistrySecret::Basic {
                username,
                password,
                registry,
            } => {
                if username.is_empty() || password.is_empty() {
                    return Err(CuaError::InvalidArgument(
                        "RegistrySecret needs a username and a password".into(),
                    ));
                }
                Ok(scope(C::new(username, password), registry))
            }
            RegistrySecret::FromEnv {
                username_var,
                password_var,
                registry,
            } => {
                let read = |var: &str| {
                    std::env::var(var)
                        .ok()
                        .filter(|v| !v.is_empty())
                        .ok_or_else(|| {
                            CuaError::InvalidArgument(format!(
                                "RegistrySecret.from_env: ${var} is not set"
                            ))
                        })
                };
                Ok(scope(
                    C::new(read(username_var)?, read(password_var)?),
                    registry,
                ))
            }
            RegistrySecret::AwsEcr { region } => {
                let host = cua_image::registry_of(image).to_string();
                let region = region
                    .clone()
                    .filter(|r| !r.is_empty())
                    .or_else(|| cua_image::auth::ecr_region(&host).map(str::to_string))
                    .ok_or_else(|| {
                        CuaError::InvalidArgument(format!(
                            "RegistrySecret.aws_ecr: {image} is not a private ECR image \
                             (<account>.dkr.ecr.<region>.amazonaws.com); pass the region"
                        ))
                    })?;
                let token = cua_image::auth::aws_ecr_login(&region).await.ok_or_else(|| {
                    CuaError::InvalidArgument(format!(
                        "RegistrySecret.aws_ecr: `aws ecr get-login-password --region {region}` \
                         failed (install the AWS CLI and sign in)"
                    ))
                })?;
                Ok(C::new("AWS", token).for_registry(host))
            }
        }
    }
}

/// One image build step (as in `images.cua.ai/v1alpha1` recipes).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)]
pub enum ImageLayer {
    /// `apt-get install`.
    AptInstall {
        /// Packages.
        packages: Vec<String>,
    },
    /// `pip install`.
    PipInstall {
        /// Packages.
        packages: Vec<String>,
    },
    /// `uv pip install`.
    UvInstall {
        /// Packages.
        packages: Vec<String>,
    },
    /// A shell command.
    Run {
        /// Command.
        command: String,
    },
    /// An app from the cua catalog (VM images only).
    AppInstall {
        /// App id.
        app_id: String,
    },
}

impl ImageLayer {
    fn to_core(&self) -> cua_image::spec::ImageLayer {
        use cua_image::spec::ImageLayer as L;
        match self.clone() {
            ImageLayer::AptInstall { packages } => L::AptInstall { packages },
            ImageLayer::PipInstall { packages } => L::PipInstall { packages },
            ImageLayer::UvInstall { packages } => L::UvInstall { packages },
            ImageLayer::Run { command } => L::Run { command },
            ImageLayer::AppInstall { app_id } => L::AppInstall { app_id },
        }
    }
}

/// A local file copied into a built image.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct BuildFile {
    /// Local path.
    pub source: String,
    /// Absolute path in the image.
    pub destination: String,
}

/// Image layers built on top of a sandbox's image. Local: a build into the
/// container engine (container images only; VM images take no layers here),
/// cached by a content hash (`cua-b-<hash>`), so an identical spec never
/// rebuilds.
#[derive(Debug, Clone, Default, PartialEq, Eq, uniffi::Record)]
pub struct ImageBuild {
    /// Steps, in order.
    #[uniffi(default = [])]
    pub layers: Vec<ImageLayer>,
    /// Image environment.
    #[uniffi(default)]
    pub env: HashMap<String, String>,
    /// Ports the image exposes.
    #[uniffi(default = [])]
    pub ports: Vec<u16>,
    /// Local files copied in.
    #[uniffi(default = [])]
    pub files: Vec<BuildFile>,
    /// Build budget (default one hour).
    #[uniffi(default = None)]
    pub timeout_ms: Option<u32>,
}

impl ImageBuild {
    pub(crate) fn to_core(&self) -> cua_sandbox_core::BuildSpec {
        cua_sandbox_core::BuildSpec {
            from: String::new(),
            layers: self.layers.iter().map(ImageLayer::to_core).collect(),
            env: self.env.clone().into_iter().collect(),
            ports: self.ports.clone(),
            files: self
                .files
                .iter()
                .map(|f| cua_sandbox_core::BuildFile {
                    source: f.source.clone().into(),
                    destination: f.destination.clone(),
                })
                .collect(),
            timeout: self.timeout_ms.map(super::millis),
        }
    }
}

/// Options for [`Sandboxes::create`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct SandboxCreateOptions {
    /// Where it runs: `local`, `direct:<addr>` (an existing machine running
    /// cua-spacesd) or a registered provider. `None` (the default): the
    /// user default (`default.on` in `~/.cua/config.toml`,
    /// `CUA_DEFAULT_ON`, else `local`). `cloud` fails with the "Cua Cloud has
    /// ended" error.
    #[uniffi(default = None)]
    pub on: Option<String>,
    /// What kind of machine: `auto`, `container` or `vm`. `None`: the user
    /// default (`default.kind`, else `auto`: macOS and Windows images are
    /// VMs, an image with a container rootfs is a container, a disk-only
    /// image is a VM).
    #[uniffi(default = None)]
    pub kind: Option<String>,
    /// Which engine: `auto` or one the location offers for the kind (local
    /// `gvisor`, `runc`, `qemu`, `lume`). `None`:
    /// the user default (`default.runtime`, else `auto`, the safest
    /// available). A local sandbox with sidecars needs `runc` where gVisor
    /// would run. A combination that does not exist is `InvalidPlacement`,
    /// listing the valid values.
    #[uniffi(default = None)]
    pub runtime: Option<String>,
    /// Image reference. A `pool:<name>` image fails with the "Cua Cloud has
    /// ended" error.
    #[uniffi(default = "")]
    pub image: String,
    /// Name. `None`: ephemeral (no state file; deleted with the sandbox).
    #[uniffi(default = None)]
    pub name: Option<String>,
    /// spacesd token.
    #[uniffi(default = None)]
    pub token: Option<String>,
    /// Guest OS (`linux`, `macos`, `windows`).
    #[uniffi(default = None)]
    pub os: Option<String>,
    /// vCPUs.
    #[uniffi(default = None)]
    pub cpus: Option<u32>,
    /// Memory (MiB).
    #[uniffi(default = None)]
    pub memory_mb: Option<u64>,
    /// Extra guest ports (local: published).
    #[uniffi(default = [])]
    pub ports: Vec<u16>,
    /// Named services (name → guest port). `env` defaults to 3211.
    #[uniffi(default)]
    pub services: HashMap<String, u16>,
    /// Readiness probes.
    #[uniffi(default = [])]
    pub wait_for: Vec<ReadinessProbe>,
    /// Readiness budget (default 10 min).
    #[uniffi(default = None)]
    pub ready_timeout_ms: Option<u32>,
    /// Guest environment (local: container environment or cloud-init; values
    /// are not secrets).
    #[uniffi(default)]
    pub env: HashMap<String, String>,
    /// The sandbox's command (argv), replacing the image's entrypoint.
    /// Same meaning local (container ENTRYPOINT, or run by cloud-init in a
    /// Linux VM) and in the cloud (the template command with
    /// `processMode: Run`, on gVisor and KubeVirt).
    #[uniffi(default = None)]
    pub command: Option<Vec<String>>,
    /// Sidecar containers, addressed by name (see [`Container`]).
    #[uniffi(default = [])]
    pub sidecars: Vec<Container>,
    /// Credentials for a private `image` (and sidecar images on its
    /// registry).
    #[uniffi(default = None)]
    pub registry_secret: Option<RegistrySecret>,
    /// Image layers built on top of `image` (a build into the local
    /// container engine, cached by content).
    #[uniffi(default = None)]
    pub build: Option<ImageBuild>,
    /// Guest network: `"default"` (unset) gives outbound network, like a
    /// Docker container; `"none"` cuts it while published ports still work.
    /// Only local QEMU VMs honour `"none"`; containers and Lume reject it.
    #[uniffi(default = None)]
    pub network: Option<String>,
    /// Binaries to inject once the sandbox is up, so tests run the build
    /// under test and not the copy the image bundles (see [`Overlay`]; the
    /// same as calling [`Sandbox::overlay`] after create). Needs
    /// cua-spacesd in the image, or a local container.
    #[uniffi(default = [])]
    pub overlays: Vec<super::Overlay>,
    /// Keep a named sandbox whose readiness check fails (its VM or
    /// container, and its record) to debug it. `false` (the default): a
    /// failed create deletes what it made. Ephemeral sandboxes are always
    /// deleted.
    #[uniffi(default = false)]
    pub keep_on_failure: bool,
    /// A GPU option of the runtime it runs on (`Spaces.gpu_support` lists them):
    /// `paravirtual` (a macOS VM on Lume: GPU acceleration, experimental),
    /// `virgl` (QEMU on Linux), `nvidia` (a runc container on Linux), a
    /// contrib provider's GPU type; `auto` picks the runtime's own. `None`
    /// (the default): no GPU.
    #[uniffi(default = None)]
    pub gpu: Option<String>,
}

impl Default for SandboxCreateOptions {
    fn default() -> Self {
        Self::auto("")
    }
}

impl SandboxCreateOptions {
    /// Options for `image` where `on` says (`local`, `direct:<addr>`, a
    /// provider), everything else default.
    pub fn new(on: impl Into<String>, image: impl Into<String>) -> Self {
        Self {
            on: Some(on.into()),
            ..Self::auto(image)
        }
    }

    /// Options for `image` with the default location (see
    /// [`SandboxCreateOptions::on`]).
    pub fn auto(image: impl Into<String>) -> Self {
        Self {
            on: None,
            kind: None,
            runtime: None,
            image: image.into(),
            name: None,
            token: None,
            os: None,
            cpus: None,
            memory_mb: None,
            ports: vec![],
            services: HashMap::new(),
            wait_for: vec![],
            ready_timeout_ms: None,
            env: HashMap::new(),
            command: None,
            sidecars: vec![],
            registry_secret: None,
            build: None,
            network: None,
            overlays: vec![],
            keep_on_failure: false,
            gpu: None,
        }
    }

    /// The location, kind and runtime this create runs with, each with
    /// where it came from: explicit values, else the user defaults
    /// ([`cua_sandbox_core::settings`]).
    pub fn placement(&self) -> Result<cua_sandbox_core::settings::Resolved> {
        use cua_sandbox_core::placement::{Kind, On, Runtime};
        let text = |v: &Option<String>| {
            v.as_deref()
                .map(str::trim)
                .filter(|v| !v.is_empty())
                .map(str::to_string)
        };
        let place =
            |e: cua_sandbox_core::placement::PlacementError| CuaError::InvalidPlacement(e.message);
        let on = text(&self.on)
            .map(|o| On::parse(&o))
            .transpose()
            .map_err(place)?;
        let kind = text(&self.kind)
            .map(|k| Kind::parse(&k))
            .transpose()
            .map_err(place)?;
        let runtime = text(&self.runtime)
            .map(|r| Runtime::parse(&r))
            .transpose()
            .map_err(place)?;
        let settings = cua_sandbox_core::settings::Settings::load()
            .map_err(|e| CuaError::InvalidArgument(e.to_string()))?;
        let r = settings
            .resolve(on, kind, runtime)
            .map_err(|e| CuaError::InvalidArgument(e.to_string()))?;
        if r.on == On::Cloud {
            return Err(CuaError::Unsupported(cua_sandbox_core::CLOUD_ENDED.into()));
        }
        cua_sandbox_core::placement::validate(&r.on, r.kind, &r.runtime).map_err(place)?;
        Ok(r)
    }

    fn to_request(&self) -> Result<CreateRequest> {
        use cua_sandbox_core::placement::On;
        let placement = self.placement()?;
        let (provider, url) = match &placement.on {
            On::Local => (Some(CoreProvider::Local), None),
            On::Direct(a) => (Some(CoreProvider::Direct), Some(a.clone())),
            On::Provider(_) => (Some(CoreProvider::Contrib), None),
            // `placement()` refused the cloud above.
            On::Relay(_) | On::Host(_) | On::Cloud => (None, None),
        };
        Ok(CreateRequest {
            // Resolved here, in the caller's process: a daemon never applies
            // its own environment to this request.
            location: Some(placement.on.to_string()),
            kind: Some(placement.kind.to_string()),
            runtime: Some(placement.runtime.to_string()),
            provider,
            url,
            name: self.name.clone(),
            image: self.image.clone(),
            token: self.token.clone(),
            os: self.os.clone(),
            cpus: self.cpus,
            memory_mb: self.memory_mb,
            ports: self.ports.clone(),
            services: self.services.clone().into_iter().collect(),
            wait_for: self
                .wait_for
                .iter()
                .map(|p| p.resolve(&self.services))
                .collect::<Result<_>>()?,
            ready_timeout: self.ready_timeout_ms.map(super::millis),
            env: self.env.clone().into_iter().collect(),
            command: self.command.clone().filter(|c| !c.is_empty()),
            labels: Default::default(),
            sidecars: self.sidecars.iter().map(Container::to_core).collect(),
            // Resolved (env, AWS CLI) in `create`, in this process.
            registry_credentials: None,
            build: self
                .build
                .as_ref()
                .map(ImageBuild::to_core)
                .filter(|b| !b.is_empty()),
            container_runtime: None,
            network: self.network.clone().filter(|n| !n.is_empty()),
            // An ephemeral sandbox a daemon holds for this process is reaped
            // once this process is gone.
            owner_pid: Some(std::process::id()),
            keep_on_failure: self.keep_on_failure,
            gpu: self.gpu.clone().filter(|g| !g.trim().is_empty()),
        })
    }
}

/// A sandbox listing and what it left out.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct SandboxListing {
    /// Sandboxes, each with its `location`.
    pub sandboxes: Vec<SandboxInfo>,
    /// Sources left out of the listing.
    pub warnings: Vec<String>,
}

/// An HTTP header.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HttpHeader {
    /// Name.
    pub name: String,
    /// Value.
    pub value: String,
}

/// Where a sandbox service is reachable from this process.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ServiceEndpoint {
    /// Base URL (append the path).
    pub url: String,
    /// Headers every request needs.
    pub headers: Vec<HttpHeader>,
}

/// An HTTP response from a sandbox service.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct HttpResponse {
    /// Status.
    pub status: u16,
    /// Headers.
    pub headers: Vec<HttpHeader>,
    /// Body.
    pub body: Vec<u8>,
}

/// Options for [`Sandbox::viewer_url`].
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ViewerOptions {
    /// Lifetime of the link in seconds (60 to 86400). Default 3600.
    #[uniffi(default = None)]
    pub ttl_seconds: Option<u32>,
    /// Watch only: no input, clipboard, files or microphone.
    #[uniffi(default = false)]
    pub view_only: bool,
    /// Two-way clipboard sync.
    #[uniffi(default = true)]
    pub clipboard: bool,
    /// Guest directory for uploads and folder sharing (`~` is the desktop
    /// user's home). `None` means `~`; an empty string turns files off.
    #[uniffi(default = None)]
    pub files_root: Option<String>,
    /// Allow the microphone (also subject to the sandbox's uplink policy).
    #[uniffi(default = true)]
    pub microphone: bool,
}

impl Default for ViewerOptions {
    fn default() -> Self {
        Self {
            ttl_seconds: None,
            view_only: false,
            clipboard: true,
            files_root: None,
            microphone: true,
        }
    }
}

/// A link to the sandbox desktop in the cua-spacesd HTML5 viewer.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ViewerLink {
    /// Open this in any modern browser. The credential is in the fragment
    /// (`#ticket=`), which browsers never send to a server.
    pub url: String,
    /// When the link stops working for new connections (unix seconds).
    pub expires_at_unix: i64,
}

/// A shareable URL of a sandbox service that expires.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct PublicUrl {
    /// Id for `Sandbox.revoke_public_url`.
    pub id: String,
    /// The URL.
    pub url: String,
    /// When it stops working (unix seconds).
    pub expires_at_unix: i64,
    /// Service name.
    pub service: String,
    /// Provider internals (local: upstream).
    pub provider_details: HashMap<String, String>,
}

impl From<cua_daemon::shares::PublicUrl> for PublicUrl {
    fn from(u: cua_daemon::shares::PublicUrl) -> Self {
        PublicUrl {
            id: u.id,
            url: u.url,
            expires_at_unix: u
                .expires_at
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0),
            service: u.service,
            provider_details: u.provider_details.into_iter().collect(),
        }
    }
}

/// A media bridge for webviews (daemon mode).
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct MediaBridge {
    /// Loopback `ws://` URL carrying a short-lived bridge ticket. Speaks
    /// rcdp wire v2 unchanged; no env token is exposed.
    pub ws_url: String,
    /// The bridge ticket (also accepted as subprotocol
    /// `cua.ticket.<ticket>`).
    pub ticket: String,
    /// `cua.env.v1.OpenMediaResponse` as proto3 JSON (upstream ticket
    /// removed).
    pub open_media_response_json: String,
}

/// Creates, finds and manages sandboxes.
#[derive(uniffi::Object)]
pub struct Sandboxes {
    pub(crate) backend: Backend,
}

impl Sandboxes {
    /// Creates without applying overlays.
    async fn create_bare(
        &self,
        options: SandboxCreateOptions,
        progress: Option<cua_sandbox_core::progress::Sink>,
    ) -> Result<Arc<Sandbox>> {
        let mut req = options.to_request()?;
        let backend = self.backend.clone();
        let secret = options.registry_secret.clone();
        let rec = run(async move {
            // Credentials are read here (this process's environment and AWS
            // CLI), then travel only to the runtime that uses them.
            if let Some(s) = secret {
                req.registry_credentials = Some(s.credentials(&req.image).await?);
            }
            Ok(match (&backend, progress) {
                (Backend::Embedded(rt), progress) => {
                    cua_sandbox_core::progress::carry(progress, rt.create(req)).await?
                }
                (Backend::Daemon(d), Some(progress)) => d.create_reporting(req, progress).await?,
                (Backend::Daemon(d), None) => d.create(req).await?,
            })
        })
        .await?;
        Ok(self.handle(rec.into()))
    }

    /// Rust hosts: a handle for a known sandbox without reattaching (for
    /// lifecycle calls on a suspended one).
    pub async fn by_name(&self, name: String) -> Result<Arc<Sandbox>> {
        let info = self.get(name).await?;
        Ok(self.handle(info))
    }

    fn handle(&self, info: SandboxInfo) -> Arc<Sandbox> {
        Arc::new(Sandbox {
            backend: self.backend.clone(),
            info,
        })
    }
}

#[uniffi::export]
impl Sandboxes {
    /// Creates (local, your cloud, a provider) or connects (direct) a sandbox
    /// and waits for the provider and every readiness probe. `on: "cloud"`
    /// fails with the "Cua Cloud has ended" error.
    pub async fn create(&self, options: SandboxCreateOptions) -> Result<Arc<Sandbox>> {
        self.create_reported(options, None).await
    }
}

impl Sandboxes {
    /// Rust hosts: [`Sandboxes::create`], passing what the create does (the
    /// image download with its bytes, creating, booting, the readiness
    /// probes) to `progress` as it happens. Through a daemon that predates
    /// streaming creates, `progress` hears nothing.
    pub async fn create_reporting(
        &self,
        options: SandboxCreateOptions,
        progress: cua_sandbox_core::progress::Sink,
    ) -> Result<Arc<Sandbox>> {
        self.create_reported(options, Some(progress)).await
    }

    async fn create_reported(
        &self,
        options: SandboxCreateOptions,
        progress: Option<cua_sandbox_core::progress::Sink>,
    ) -> Result<Arc<Sandbox>> {
        let facts = super::telemetry::CreateFacts::of(&options);
        let mut options = options;
        // A local sandbox's cua-spacesd reports aggregate health counts only
        // when the host's telemetry is on (and the caller did not decide).
        if facts.is_local() && cua_telemetry::global().is_enabled() {
            options
                .env
                .entry("CUA_SPACESD_TELEMETRY".into())
                .or_insert_with(|| "1".into());
        }
        let r = self.create_recorded(options, progress).await;
        facts.record(&r);
        r
    }

    async fn create_recorded(
        &self,
        options: SandboxCreateOptions,
        progress: Option<cua_sandbox_core::progress::Sink>,
    ) -> Result<Arc<Sandbox>> {
        let overlays = options.overlays.clone();
        for o in &overlays {
            o.validate()?;
        }
        let ready_timeout_ms = options.ready_timeout_ms;
        let sandbox = self.create_bare(options, progress).await?;
        if overlays.is_empty() {
            return Ok(sandbox);
        }
        // The overlays are part of what was asked for: a sandbox that
        // cannot run the build under test is deleted, not returned.
        match sandbox.clone().overlay(overlays, ready_timeout_ms).await {
            Ok(_) => Ok(sandbox),
            Err(e) => {
                let _ = sandbox.delete().await;
                Err(e)
            }
        }
    }
}

#[uniffi::export]
impl Sandboxes {
    /// Connects directly to a machine by URL (`http(s)://host:port`, bare
    /// `host:port` or a relay URL) with an optional spacesd token. No daemon is assumed and nothing is probed.
    pub async fn connect_url(
        &self,
        url: String,
        token: Option<String>,
        name: Option<String>,
    ) -> Result<Arc<Sandbox>> {
        let addr = url.trim().to_string();
        if addr.is_empty() {
            return Err(CuaError::InvalidArgument("connect_url needs a URL".into()));
        }
        self.create(SandboxCreateOptions {
            name,
            token,
            ..SandboxCreateOptions::new(format!("direct:{addr}"), "")
        })
        .await
    }

    /// Reattaches to a sandbox by ref (`local:<name>`, `cloud:<name>`,
    /// `direct:<host:port>`, a legacy id) or by a name that is unique across
    /// locations (else `AmbiguousSandbox`, listing the qualified refs).
    pub async fn connect(&self, name: String) -> Result<Arc<Sandbox>> {
        let started = std::time::Instant::now();
        let backend = self.backend.clone();
        let rec = run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.connect(&name).await?,
                Backend::Daemon(d) => d.connect(&name).await?,
            })
        })
        .await;
        super::telemetry::api("sandbox.connect", started, &rec);
        Ok(self.handle(rec?.into()))
    }

    /// Sandboxes, each tagged with its `location`. `None` (the default):
    /// all of them, local and direct, whatever the default location is.
    /// `"local"` or `"direct"`: only those. Cua Cloud has ended, so
    /// `"cloud"` lists none.
    pub async fn list(&self, location: Option<String>) -> Result<Vec<SandboxInfo>> {
        let listing = self.list_with_warnings(location).await?;
        for w in &listing.warnings {
            tracing::warn!("{w}");
        }
        Ok(listing.sandboxes)
    }

    /// [`Sandboxes::list`] with what the listing left out.
    pub async fn list_with_warnings(&self, location: Option<String>) -> Result<SandboxListing> {
        let backend = self.backend.clone();
        let p = location_filter(location.as_deref())?;
        // Cua Cloud has ended: it has no sandboxes to list.
        if location.as_deref().is_some_and(asks_for_cloud) {
            return Ok(SandboxListing {
                sandboxes: vec![],
                warnings: vec![],
            });
        }
        let listing = run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.list_filtered(p).await?,
                Backend::Daemon(d) => d.list_filtered(p).await?,
            })
        })
        .await?;
        Ok(SandboxListing {
            sandboxes: listing.sandboxes.into_iter().map(Into::into).collect(),
            warnings: listing.warnings,
        })
    }

    /// Deprecated: [`Sandboxes::list`] with no location lists everything.
    pub async fn list_all(&self) -> Result<Vec<SandboxInfo>> {
        self.list(None).await
    }

    /// Cancels the create of the named sandbox `name` that is still
    /// running (in this process or the daemon): the work in flight stops
    /// (an image download, a boot) and what the create made is
    /// deleted; a sandbox of that name that existed before is never
    /// touched. Finished image downloads stay cached. Returns what was
    /// removed, or `None` when no create of that name was running. The
    /// create itself fails with `Cancelled`.
    pub async fn cancel_create(&self, name: String) -> Result<Option<String>> {
        let backend = self.backend.clone();
        run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.cancel_create(&name).await?,
                Backend::Daemon(d) => d.cancel_create(&name).await?,
            })
        })
        .await
    }

    /// One sandbox's info, by ref or unique name.
    pub async fn get(&self, name: String) -> Result<SandboxInfo> {
        let backend = self.backend.clone();
        Ok(run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.record(&name).await?,
                Backend::Daemon(d) => d.get(&name).await?,
            })
        })
        .await?
        .into())
    }

    /// Deletes a sandbox by ref or unique name.
    pub async fn delete(&self, name: String) -> Result<()> {
        let backend = self.backend.clone();
        // The location word of a ref (`cloud:box`); a bare name is `other`.
        let location = name
            .split_once(':')
            .map(|(l, _)| l.to_string())
            .unwrap_or_default();
        let r = run(async move { delete(&backend, &name).await }).await;
        super::telemetry::sandbox_deleted(&location, &r);
        r
    }
}

impl Sandboxes {
    /// The sandboxes this machine knows (state files, local backends,
    /// connected URLs) of `provider` (all when `None`). Rust only; the CLI's
    /// `cua do ls` uses it.
    pub async fn list_known(&self, location: Option<&str>) -> Result<Vec<SandboxInfo>> {
        let backend = self.backend.clone();
        let p = location_filter(location)?;
        let listing = run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.list_filtered(p).await?,
                Backend::Daemon(d) => d.list_filtered(p).await?,
            })
        })
        .await?;
        Ok(listing.sandboxes.into_iter().map(Into::into).collect())
    }
}

/// Whether a `location` filter asks for Cua Cloud, which has ended.
fn asks_for_cloud(location: &str) -> bool {
    cua_sandbox_core::Location::parse(location.trim()) == Some(cua_sandbox_core::Location::Cloud)
}

/// A `location` filter (`local`, `direct`; empty or `None`: all).
fn location_filter(location: Option<&str>) -> Result<Option<CoreProvider>> {
    let Some(l) = location.map(str::trim).filter(|l| !l.is_empty()) else {
        return Ok(None);
    };
    match cua_sandbox_core::Location::parse(l) {
        Some(cua_sandbox_core::Location::Local) => Ok(Some(CoreProvider::Local)),
        // The caller returns an empty listing before using the filter.
        Some(cua_sandbox_core::Location::Cloud) => Ok(None),
        Some(cua_sandbox_core::Location::Direct) => Ok(Some(CoreProvider::Direct)),
        _ => Err(CuaError::InvalidArgument(format!(
            "location {l:?}: expected local or direct"
        ))),
    }
}

async fn delete(backend: &Backend, name: &str) -> Result<()> {
    match backend {
        Backend::Embedded(rt) => Ok(rt.delete(name).await?),
        Backend::Daemon(d) => Ok(d.delete(name).await?),
    }
}

/// A sandbox handle.
#[derive(uniffi::Object)]
pub struct Sandbox {
    backend: Backend,
    info: SandboxInfo,
}

#[uniffi::export]
impl Sandbox {
    /// Name.
    pub fn name(&self) -> String {
        self.info.name.clone()
    }

    /// Qualified ref (`local:<name>`, `cloud:<name>`, `direct:<host:port>`),
    /// the same kind of value local and in the cloud; it round-trips through
    /// `Sandboxes.connect`.
    pub fn id(&self) -> String {
        self.info.id.clone()
    }

    /// Where it runs: `local`, `cloud`, `direct` or `relay`.
    pub fn location(&self) -> String {
        self.info.location.clone()
    }

    /// What kind of machine: `container` or `vm` (empty when not known).
    pub fn kind(&self) -> String {
        self.info.kind.clone()
    }

    /// The engine that runs it (`gvisor`, `runc`, `qemu`, `lume`,
    /// `kubevirt`; empty when not known).
    pub fn runtime(&self) -> String {
        self.info.runtime.clone()
    }

    /// `runtime_type`.
    pub fn runtime_type(&self) -> String {
        self.info.runtime_type.clone()
    }

    /// Whether the sandbox is torn down on delete and has no state file.
    pub fn is_ephemeral(&self) -> bool {
        self.info.ephemeral
    }

    /// Declared services.
    pub fn services(&self) -> HashMap<String, u16> {
        self.info.services.clone()
    }

    /// Info as of creation / connection.
    pub fn info(&self) -> SandboxInfo {
        self.info.clone()
    }

    /// The image this sandbox runs, as resolved and pinned at create time:
    /// the digest and variant that actually ran. `None` for direct (URL)
    /// connections, images not resolved from a registry, and the daemon
    /// topology.
    pub fn image_info(&self) -> Option<ImageInfo> {
        self.info.image_info.clone()
    }

    /// Fresh info (status from the provider).
    pub async fn refresh(&self) -> Result<SandboxInfo> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        Ok(run(async move {
            Ok(match &backend {
                Backend::Embedded(rt) => rt.record(&name).await?,
                Backend::Daemon(d) => d.get(&name).await?,
            })
        })
        .await?
        .into())
    }

    /// Attaches to cua-spacesd inside the sandbox (the `env` service or
    /// guest port 3211). Fails with `SpacesdNotAvailable` when none
    /// answers; sandbox lifecycle never depends on it.
    pub async fn spacesd(&self, probe_timeout_ms: Option<u32>) -> Result<Arc<SpacesdClient>> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        let location = self.info.location.clone();
        let timeout = probe_timeout_ms.map(super::millis);
        run(async move {
            match &backend {
                Backend::Embedded(rt) => {
                    let a = rt.env(&name, timeout).await?;
                    Ok(Arc::new(
                        SpacesdClient::new(a.client, a.ws_headers).at(&location),
                    ))
                }
                Backend::Daemon(d) => {
                    let ep = d.env_endpoint(&name, timeout).await?;
                    let mut o = cua_spacesd_client::ConnectOptions::parse(&ep.url)?
                        .transport(cua_spacesd_client::TransportPreference::Native)
                        .probe(false);
                    o.token = Some(ep.token.clone());
                    let client = cua_spacesd_client::SpacesdClient::connect(o).await?;
                    Ok(Arc::new(
                        SpacesdClient::new(
                            client,
                            vec![("authorization".into(), format!("Bearer {}", ep.token))],
                        )
                        .at(&location),
                    ))
                }
            }
        })
        .await
    }

    /// A browser link to this sandbox's desktop in the cua-spacesd HTML5
    /// viewer (`/viewer` on the `env` service): video, audio, input,
    /// clipboard, file drop and folder sharing, in any modern browser. The
    /// link carries a scoped viewer ticket, never the sandbox token. Needs
    /// cua-spacesd in the sandbox.
    #[uniffi::method(default(options = None))]
    pub async fn viewer_url(&self, options: Option<ViewerOptions>) -> Result<ViewerLink> {
        let started = std::time::Instant::now();
        let r: Result<ViewerLink> = async move {
            let o = options.unwrap_or_default();
            let ttl = o.ttl_seconds.unwrap_or(3600);
            if !(60..=86_400).contains(&ttl) {
                return Err(CuaError::InvalidArgument(
                    "ttl_seconds must be between 60 and 86400".into(),
                ));
            }
            let guest = self.spacesd(None).await?;
            let base = self.service("env".into())?.url().await?;
            run(async move {
                use cua_spacesd_client::pb;
                let files_root = if o.view_only {
                    String::new()
                } else {
                    o.files_root.unwrap_or_else(|| "~".into())
                };
                let minted = guest
                    .client
                    .system()
                    .create_viewer_ticket(pb::CreateViewerTicketRequest {
                        ttl: Some(cua_proto::wkt::Duration {
                            seconds: i64::from(ttl),
                            nanos: 0,
                        }),
                        policy: if o.view_only {
                            pb::SessionPolicy::ViewOnly
                        } else {
                            pb::SessionPolicy::AllowActivation
                        } as i32,
                        clipboard: o.clipboard && !o.view_only,
                        files_root,
                        audio_uplink: o.microphone && !o.view_only,
                        principal: None,
                    })
                    .await
                    .map_err(cua_spacesd_client::Error::from)?
                    .into_inner();
                Ok(ViewerLink {
                    url: format!("{}{}", base.trim_end_matches('/'), minted.viewer_path),
                    expires_at_unix: minted.expires_at.map(|t| t.seconds).unwrap_or_default(),
                })
            })
            .await
        }
        .await;
        super::telemetry::api("sandbox.viewer_url", started, &r);
        r
    }

    /// Coding agents inside this sandbox (needs cua-spacesd): run a harness
    /// over ACP, stream normalized events, follow up, interrupt, collect
    /// results; runs outlive this handle.
    pub async fn agents(&self) -> Result<Arc<super::Agents>> {
        let guest = self.spacesd(None).await?;
        super::Agents::over(guest.client.clone(), &self.info.location).await
    }

    /// A named service (for example `"server"` or `"env"`).
    pub fn service(&self, name: String) -> Result<Arc<Service>> {
        if !self.info.services.contains_key(&name) && !self.info.endpoints.contains_key(&name) {
            // Direct and local sandboxes accept declared services only.
            if !self.info.services.is_empty() {
                return Err(CuaError::NotFound(format!(
                    "sandbox {} has no service {name:?} (known: {:?})",
                    self.info.name,
                    self.info.services.keys().collect::<Vec<_>>()
                )));
            }
        }
        Ok(Arc::new(Service {
            backend: self.backend.clone(),
            sandbox: self.info.id.clone(),
            name,
        }))
    }

    /// Where the MCP server behind `service` is (URL of its endpoint at
    /// `path`, default `/mcp`, plus the headers every request needs), for
    /// any MCP client. Embedded: the service route itself (loopback).
    /// Daemon: the daemon's streaming passthrough with its loopback bearer.
    #[uniffi::method(default(path = None))]
    pub async fn mcp_config(
        &self,
        service: String,
        path: Option<String>,
    ) -> Result<super::McpConfig> {
        self.service(service.clone())?.mcp_config(path).await
    }

    /// An MCP client (the official Rust SDK) for the MCP server behind
    /// `service` at `path` (default `/mcp`).
    #[uniffi::method(default(path = None))]
    pub async fn mcp(
        &self,
        service: String,
        path: Option<String>,
    ) -> Result<Arc<super::McpClient>> {
        self.service(service)?.mcp(path).await
    }

    /// A shareable URL for `service` that stops working after `ttl_seconds`
    /// (60 s to 24 h, default 1 h): a loopback URL with its own token, served
    /// by the cua daemon (started if needed; `CUA_BIN` names the CLI).
    #[uniffi::method(default(ttl_seconds = None, label = None))]
    pub async fn public_url(
        &self,
        service: String,
        ttl_seconds: Option<u32>,
        label: Option<String>,
    ) -> Result<PublicUrl> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        let ttl = ttl_seconds.map(super::secs);
        run(async move {
            let u = match &backend {
                Backend::Embedded(rt) => rt.public_url(&name, &service, ttl, label).await?,
                Backend::Daemon(d) => d.public_url(&name, &service, ttl, label).await?,
            };
            Ok(u.into())
        })
        .await
    }

    /// Revokes a URL from `public_url`.
    pub async fn revoke_public_url(&self, id: String) -> Result<()> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        run(async move {
            match &backend {
                Backend::Embedded(rt) => Ok(rt.revoke_public_url(&name, &id).await?),
                Backend::Daemon(d) => Ok(d.revoke_public_url(&name, &id).await?),
            }
        })
        .await
    }

    /// Forwards a loopback port to guest `port`: a TCP forward locally (and
    /// over cua-spacesd's tunnel when the image has it). `url()` is a
    /// loopback URL.
    pub async fn forward(&self, port: u16) -> Result<Arc<PortForward>> {
        let started = std::time::Instant::now();
        let r: Result<Arc<PortForward>> = async move {
            let backend = self.backend.clone();
            let name = self.info.id.clone();
            let info = run({
                let backend = backend.clone();
                async move {
                    Ok(match &backend {
                        Backend::Embedded(rt) => rt.forward(&name, port).await?,
                        Backend::Daemon(d) => d.forward(&name, port).await?,
                    })
                }
            })
            .await?;
            Ok(Arc::new(PortForward {
                backend,
                info,
                closed: std::sync::atomic::AtomicBool::new(false),
            }))
        }
        .await;
        super::telemetry::api("sandbox.forward", started, &r);
        r
    }

    /// Waits until every probe passes.
    pub async fn wait_ready(&self, probes: Vec<ReadinessProbe>, timeout_ms: u32) -> Result<()> {
        let probes = probes
            .iter()
            .map(|p| p.resolve(&self.info.services))
            .collect::<Result<Vec<_>>>()?;
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        let t = super::millis(timeout_ms);
        run(async move {
            match &backend {
                Backend::Embedded(rt) => Ok(rt.wait_ready(&name, &probes, t).await?),
                Backend::Daemon(d) => Ok(d.wait_ready(&name, &probes, t).await?),
            }
        })
        .await
    }

    /// Extends the sandbox's lease by `seconds`, for a provider that has one.
    pub async fn keep_alive(&self, seconds: u32) -> Result<()> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        let d = super::secs(seconds);
        run(async move {
            match &backend {
                Backend::Embedded(rt) => Ok(rt.keep_alive(&name, d).await?),
                Backend::Daemon(c) => Ok(c.keep_alive(&name, d).await?),
            }
        })
        .await
    }

    /// Suspends.
    pub async fn suspend(&self) -> Result<()> {
        self.lifecycle(Op::Suspend).await
    }

    /// Resumes.
    pub async fn resume(&self) -> Result<()> {
        self.lifecycle(Op::Resume).await
    }

    /// Restarts.
    pub async fn restart(&self) -> Result<()> {
        self.lifecycle(Op::Restart).await
    }

    /// Deletes (local: removes it; direct: forgets it; your cloud: deletes
    /// the machine).
    pub async fn delete(&self) -> Result<()> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        let r = run(async move { delete(&backend, &name).await }).await;
        super::telemetry::sandbox_deleted(&self.info.location, &r);
        r
    }

    /// Opens a media session and returns a loopback WebSocket bridge for a
    /// webview (daemon mode). `open_media_json` is a
    /// `cua.env.v1.OpenMediaRequest` in proto3 JSON (`None`: primary display).
    pub async fn open_media_bridge(&self, open_media_json: Option<String>) -> Result<MediaBridge> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        run(async move {
            match &backend {
                Backend::Daemon(d) => {
                    let r = d.open_media_bridge(&name, open_media_json).await?;
                    Ok(MediaBridge {
                        ws_url: r.ws_url,
                        ticket: r.ticket,
                        open_media_response_json: r.open_media_response_json,
                    })
                }
                Backend::Embedded(_) => Err(CuaError::Unsupported(
                    "media bridges are served by `cua daemon`; use Cua.connect, or \
                     SpacesdClient.open_media in-process"
                        .into(),
                )),
            }
        })
        .await
    }
}

enum Op {
    Suspend,
    Resume,
    Restart,
}

impl Sandbox {
    async fn lifecycle(&self, op: Op) -> Result<()> {
        let backend = self.backend.clone();
        let name = self.info.id.clone();
        run(async move {
            match (&backend, op) {
                (Backend::Embedded(rt), Op::Suspend) => Ok(rt.suspend(&name).await?),
                (Backend::Embedded(rt), Op::Resume) => Ok(rt.resume(&name).await?),
                (Backend::Embedded(rt), Op::Restart) => Ok(rt.restart(&name).await?),
                (Backend::Daemon(d), Op::Suspend) => Ok(d.suspend(&name).await?),
                (Backend::Daemon(d), Op::Resume) => Ok(d.resume(&name).await?),
                (Backend::Daemon(d), Op::Restart) => Ok(d.restart(&name).await?),
            }
        })
        .await
    }
}

/// The guest display of a sandbox without cua-spacesd
/// (`Sandbox.guest_display`). An object, not a record, so no binding's
/// default string form (repr, str, description, toString, Debug) can show
/// the VNC password: `url()` is masked, and only the explicit
/// `url_with_password()` returns it.
#[derive(uniffi::Object)]
pub struct GuestDisplay {
    inner: cua_sandbox_core::GuestDisplay,
}

impl std::fmt::Debug for GuestDisplay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // cua_sandbox_core::GuestDisplay's Debug is masked.
        self.inner.fmt(f)
    }
}

impl std::fmt::Display for GuestDisplay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.inner.redacted_url())
    }
}

impl From<cua_sandbox_core::GuestDisplay> for GuestDisplay {
    fn from(inner: cua_sandbox_core::GuestDisplay) -> Self {
        GuestDisplay { inner }
    }
}

#[uniffi::export]
impl GuestDisplay {
    /// The display URL (`vnc://HOST:PORT`) with any password masked as `****`.
    /// Safe to print and log.
    pub fn url(&self) -> String {
        self.inner.redacted_url()
    }

    /// SENSITIVE: the display URL with the VNC password
    /// (`vnc://:PASSWORD@HOST:PORT`), for handing to a VNC client. Never
    /// print or log it.
    pub fn url_with_password(&self) -> String {
        self.inner.url.clone()
    }

    /// How the display is reached (`vnc`).
    pub fn via(&self) -> String {
        self.inner.via.clone()
    }

    /// A host command that opens a viewer on it (`lume attach <vm>`);
    /// empty when there is none. It handles the password itself.
    pub fn open_command(&self) -> Vec<String> {
        self.inner.open_command.clone().unwrap_or_default()
    }
}

fn core_err(e: cua_sandbox_core::Error) -> CuaError {
    cua_daemon::Error::from(e).into()
}

/// The agentless fallback in the daemon topology: the daemon runs on this
/// machine, and Lume's `lume ssh` and VNC endpoint are host facilities, so
/// the client reaches them itself for a local sandbox.
fn daemon_local(info: &SandboxInfo, op: &str) -> Result<cua_daemon::local::VmmLocal> {
    if info.location != "local" {
        return Err(CuaError::Unsupported(format!(
            "{op} without cua-spacesd is only available for local Lume sandboxes \
             ({} is {})",
            info.name, info.location
        )));
    }
    Ok(cua_daemon::local::VmmLocal::default())
}

/// Agentless access for sandboxes without cua-spacesd (Rust hosts; the
/// exported methods are below).
impl Sandbox {
    /// `Sandbox.guest_sh`, forwarding output to `sink` as it arrives;
    /// returns the exit code.
    pub async fn guest_sh_streaming(
        &self,
        line: String,
        timeout_ms: Option<u32>,
        sink: tokio::sync::mpsc::Sender<cua_sandbox_core::GuestOutput>,
    ) -> Result<i64> {
        use cua_sandbox_core::LocalRuntime as _;
        let backend = self.backend.clone();
        let info = self.info.clone();
        let timeout = Some(super::millis(timeout_ms.unwrap_or(120_000)));
        run(async move {
            match &backend {
                Backend::Embedded(rt) => rt
                    .handle(&info.id)
                    .await?
                    .guest_exec(&line, timeout, sink)
                    .await
                    .map_err(core_err),
                Backend::Daemon(_) => daemon_local(&info, "exec")?
                    .guest_exec(&info.name, &line, timeout, sink)
                    .await
                    .map_err(|e| core_err(e.into())),
            }
        })
        .await
    }
}

#[uniffi::export]
impl Sandbox {
    /// Whether this sandbox has no cua-spacesd: it declares no `env`
    /// service, or its image says it does not carry one. `spacesd()` fails
    /// for these; `guest_sh`, `guest_screenshot` and `guest_display` reach a
    /// local Lume sandbox without it.
    pub fn lacks_spacesd(&self) -> bool {
        !self.info.services.contains_key("env")
            || self.info.image_info.as_ref().and_then(|i| i.spacesd) == Some(false)
    }

    /// Runs `line` with `/bin/sh -c` in the guest without cua-spacesd, to
    /// completion (default timeout 120 s). Local macOS Lume sandboxes only:
    /// over `lume ssh`, stdout and stderr kept apart, no stdin. Others fail
    /// with `Unsupported`.
    #[uniffi::method(default(timeout_ms = None))]
    pub async fn guest_sh(&self, line: String, timeout_ms: Option<u32>) -> Result<ProcessOutput> {
        let (tx, mut rx) = tokio::sync::mpsc::channel(64);
        let run = self.guest_sh_streaming(line, timeout_ms, tx);
        let collect = async {
            let (mut stdout, mut stderr) = (Vec::new(), Vec::new());
            while let Some(c) = rx.recv().await {
                match c {
                    cua_sandbox_core::GuestOutput::Stdout(b) => stdout.extend(b),
                    cua_sandbox_core::GuestOutput::Stderr(b) => stderr.extend(b),
                }
            }
            (stdout, stderr)
        };
        let (code, (stdout, stderr)) = tokio::join!(run, collect);
        let code = code?;
        Ok(ProcessOutput {
            exit: ExitInfo {
                success: code == 0,
                code: i32::try_from(code).ok(),
                signal: None,
                timed_out: false,
                error: None,
            },
            stdout,
            stderr,
            pty: vec![],
        })
    }

    /// Captures the guest framebuffer as PNG without cua-spacesd. Local
    /// Lume sandboxes only: over the VM's VNC endpoint.
    pub async fn guest_screenshot(&self) -> Result<Screenshot> {
        use cua_sandbox_core::LocalRuntime as _;
        let backend = self.backend.clone();
        let info = self.info.clone();
        let s = run(async move {
            match &backend {
                Backend::Embedded(rt) => rt
                    .handle(&info.id)
                    .await?
                    .guest_screenshot()
                    .await
                    .map_err(core_err),
                Backend::Daemon(_) => daemon_local(&info, "screenshots")?
                    .guest_screenshot(&info.name)
                    .await
                    .map_err(|e| core_err(e.into())),
            }
        })
        .await?;
        Ok(Screenshot {
            image: s.png,
            format: ImageFormat::Png,
            width: s.width,
            height: s.height,
            scale: 1.0,
            screenshot_id: String::new(),
        })
    }

    /// The guest display without cua-spacesd: the VM's VNC endpoint and a
    /// host command that opens it (`lume attach`). Local Lume sandboxes
    /// only.
    pub async fn guest_display(&self) -> Result<Arc<GuestDisplay>> {
        use cua_sandbox_core::LocalRuntime as _;
        let backend = self.backend.clone();
        let info = self.info.clone();
        run(async move {
            match &backend {
                Backend::Embedded(rt) => rt
                    .handle(&info.id)
                    .await?
                    .guest_display()
                    .await
                    .map(|d| Arc::new(d.into()))
                    .map_err(core_err),
                Backend::Daemon(_) => daemon_local(&info, "a display")?
                    .guest_display(&info.name)
                    .await
                    .map(|d| Arc::new(d.into()))
                    .map_err(|e| core_err(e.into())),
            }
        })
        .await
    }
}

/// A named service of a sandbox.
#[derive(uniffi::Object)]
pub struct Service {
    backend: Backend,
    sandbox: String,
    name: String,
}

#[uniffi::export]
impl Service {
    /// Service name.
    pub fn name(&self) -> String {
        self.name.clone()
    }

    /// A URL for the service usable from this machine with no credentials
    /// (no trailing slash): the published loopback port locally.
    pub async fn url(&self) -> Result<String> {
        let backend = self.backend.clone();
        let (sb, svc) = (self.sandbox.clone(), self.name.clone());
        run(async move {
            match &backend {
                Backend::Embedded(rt) => Ok(rt.service_url(&sb, &svc).await?),
                Backend::Daemon(d) => Ok(d.service_url(&sb, &svc).await?),
            }
        })
        .await
    }

    /// A shareable URL for this service that stops working after
    /// `ttl_seconds` (60 s to 24 h, default 1 h): the same as
    /// `Sandbox.public_url(name, ...)`: a loopback URL with its own token,
    /// served by the cua daemon.
    #[uniffi::method(default(ttl_seconds = None, label = None))]
    pub async fn public_url(
        &self,
        ttl_seconds: Option<u32>,
        label: Option<String>,
    ) -> Result<PublicUrl> {
        let backend = self.backend.clone();
        let (sb, svc) = (self.sandbox.clone(), self.name.clone());
        let ttl = ttl_seconds.map(super::secs);
        run(async move {
            let u = match &backend {
                Backend::Embedded(rt) => rt.public_url(&sb, &svc, ttl, label).await?,
                Backend::Daemon(d) => d.public_url(&sb, &svc, ttl, label).await?,
            };
            Ok(u.into())
        })
        .await
    }

    /// Where this service is reachable from this process: base URL plus
    /// the headers every request needs. Any HTTP client can use it (SSE,
    /// long-lived streams and every method pass through unchanged).
    pub async fn endpoint(&self) -> Result<ServiceEndpoint> {
        let (backend, sb, svc) = (
            self.backend.clone(),
            self.sandbox.clone(),
            self.name.clone(),
        );
        let e = run(async move { super::mcp::service_endpoint(&backend, &sb, &svc).await }).await?;
        Ok(ServiceEndpoint {
            url: e.url,
            headers: e
                .headers
                .into_iter()
                .map(|(name, value)| HttpHeader { name, value })
                .collect(),
        })
    }

    /// The MCP endpoint of this service at `path` (default `/mcp`).
    #[uniffi::method(default(path = None))]
    pub async fn mcp_config(&self, path: Option<String>) -> Result<super::McpConfig> {
        let (backend, sb, svc) = (
            self.backend.clone(),
            self.sandbox.clone(),
            self.name.clone(),
        );
        run(async move {
            let e = super::mcp::service_endpoint(&backend, &sb, &svc).await?;
            Ok(cua_sandbox_core::McpConfig::of(&e, path.as_deref()).into())
        })
        .await
    }

    /// An MCP client (the official Rust SDK) for this service's endpoint at
    /// `path` (default `/mcp`).
    #[uniffi::method(default(path = None))]
    pub async fn mcp(&self, path: Option<String>) -> Result<Arc<super::McpClient>> {
        let (backend, sb, svc) = (
            self.backend.clone(),
            self.sandbox.clone(),
            self.name.clone(),
        );
        run(async move {
            let e = super::mcp::service_endpoint(&backend, &sb, &svc).await?;
            super::McpClient::connect(cua_sandbox_core::McpConfig::of(&e, path.as_deref())).await
        })
        .await
    }

    /// One HTTP request to `path` on the service. Credentials are attached by
    /// the runtime. `headers` are sent as given (for example `content-type`,
    /// or `accept` and `mcp-session-id` for MCP).
    #[uniffi::method(default(headers = None))]
    pub async fn request(
        &self,
        method: String,
        path: String,
        body: Option<Vec<u8>>,
        timeout_ms: Option<u32>,
        headers: Option<Vec<HttpHeader>>,
    ) -> Result<HttpResponse> {
        let backend = self.backend.clone();
        let (sb, svc) = (self.sandbox.clone(), self.name.clone());
        let t = ms(timeout_ms, 30_000);
        let headers: Vec<(String, String)> = headers
            .unwrap_or_default()
            .into_iter()
            .map(|h| (h.name, h.value))
            .collect();
        run(async move {
            match &backend {
                Backend::Embedded(rt) => {
                    let r = rt
                        .service_request(&sb, &svc, &method, &path, &headers, body, t)
                        .await?;
                    Ok(HttpResponse {
                        status: r.status,
                        headers: r
                            .headers
                            .into_iter()
                            .map(|(name, value)| HttpHeader { name, value })
                            .collect(),
                        body: r.body,
                    })
                }
                Backend::Daemon(d) => {
                    let r = d
                        .service_request(&sb, &svc, &method, &path, &headers, body, t)
                        .await?;
                    Ok(HttpResponse {
                        status: r.status,
                        headers: r
                            .headers
                            .into_iter()
                            .map(|(name, value)| HttpHeader { name, value })
                            .collect(),
                        body: r.body,
                    })
                }
            }
        })
        .await
    }
}

/// An active port forward. Closed on `close()` or when dropped.
#[derive(uniffi::Object)]
pub struct PortForward {
    backend: Backend,
    info: cua_daemon::ForwardInfo,
    closed: std::sync::atomic::AtomicBool,
}

#[uniffi::export]
impl PortForward {
    /// Guest port.
    pub fn guest_port(&self) -> u16 {
        self.info.guest_port
    }

    /// Loopback `host:port` accepting connections (local/direct).
    pub fn local_addr(&self) -> Option<String> {
        self.info.local_addr.clone()
    }

    /// URL to use (a loopback URL).
    pub fn url(&self) -> Option<String> {
        self.info.url.clone()
    }

    /// Stops the forward.
    pub async fn close(&self) -> Result<()> {
        if self.closed.swap(true, std::sync::atomic::Ordering::SeqCst) || self.info.id.is_empty() {
            return Ok(());
        }
        let backend = self.backend.clone();
        let id = self.info.id.clone();
        run(async move {
            match &backend {
                Backend::Embedded(rt) => Ok(rt.close_forward(&id)?),
                Backend::Daemon(d) => Ok(d.close_forward(&id).await?),
            }
        })
        .await
    }
}

impl Drop for PortForward {
    fn drop(&mut self) {
        if self.closed.swap(true, std::sync::atomic::Ordering::SeqCst) || self.info.id.is_empty() {
            return;
        }
        let backend = self.backend.clone();
        let id = self.info.id.clone();
        super::runtime().spawn(async move {
            let _ = match &backend {
                Backend::Embedded(rt) => rt.close_forward(&id),
                Backend::Daemon(d) => d.close_forward(&id).await,
            };
        });
    }
}

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

    #[test]
    fn service_probes_resolve_against_declared_services() {
        let services: HashMap<String, u16> = [("mcp".to_string(), 8765u16)].into();
        assert_eq!(
            ReadinessProbe::http("mcp", "health")
                .resolve(&services)
                .unwrap(),
            Probe::Http {
                port: 8765,
                path: "/health".into(),
                status: None
            }
        );
        assert_eq!(
            ReadinessProbe::tcp("mcp").resolve(&services).unwrap(),
            Probe::Tcp(8765)
        );
        assert_eq!(
            ReadinessProbe::tcp("env").resolve(&services).unwrap(),
            Probe::Tcp(3211),
            "env defaults to the spacesd port"
        );
        assert!(ReadinessProbe::tcp("nope").resolve(&services).is_err());
        assert!(ReadinessProbe::default().resolve(&services).is_err());
        let by_port = ReadinessProbe {
            port: 22,
            ..Default::default()
        };
        assert_eq!(by_port.resolve(&services).unwrap(), Probe::Tcp(22));
    }

    /// With no `on`, the location is the user default (local unless
    /// configured). Runs with a private CUA_HOME and no default overrides in
    /// the environment.
    #[test]
    fn the_location_defaults_to_the_user_default() {
        use cua_sandbox_core::placement::{Kind, On, Runtime};
        let _env = super::super::test_env::EnvGuard::isolated();
        let o = SandboxCreateOptions::auto("python:3.12-slim");
        assert_eq!(o.placement().unwrap().on, On::Local);
        assert_eq!(SandboxCreateOptions::default().on, None);
        let r = o.to_request().unwrap();
        assert_eq!(r.location.as_deref(), Some("local"));
        assert_eq!(r.provider, Some(CoreProvider::Local));
        // Cua Cloud has ended.
        let e = SandboxCreateOptions::new("cloud", "x")
            .placement()
            .unwrap_err();
        assert_eq!(
            e.to_string(),
            format!("unsupported: {}", cua_sandbox_core::CLOUD_ENDED)
        );
        // direct:<addr> carries the address.
        let o = SandboxCreateOptions::new("direct:127.0.0.1:3211", "");
        let r = o.to_request().unwrap();
        assert_eq!(r.url.as_deref(), Some("127.0.0.1:3211"));
        assert_eq!(r.location.as_deref(), Some("direct:127.0.0.1:3211"));
        // kind and runtime go out resolved.
        let mut o = SandboxCreateOptions::new("local", "img");
        o.kind = Some("vm".into());
        let p = o.placement().unwrap();
        assert_eq!((p.kind, p.runtime), (Kind::Vm, Runtime::Auto));
        assert_eq!(o.to_request().unwrap().kind.as_deref(), Some("vm"));
    }

    #[test]
    fn invalid_placements_are_typed_and_list_the_valid_values() {
        let _env = super::super::test_env::EnvGuard::isolated();
        let mut o = SandboxCreateOptions::new("local", "img");
        o.runtime = Some("kubevirt".into());
        let e = o.placement().unwrap_err();
        let CuaError::InvalidPlacement(m) = &e else {
            panic!("{e:?}")
        };
        assert!(m.contains("valid runtime: auto"), "{m}");
        assert_eq!(e.variant(), "InvalidPlacement");
        let mut o = SandboxCreateOptions::new("local", "img");
        o.kind = Some("container".into());
        o.runtime = Some("lume".into());
        assert!(matches!(o.placement(), Err(CuaError::InvalidPlacement(_))));
        let o = SandboxCreateOptions::new("qemu", "img");
        let e = o.placement().unwrap_err();
        assert!(e.to_string().contains("--runtime qemu"), "{e}");
    }

    /// Precedence: explicit > env > config > built-in.
    #[test]
    fn user_defaults_apply_below_explicit_values() {
        use cua_sandbox_core::placement::On;
        let env = super::super::test_env::EnvGuard::isolated();
        let mut s = cua_sandbox_core::settings::Settings::load().unwrap();
        s.set(
            cua_sandbox_core::settings::key("default.on").unwrap(),
            "aws",
        )
        .unwrap();
        let o = SandboxCreateOptions::auto("img");
        let p = o.placement().unwrap();
        assert_eq!(p.on, On::Provider("aws".into()));
        assert!(matches!(
            p.on_source,
            cua_sandbox_core::settings::Source::Config(_)
        ));
        env.set("CUA_DEFAULT_ON", "local");
        assert_eq!(o.placement().unwrap().on, On::Local);
        let o = SandboxCreateOptions::new("local", "img");
        assert_eq!(o.placement().unwrap().on, On::Local);
        // Cua Cloud has ended.
        let o = SandboxCreateOptions::new("cloud", "img");
        assert!(matches!(o.placement(), Err(CuaError::Unsupported(_))));
    }

    #[test]
    fn on_words_pick_the_provider_and_the_location() {
        let mut o = SandboxCreateOptions::auto("ghcr.io/trycua/linux:24.04");
        o.on = Some("e2b".into());
        let r = o.to_request().unwrap();
        assert_eq!(r.provider, Some(CoreProvider::Contrib));
        assert_eq!(r.location.as_deref(), Some("e2b"));
        o.on = Some("cloud".into());
        assert!(matches!(o.to_request(), Err(CuaError::Unsupported(_))));
        o.on = Some("direct:127.0.0.1:3211".into());
        assert_eq!(
            o.to_request().unwrap().url.as_deref(),
            Some("127.0.0.1:3211")
        );
        o.on = Some("nosuchcloud".into());
        let err = o.to_request().unwrap_err().to_string();
        assert!(err.contains("daytona"), "{err}");
    }

    #[test]
    fn phases_are_portable() {
        assert_eq!(
            SandboxPhase::of(SandboxStatus::Running),
            SandboxPhase::Ready
        );
        assert_eq!(
            SandboxPhase::of(SandboxStatus::Suspended),
            SandboxPhase::Stopped
        );
        assert_eq!(
            SandboxPhase::of(SandboxStatus::Provisioning),
            SandboxPhase::Provisioning
        );
        assert_eq!(
            SandboxPhase::of(SandboxStatus::Unknown),
            SandboxPhase::Starting
        );
    }
}

/// A parsed sandbox ref.
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct SandboxRefParts {
    /// `local`, `cloud`, `direct`, `relay` or a contrib provider (`e2b`);
    /// `None` for a bare name.
    pub location: Option<String>,
    /// The name, `host:port` or relay machine id.
    pub name: String,
    /// The canonical form (`location:name`, or the bare name).
    pub id: String,
}

/// Every location word `on=` accepts, in display order: `local`, `cloud`,
/// then the contrib providers (`e2b`, `daytona`, `modal`, ...) and your own
/// clouds (`aws`, `gcp`). A word is listed whether or not this build
/// includes that provider (see [`contrib_providers_built`]).
#[uniffi::export]
pub fn sandbox_locations() -> Vec<String> {
    // Cua Cloud (`cloud`) has ended and is no longer offered.
    let mut out: Vec<String> = ["local"]
        .into_iter()
        .chain(cua_sandbox_core::CONTRIB_LOCATIONS.iter().copied())
        .map(str::to_string)
        .collect();
    for w in cua_sandbox_core::CLOUD_LOCATIONS {
        if !out.iter().any(|o| o == w) {
            out.push((*w).to_string());
        }
    }
    out
}

/// The contrib providers this build includes (empty unless built with the
/// `contrib` feature).
#[uniffi::export]
pub fn contrib_providers_built() -> Vec<String> {
    cua_daemon::contrib_provider_names()
}

/// Parses a sandbox ref: `local:<name>`, `cloud:<name>`,
/// `direct:<host:port>`, `relay:<machine-id>`, a legacy spelling
/// (`space://cloud/<name>`, `url:<addr>`, a URL), or a bare name.
#[uniffi::export]
pub fn parse_sandbox_ref(input: String) -> Result<SandboxRefParts> {
    let r = cua_sandbox_core::SandboxRef::parse(&input)?;
    Ok(SandboxRefParts {
        location: r.location_word().map(str::to_string),
        name: r.name().to_string(),
        id: r.to_string(),
    })
}

/// Qualifies `name` for a lookup: `local = true` narrows a bare name to
/// `local:<name>`, `false` to `cloud:<name>`, `None` keeps it (a bare name
/// is then searched across locations). A qualified ref elsewhere than
/// `local` asks is an `InvalidArgument`.
#[uniffi::export(default(local = None))]
pub fn qualify_sandbox_ref(name: String, local: Option<bool>) -> Result<String> {
    use cua_sandbox_core::{Location, SandboxRef};
    let location = local.map(|l| if l { Location::Local } else { Location::Cloud });
    Ok(SandboxRef::parse(&name)?.narrow(location)?.to_string())
}

/// The qualified candidates an `AmbiguousSandbox` message lists (empty
/// for any other message).
#[uniffi::export]
pub fn ambiguous_sandbox_candidates(message: String) -> Vec<String> {
    message
        .rsplit_once("use one of: ")
        .map(|(_, list)| {
            list.split(',')
                .map(str::trim)
                .filter(|c| !c.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}