tensorlake 0.5.145

A Rust SDK for interacting with Tensorlake Cloud APIs.
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
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};

#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SandboxLogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
    Fatal,
}

impl SandboxLogLevel {
    pub fn as_i8(self) -> i8 {
        match self {
            SandboxLogLevel::Trace => 1,
            SandboxLogLevel::Debug => 2,
            SandboxLogLevel::Info => 3,
            SandboxLogLevel::Warn => 4,
            SandboxLogLevel::Error => 5,
            SandboxLogLevel::Fatal => 6,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxLogSignal {
    pub timestamp: u64,
    pub uuid: uuid::Uuid,
    pub namespace: String,
    pub application: String,
    #[serde(default, rename = "sandboxId")]
    pub sandbox_id: Option<String>,
    #[serde(default, rename = "resourceAttributes")]
    pub resource_attributes: Vec<(String, String)>,
    pub body: String,
    #[serde(rename = "logAttributes")]
    pub log_attributes: String,
    #[serde(default)]
    pub allocations: Vec<String>,
    #[serde(default, rename = "functionRuns")]
    pub function_runs: Vec<String>,
    #[serde(default)]
    pub level: Option<i8>,
    #[serde(default)]
    pub retention: Option<i8>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxLogsResponse {
    pub logs: Vec<SandboxLogSignal>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_token: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxProcessLogFilter {
    #[serde(rename = "processId")]
    pub process_id: String,
    #[serde(rename = "processPid")]
    pub process_pid: String,
    #[serde(rename = "processCommand")]
    pub process_command: String,
    #[serde(rename = "processManagedId")]
    pub process_managed_id: String,
    #[serde(rename = "processManagedName")]
    pub process_managed_name: String,
    #[serde(rename = "firstSeen")]
    pub first_seen: i64,
    #[serde(rename = "lastSeen")]
    pub last_seen: i64,
    #[serde(rename = "logCount")]
    pub log_count: u64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxProcessLogFiltersResponse {
    pub processes: Vec<SandboxProcessLogFilter>,
}

#[derive(Builder, Clone, Debug, Default, Deserialize)]
pub struct GetSandboxLogsRequest {
    #[builder(setter(into))]
    pub sandbox_id: String,
    #[builder(default, setter(into))]
    pub levels: Vec<SandboxLogLevel>,
    #[builder(default, setter(into))]
    pub process_ids: Vec<String>,
    #[builder(default, setter(into, strip_option))]
    pub next_token: Option<String>,
    #[builder(default, setter(strip_option))]
    pub head: Option<usize>,
    #[builder(default, setter(strip_option))]
    pub tail: Option<usize>,
    #[builder(default, setter(into, strip_option))]
    pub body: Option<String>,
}

impl GetSandboxLogsRequest {
    pub fn builder() -> GetSandboxLogsRequestBuilder {
        GetSandboxLogsRequestBuilder::default()
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ContainerResourcesInfo {
    pub cpus: f64,
    pub memory_mb: i64,
    pub disk_mb: i64,
}

/// GPU models supported by the sandbox scheduler.
///
/// The serialized values are the canonical names used by Server and the
/// executor API.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum GpuModel {
    #[serde(rename = "A100-40GB")]
    A10040Gb,
    #[serde(rename = "A100-80GB")]
    A10080Gb,
    #[serde(rename = "H100")]
    H100,
    #[serde(rename = "T4")]
    T4,
    #[serde(rename = "A6000")]
    A6000,
    #[serde(rename = "A10")]
    A10,
    #[serde(rename = "RTX-PRO-6000")]
    RtxPro6000,
    #[serde(rename = "L40")]
    L40,
}

impl GpuModel {
    pub const ALL: [Self; 8] = [
        Self::A10040Gb,
        Self::A10080Gb,
        Self::H100,
        Self::T4,
        Self::A6000,
        Self::A10,
        Self::RtxPro6000,
        Self::L40,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::A10040Gb => "A100-40GB",
            Self::A10080Gb => "A100-80GB",
            Self::H100 => "H100",
            Self::T4 => "T4",
            Self::A6000 => "A6000",
            Self::A10 => "A10",
            Self::RtxPro6000 => "RTX-PRO-6000",
            Self::L40 => "L40",
        }
    }
}

impl fmt::Display for GpuModel {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for GpuModel {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::ALL
            .into_iter()
            .find(|model| model.as_str() == value)
            .ok_or_else(|| format!("unsupported GPU model: {value}"))
    }
}

/// A homogeneous GPU allocation for a sandbox.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct GpuRequest {
    pub count: u32,
    pub model: GpuModel,
}

impl GpuRequest {
    pub fn new(model: GpuModel, count: u32) -> Result<Self, String> {
        if count == 0 {
            return Err("GPU count must be positive".to_string());
        }
        Ok(Self { count, model })
    }
}

/// GPU resource request used by the existing sandbox request model.
///
/// `model` remains a string for Rust source compatibility. New code can build
/// a typed [`GpuRequest`] and convert it with [`From`].
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct GPUResources {
    pub count: u32,
    pub model: String,
}

impl From<GpuRequest> for GPUResources {
    fn from(request: GpuRequest) -> Self {
        Self {
            count: request.count,
            model: request.model.to_string(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSandboxResources {
    #[serde(
        default = "unspecified_cpus",
        skip_serializing_if = "is_unspecified_f64"
    )]
    pub cpus: f64,
    #[serde(
        default = "unspecified_memory_mb",
        skip_serializing_if = "is_unspecified_i64"
    )]
    pub memory_mb: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disk_mb: Option<u64>,
    /// GPU allocation. The server accepts GPU sandboxes only with a CAS
    /// (`content_addressed_streaming_v1`) image; omitting `image` asks the
    /// server to select its configured GPU default.
    #[serde(rename = "gpus", skip_serializing_if = "Option::is_none")]
    pub gpu_configs: Option<Vec<GPUResources>>,
}

fn unspecified_cpus() -> f64 {
    -1.0
}

fn unspecified_memory_mb() -> i64 {
    -1
}

fn is_unspecified_f64(value: &f64) -> bool {
    *value == unspecified_cpus()
}

fn is_unspecified_i64(value: &i64) -> bool {
    *value == unspecified_memory_mb()
}

impl Default for CreateSandboxResources {
    fn default() -> Self {
        Self {
            cpus: unspecified_cpus(),
            memory_mb: unspecified_memory_mb(),
            disk_mb: None,
            gpu_configs: None,
        }
    }
}

impl CreateSandboxResources {
    fn is_empty(&self) -> bool {
        is_unspecified_f64(&self.cpus)
            && is_unspecified_i64(&self.memory_mb)
            && self.disk_mb.is_none()
            && self.gpu_configs.is_none()
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct NetworkConfig {
    #[serde(default = "default_allow_internet_access")]
    pub allow_internet_access: bool,
    #[serde(default)]
    pub allow_out: Vec<String>,
    #[serde(default)]
    pub deny_out: Vec<String>,
}

fn default_allow_internet_access() -> bool {
    true
}

/// One file system mounted into a sandbox at an absolute guest path.
///
/// `file_system_id` is the Artifact Storage file-system name created with
/// `tl fs create <name>` and `mount_path` is an absolute, unique guest path
/// (e.g. `/mnt/skills`).
///
/// `read_only` and `prefetch` are optional mount modes. They serialize only
/// when `true`: older servers deserialize mount bodies with
/// `deny_unknown_fields` and would reject an explicit `false`.
///
/// `snapshot_id` optionally pins the mount to a specific filesystem
/// snapshot. A pinned mount must also be `read_only` (the server rejects a
/// writable pin with HTTP 400). The field serializes only when set: older
/// servers reject mount bodies carrying unknown fields, so "unpinned" is
/// expressed by omission.
///
/// `owner` optionally presents the mounted files as owned by a guest user:
/// `NAME`, `UID`, `NAME:GROUP`, or `UID:GID` (e.g. `agent` or `1001:1001`),
/// resolved against the sandbox image's own user database when the mount
/// attaches. Unset means the image default (the baked `tl-user` account when
/// the image has one, otherwise root). The field serializes only when set,
/// for the same compatibility reason as the pin.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FileSystemMount {
    pub file_system_id: String,
    pub mount_path: String,
    /// Mount the file system read-only inside the guest.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub read_only: bool,
    /// Eagerly download the complete file system into the guest cache.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub prefetch: bool,
    /// Pin the mount to a specific filesystem snapshot (requires
    /// `read_only`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
    /// Present the mounted files as owned by this guest user spec.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSandboxRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    /// Resource overrides for the new sandbox. Snapshot restores may leave
    /// this empty to inherit the snapshot's CPU, memory, disk, and GPU allocation.
    #[serde(default, skip_serializing_if = "CreateSandboxResources::is_empty")]
    pub resources: CreateSandboxResources,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_secs: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<NetworkConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
    /// Optional name for the sandbox. Named sandboxes support suspend/resume.
    /// When absent the sandbox is ephemeral.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// File systems to mount into the sandbox at boot, each at its own
    /// absolute, unique guest mount path.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub file_systems: Vec<FileSystemMount>,
    /// `Some(false)` asks the server to answer as soon as the sandbox is
    /// durable (HTTP 202 with `state: pending`) instead of waiting for it to
    /// run. Unset or `Some(true)` is the blocking create. Omitted from the
    /// wire when unset so older servers keep accepting the body.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub wait: Option<bool>,
    /// Longest the sandbox may wait for capacity before the server fails it
    /// with reason `no_capacity`. `0` fails at once when it cannot be placed;
    /// unset (the default) waits indefinitely. Applies to capacity waits
    /// only, not to image pull or boot. A bound shorter than the fleet's boot
    /// time (up to 20 minutes on metal hosts) expires the very demand that
    /// made the autoscaler launch a host; 30 minutes or more is recommended
    /// for capacity waits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_pending_secs: Option<u64>,
}

/// Sandbox-specific state to apply while claiming a warm pool container.
///
/// Pool templates stay storage-neutral; these mounts belong only to the
/// sandbox created by the claim.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ClaimSandboxRequest {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub file_systems: Vec<FileSystemMount>,
}

/// Request body for detaching a file system from a running sandbox. The
/// mount path is sent in the body (rather than the URL) so its slashes don't
/// need URL-encoding.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DetachFileSystemRequest {
    pub mount_path: String,
}

/// Resource targets for a running Cloud Hypervisor sandbox. Names and numeric
/// types match create; values are optional to support partial updates.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ResizeSandboxResources {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpus: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_mb: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disk_mb: Option<u64>,
}

/// Latest resize operation. `SandboxInfo.resources` is the confirmed allocation,
/// including when a failed operation only partially converged.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxResourceResizeInfo {
    pub generation: u64,
    pub requested: ContainerResourcesInfo,
    pub status: String,
    #[serde(default)]
    pub error_message: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UpdateSandboxRequest {
    /// Standalone live resize; omitted dimensions retain their confirmed allocation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResizeSandboxResources>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_unauthenticated_access: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exposed_ports: Option<Vec<u16>>,
    /// Tri-state update of the running sandbox's egress network policy: omitted
    /// leaves it unchanged, `null` clears it to unrestricted egress, an object
    /// replaces the whole policy. The dataplane re-renders the live VM's
    /// firewall in one atomic swap with no enforcement gap.
    #[serde(default, skip_serializing_if = "NetworkPolicyUpdate::is_keep")]
    pub network: NetworkPolicyUpdate,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxPoolRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image: Option<String>,
    pub resources: CreateSandboxResources,
    #[serde(default)]
    pub timeout_secs: i64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_containers: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warm_containers: Option<i64>,
}

/// A pool creation request with an optional container network policy.
#[derive(Clone, Debug, PartialEq)]
pub struct CreateSandboxPoolRequest {
    pub pool: SandboxPoolRequest,
    pub network: Option<NetworkConfig>,
}

// These pool request wrappers intentionally implement their flat wire shape
// without `serde(flatten)`. When another workspace dependency enables
// serde_json's `arbitrary_precision` feature, flatten's intermediate content
// representation serializes nested floating-point values as private Number
// maps instead of JSON numbers.
impl Serialize for CreateSandboxPoolRequest {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct Wire<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            image: Option<&'a str>,
            resources: &'a CreateSandboxResources,
            timeout_secs: i64,
            #[serde(skip_serializing_if = "Option::is_none")]
            entrypoint: Option<&'a Vec<String>>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_containers: Option<i64>,
            #[serde(skip_serializing_if = "Option::is_none")]
            warm_containers: Option<i64>,
            #[serde(skip_serializing_if = "Option::is_none")]
            network: Option<&'a NetworkConfig>,
        }

        Wire {
            image: self.pool.image.as_deref(),
            resources: &self.pool.resources,
            timeout_secs: self.pool.timeout_secs,
            entrypoint: self.pool.entrypoint.as_ref(),
            max_containers: self.pool.max_containers,
            warm_containers: self.pool.warm_containers,
            network: self.network.as_ref(),
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for CreateSandboxPoolRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            image: Option<String>,
            resources: CreateSandboxResources,
            #[serde(default)]
            timeout_secs: i64,
            entrypoint: Option<Vec<String>>,
            max_containers: Option<i64>,
            warm_containers: Option<i64>,
            network: Option<NetworkConfig>,
        }

        let wire = Wire::deserialize(deserializer)?;
        Ok(Self {
            pool: SandboxPoolRequest {
                image: wire.image,
                resources: wire.resources,
                timeout_secs: wire.timeout_secs,
                entrypoint: wire.entrypoint,
                max_containers: wire.max_containers,
                warm_containers: wire.warm_containers,
            },
            network: wire.network,
        })
    }
}

/// What an update should do with a pool's or sandbox's network policy.
///
/// The three states are distinct on the wire: the field is omitted to keep the
/// current policy, sent as `null` to clear it, or sent as an object to replace
/// it. Shared by [`UpdateSandboxPoolRequest`] and [`UpdateSandboxRequest`].
#[derive(Clone, Debug, Default, PartialEq)]
pub enum NetworkPolicyUpdate {
    /// Leave the current network policy in place.
    #[default]
    Keep,
    /// Remove the network policy, leaving egress unrestricted.
    Clear,
    /// Replace the network policy.
    Set(NetworkConfig),
}

impl NetworkPolicyUpdate {
    pub fn is_keep(&self) -> bool {
        matches!(self, Self::Keep)
    }
}

impl Serialize for NetworkPolicyUpdate {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            // `Keep` is normally skipped by `skip_serializing_if`; if a caller
            // serializes it directly, `null` is the closest wire meaning.
            Self::Keep | Self::Clear => serializer.serialize_none(),
            Self::Set(policy) => serializer.serialize_some(policy),
        }
    }
}

impl<'de> Deserialize<'de> for NetworkPolicyUpdate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // Only reached when the key is present, so an absent field falls back
        // to `Default` (`Keep`) via `serde(default)` on the field.
        Ok(match Option::<NetworkConfig>::deserialize(deserializer)? {
            None => Self::Clear,
            Some(policy) => Self::Set(policy),
        })
    }
}

/// A pool update request carrying a tri-state network policy instruction.
#[derive(Clone, Debug, PartialEq)]
pub struct UpdateSandboxPoolRequest {
    pub pool: SandboxPoolRequest,
    pub network: NetworkPolicyUpdate,
}

impl Serialize for UpdateSandboxPoolRequest {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(Serialize)]
        struct Wire<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            image: Option<&'a str>,
            resources: &'a CreateSandboxResources,
            timeout_secs: i64,
            #[serde(skip_serializing_if = "Option::is_none")]
            entrypoint: Option<&'a Vec<String>>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_containers: Option<i64>,
            #[serde(skip_serializing_if = "Option::is_none")]
            warm_containers: Option<i64>,
            #[serde(skip_serializing_if = "network_policy_update_ref_is_keep")]
            network: &'a NetworkPolicyUpdate,
        }

        fn network_policy_update_ref_is_keep(value: &&NetworkPolicyUpdate) -> bool {
            value.is_keep()
        }

        Wire {
            image: self.pool.image.as_deref(),
            resources: &self.pool.resources,
            timeout_secs: self.pool.timeout_secs,
            entrypoint: self.pool.entrypoint.as_ref(),
            max_containers: self.pool.max_containers,
            warm_containers: self.pool.warm_containers,
            network: &self.network,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for UpdateSandboxPoolRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            image: Option<String>,
            resources: CreateSandboxResources,
            #[serde(default)]
            timeout_secs: i64,
            entrypoint: Option<Vec<String>>,
            max_containers: Option<i64>,
            warm_containers: Option<i64>,
            #[serde(default)]
            network: NetworkPolicyUpdate,
        }

        let wire = Wire::deserialize(deserializer)?;
        Ok(Self {
            pool: SandboxPoolRequest {
                image: wire.image,
                resources: wire.resources,
                timeout_secs: wire.timeout_secs,
                entrypoint: wire.entrypoint,
                max_containers: wire.max_containers,
                warm_containers: wire.warm_containers,
            },
            network: wire.network,
        })
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSandboxResponse {
    pub sandbox_id: String,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub routing_hint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ingress_endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sandbox_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub termination_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_details: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CopySandboxResponse {
    pub source_sandbox_id: String,
    pub sandboxes: Vec<CreateSandboxResponse>,
}

fn default_pending_state() -> String {
    "pending".to_string()
}

/// The acknowledgement of a `wait: false` create (ADR 0086): the sandbox is
/// durable and starts whenever capacity allows. Wait for it with
/// [`super::SandboxesClient::wait_until_settled`] or poll [`super::SandboxesClient::get`].
///
/// A server that predates `wait: false` ignores the field and answers the
/// blocking create's shape instead, so `status` is accepted as an alias of
/// `state` and the routing fields are kept when present.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxAccepted {
    pub sandbox_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default = "default_pending_state", alias = "status")]
    pub state: String,
    /// Why the sandbox is waiting, in snake_case (`scheduling` at create
    /// time; the capacity reasons appear after the first scheduler pass).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub routing_hint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ingress_endpoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sandbox_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub termination_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_details: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxInfo {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_resize: Option<SandboxResourceResizeInfo>,
    #[serde(alias = "id", alias = "sandbox_id")]
    pub sandbox_id: String,
    pub namespace: String,
    pub status: String,
    #[serde(default)]
    pub image: Option<String>,
    pub resources: ContainerResourcesInfo,
    #[serde(default)]
    pub timeout_secs: Option<i64>,
    #[serde(default)]
    pub entrypoint: Option<Vec<String>>,
    /// Egress network policy currently applied to the sandbox.
    #[serde(default)]
    pub network_policy: Option<NetworkConfig>,
    #[serde(default)]
    pub pool_id: Option<String>,
    #[serde(default)]
    pub outcome: Option<String>,
    #[serde(default)]
    pub termination_reason: Option<String>,
    #[serde(default)]
    pub error_details: Option<serde_json::Value>,
    /// Why a pending sandbox is waiting, in snake_case.
    #[serde(default)]
    pub pending_reason: Option<String>,
    #[serde(default)]
    pub created_at: Option<serde_json::Value>,
    #[serde(default)]
    pub terminated_at: Option<serde_json::Value>,
    /// User-provided name. Present only on named (non-ephemeral) sandboxes.
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub routing_hint: Option<String>,
    #[serde(default)]
    pub allow_unauthenticated_access: bool,
    #[serde(default)]
    pub exposed_ports: Option<Vec<u16>>,
    #[serde(default)]
    pub ingress_endpoint: Option<String>,
    #[serde(default)]
    pub sandbox_url: Option<String>,
    /// File systems currently mounted into the sandbox, each at its own
    /// guest mount path. Empty when no file systems are mounted.
    #[serde(default)]
    pub file_systems: Vec<FileSystemMount>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListSandboxesResponse {
    pub sandboxes: Vec<SandboxInfo>,
}

/// Sandbox information plus the archival timestamp. Returned by
/// `list_archived_sandboxes` and `get_archived_sandbox`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ArchivedSandboxInfo {
    #[serde(flatten)]
    pub sandbox: SandboxInfo,
    /// Wall-clock milliseconds when the sandbox was archived.
    pub archived_at: u64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListArchivedSandboxesResponse {
    pub sandboxes: Vec<ArchivedSandboxInfo>,
    #[serde(default)]
    pub prev_cursor: Option<String>,
    #[serde(default)]
    pub next_cursor: Option<String>,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArchivedSandboxesPaginationDirection {
    Forward,
    Backward,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct ListArchivedSandboxesParams {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direction: Option<ArchivedSandboxesPaginationDirection>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSandboxPoolResponse {
    pub pool_id: String,
    pub namespace: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PoolContainerInfo {
    pub id: String,
    pub state: String,
    #[serde(default)]
    pub sandbox_id: Option<String>,
    pub executor_id: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SandboxPoolInfo {
    #[serde(alias = "id", alias = "pool_id")]
    pub pool_id: String,
    pub namespace: String,
    pub image: String,
    pub resources: ContainerResourcesInfo,
    #[serde(default)]
    pub timeout_secs: i64,
    #[serde(default)]
    pub entrypoint: Option<Vec<String>>,
    #[serde(default)]
    pub max_containers: Option<i64>,
    #[serde(default)]
    pub warm_containers: Option<i64>,
    #[serde(default)]
    pub network_policy: Option<NetworkConfig>,
    #[serde(default)]
    pub containers: Option<Vec<PoolContainerInfo>>,
    #[serde(default)]
    pub created_at: Option<serde_json::Value>,
    #[serde(default)]
    pub updated_at: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListSandboxPoolsResponse {
    pub pools: Vec<SandboxPoolInfo>,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SnapshotType {
    Memory,
    Filesystem,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSnapshotRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_type: Option<SnapshotType>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CreateSnapshotResponse {
    pub snapshot_id: String,
    pub status: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SnapshotInfo {
    #[serde(alias = "id", alias = "snapshot_id")]
    pub snapshot_id: String,
    pub namespace: String,
    pub sandbox_id: String,
    #[serde(default)]
    pub base_image: Option<String>,
    pub status: String,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub snapshot_uri: Option<String>,
    #[serde(default)]
    pub snapshot_format_version: Option<String>,
    #[serde(default)]
    pub size_bytes: Option<i64>,
    #[serde(default)]
    pub rootfs_disk_bytes: Option<u64>,
    #[serde(default)]
    pub snapshot_type: Option<SnapshotType>,
    #[serde(default)]
    pub created_at: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListSnapshotsResponse {
    pub snapshots: Vec<SnapshotInfo>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProcessInfo {
    #[serde(default)]
    pub handle: Option<i64>,
    pub pid: i64,
    pub status: String,
    #[serde(default)]
    pub exit_code: Option<i64>,
    #[serde(default)]
    pub signal: Option<i64>,
    #[serde(default)]
    pub oom_killed: bool,
    #[serde(default)]
    pub stdin_writable: bool,
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    pub started_at: serde_json::Value,
    #[serde(default)]
    pub ended_at: Option<serde_json::Value>,
    #[serde(default)]
    pub managed: Option<ProcessManagedInfo>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListProcessesResponse {
    pub processes: Vec<ProcessInfo>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RestartPolicy {
    Never,
    OnFailure,
    Always,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RestartPolicyConfig {
    #[serde(default = "default_restart_policy")]
    pub policy: RestartPolicy,
    #[serde(default)]
    pub max_restarts: Option<u32>,
    #[serde(default = "default_restart_initial_backoff_ms")]
    pub initial_backoff_ms: u64,
    #[serde(default = "default_restart_max_backoff_ms")]
    pub max_backoff_ms: u64,
}

fn default_restart_policy() -> RestartPolicy {
    RestartPolicy::OnFailure
}

fn default_restart_initial_backoff_ms() -> u64 {
    500
}

fn default_restart_max_backoff_ms() -> u64 {
    30_000
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProcessHealthCheckKind {
    Http,
    Tcp,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessHealthCheck {
    #[serde(rename = "type")]
    pub kind: ProcessHealthCheckKind,
    pub port: u16,
    #[serde(default)]
    pub path: Option<String>,
    #[serde(default = "default_health_initial_delay_ms")]
    pub initial_delay_ms: u64,
    #[serde(default = "default_health_interval_ms")]
    pub interval_ms: u64,
    #[serde(default = "default_health_timeout_ms")]
    pub timeout_ms: u64,
    #[serde(default = "default_health_failure_threshold")]
    pub failure_threshold: u32,
}

fn default_health_initial_delay_ms() -> u64 {
    5_000
}

fn default_health_interval_ms() -> u64 {
    1_000
}

fn default_health_timeout_ms() -> u64 {
    500
}

fn default_health_failure_threshold() -> u32 {
    3
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SupervisedProcessStatus {
    Starting,
    Running,
    BackingOff,
    Stopped,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SupervisedProcessHealthStatus {
    Disabled,
    Starting,
    Healthy,
    Unhealthy,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SupervisedProcessExit {
    #[serde(default)]
    pub exit_code: Option<i64>,
    #[serde(default)]
    pub signal: Option<i64>,
    #[serde(default)]
    pub oom_killed: bool,
    pub ended_at: serde_json::Value,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProcessManagedInfo {
    pub id: String,
    #[serde(default)]
    pub name: Option<String>,
    pub status: SupervisedProcessStatus,
    pub restart_count: u32,
    pub restart: RestartPolicyConfig,
    #[serde(default)]
    pub health_check: Option<ProcessHealthCheck>,
    pub health_status: SupervisedProcessHealthStatus,
    pub consecutive_health_failures: u32,
    #[serde(default)]
    pub last_exit: Option<SupervisedProcessExit>,
    #[serde(default)]
    pub last_error: Option<String>,
    #[serde(default)]
    pub next_restart_at: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SendSignalResponse {
    pub success: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OutputResponse {
    pub pid: i64,
    pub lines: Vec<String>,
    pub line_count: i64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OutputEvent {
    pub line: String,
    pub timestamp: serde_json::Value,
    #[serde(default)]
    pub stream: Option<String>,
}

/// Events returned by the streaming `POST /api/v1/processes/run` endpoint.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RunProcessEvent {
    /// First event: process was created.
    Started {
        pid: i64,
        started_at: serde_json::Value,
    },
    /// Intermediate events: output lines (stdout/stderr).
    Output(OutputEvent),
    /// Final event: process exited.
    Exited {
        #[serde(default)]
        exit_code: Option<i64>,
        #[serde(default)]
        signal: Option<i64>,
        #[serde(default)]
        oom_killed: bool,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DaemonInfo {
    pub version: String,
    pub uptime_secs: i64,
    pub running_processes: i64,
    pub total_processes: i64,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HealthResponse {
    pub healthy: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DirectoryEntry {
    pub name: String,
    pub is_dir: bool,
    #[serde(default)]
    pub size: Option<i64>,
    #[serde(default)]
    pub modified_at: Option<serde_json::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ListDirectoryResponse {
    pub path: String,
    pub entries: Vec<DirectoryEntry>,
}

/// Request body for `POST /api/v1/blob/sign`. The proxy converts either an
/// artifact path returned by platform-api or a full parent snapshot blob URI
/// into a concrete builder upload/download spec.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SignBlobRequest {
    pub target: SignBlobTarget,
    pub op: SignBlobOp,
}

#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SignBlobTarget {
    Artifact { rel_path: String },
    Blob { uri: String },
}

#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SignBlobOp {
    PutArtifact {
        #[serde(skip_serializing_if = "Option::is_none")]
        multipart_hint: Option<MultipartHint>,
    },
    GetBlob,
}

#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MultipartHint {
    pub max_parts: u32,
    pub part_size_bytes: u64,
}

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

    #[test]
    fn create_pool_request_deserializes_flat_network_policy() {
        let request: CreateSandboxPoolRequest = serde_json::from_value(serde_json::json!({
            "image": "alpine",
            "resources": {
                "cpus": 1.0,
                "memory_mb": 1024,
                "disk_mb": 20480
            },
            "timeout_secs": 0,
            "network": {
                "allow_internet_access": false,
                "allow_out": [],
                "deny_out": []
            }
        }))
        .unwrap();

        assert_eq!(request.pool.image.as_deref(), Some("alpine"));
        assert_eq!(request.pool.resources.disk_mb, Some(20480));
        assert_eq!(
            request.network,
            Some(NetworkConfig {
                allow_internet_access: false,
                allow_out: vec![],
                deny_out: vec![],
            })
        );
    }

    #[test]
    fn sandbox_info_reads_network_policy_wire_key() {
        let policy = NetworkConfig {
            allow_internet_access: false,
            allow_out: vec![],
            deny_out: vec!["198.51.100.0/24".to_string()],
        };
        let base = serde_json::json!({
            "id": "sbx-1",
            "namespace": "default",
            "status": "running",
            "resources": {"cpus": 1.0, "memory_mb": 1024, "disk_mb": 1024}
        });

        let mut current = base.clone();
        current["network_policy"] = serde_json::to_value(&policy).unwrap();
        let info: SandboxInfo = serde_json::from_value(current).unwrap();
        assert_eq!(info.network_policy, Some(policy.clone()));

        // `network` is the request key; the server never reports the policy
        // under it, so it must not be read as an alias.
        let mut request_key = base.clone();
        request_key["network"] = serde_json::to_value(&policy).unwrap();
        let info: SandboxInfo = serde_json::from_value(request_key).unwrap();
        assert_eq!(info.network_policy, None);

        let info: SandboxInfo = serde_json::from_value(base).unwrap();
        assert_eq!(info.network_policy, None);

        // Re-serialization (what the Python/TS bindings hand to their
        // models) uses the canonical key.
        let out = serde_json::to_value(SandboxInfo {
            network_policy: Some(policy.clone()),
            ..info
        })
        .unwrap();
        assert_eq!(
            out["network_policy"],
            serde_json::to_value(&policy).unwrap()
        );
        assert!(out.get("network").is_none());
    }

    #[test]
    fn container_resources_info_requires_canonical_disk() {
        let canonical: ContainerResourcesInfo = serde_json::from_value(serde_json::json!({
            "cpus": 1.0,
            "memory_mb": 1024,
            "disk_mb": 20480,
            "ephemeral_disk_mb": 1024
        }))
        .unwrap();
        assert_eq!(canonical.disk_mb, 20480);

        let legacy = serde_json::from_value::<ContainerResourcesInfo>(serde_json::json!({
            "cpus": 1.0,
            "memory_mb": 1024,
            "ephemeral_disk_mb": 10240
        }));
        assert!(legacy.is_err(), "disk_mb is required in server responses");
        assert_eq!(
            serde_json::to_value(canonical).unwrap(),
            serde_json::json!({"cpus": 1.0, "memory_mb": 1024, "disk_mb": 20480})
        );
    }

    #[test]
    fn file_system_mount_omits_false_mount_modes() {
        let mount = FileSystemMount {
            file_system_id: "skills".to_string(),
            mount_path: "/mnt/skills".to_string(),
            read_only: false,
            prefetch: false,
            snapshot_id: None,
            owner: None,
        };
        assert_eq!(
            serde_json::to_value(&mount).unwrap(),
            serde_json::json!({
                "file_system_id": "skills",
                "mount_path": "/mnt/skills"
            })
        );
    }

    #[test]
    fn create_sandbox_request_allows_snapshot_resource_inheritance() {
        let request: CreateSandboxRequest = serde_json::from_value(serde_json::json!({
            "snapshot_id": "snap-memory"
        }))
        .unwrap();

        assert_eq!(request.snapshot_id.as_deref(), Some("snap-memory"));
        assert!(request.resources.is_empty());
        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::json!({"snapshot_id": "snap-memory"})
        );

        let cpu_override: CreateSandboxRequest = serde_json::from_value(serde_json::json!({
            "snapshot_id": "snap-memory",
            "resources": {"cpus": 2.0}
        }))
        .unwrap();
        assert_eq!(cpu_override.resources.cpus, 2.0);
        assert_eq!(cpu_override.resources.memory_mb, unspecified_memory_mb());

        let invalid_zero: CreateSandboxResources =
            serde_json::from_value(serde_json::json!({"cpus": 0.0})).unwrap();
        assert_eq!(
            serde_json::to_value(&invalid_zero).unwrap(),
            serde_json::json!({"cpus": 0.0})
        );
    }

    #[test]
    fn file_system_mount_serializes_true_mount_modes() {
        let mount = FileSystemMount {
            file_system_id: "skills".to_string(),
            mount_path: "/mnt/skills".to_string(),
            read_only: true,
            prefetch: true,
            snapshot_id: None,
            owner: None,
        };
        assert_eq!(
            serde_json::to_value(&mount).unwrap(),
            serde_json::json!({
                "file_system_id": "skills",
                "mount_path": "/mnt/skills",
                "read_only": true,
                "prefetch": true
            })
        );
    }

    #[test]
    fn file_system_mount_serializes_snapshot_pin_only_when_set() {
        let pinned = FileSystemMount {
            file_system_id: "skills".to_string(),
            mount_path: "/mnt/skills".to_string(),
            read_only: true,
            prefetch: false,
            snapshot_id: Some("0abc123def".to_string()),
            owner: None,
        };
        assert_eq!(
            serde_json::to_value(&pinned).unwrap(),
            serde_json::json!({
                "file_system_id": "skills",
                "mount_path": "/mnt/skills",
                "read_only": true,
                "snapshot_id": "0abc123def"
            })
        );
    }

    #[test]
    fn file_system_mount_deserializes_absent_and_present_mount_modes() {
        let absent: FileSystemMount = serde_json::from_value(serde_json::json!({
            "file_system_id": "skills",
            "mount_path": "/mnt/skills"
        }))
        .unwrap();
        assert!(!absent.read_only);
        assert!(!absent.prefetch);
        assert_eq!(absent.snapshot_id, None);

        let present: FileSystemMount = serde_json::from_value(serde_json::json!({
            "file_system_id": "skills",
            "mount_path": "/mnt/skills",
            "read_only": true,
            "prefetch": true,
            "snapshot_id": "0abc123def"
        }))
        .unwrap();
        assert!(present.read_only);
        assert!(present.prefetch);
        assert_eq!(present.snapshot_id.as_deref(), Some("0abc123def"));
    }

    #[test]
    fn snapshot_type_serializes_as_snake_case() {
        assert_eq!(
            serde_json::to_string(&SnapshotType::Memory).unwrap(),
            "\"memory\""
        );
        assert_eq!(
            serde_json::to_string(&SnapshotType::Filesystem).unwrap(),
            "\"filesystem\""
        );
    }

    #[test]
    fn create_snapshot_request_skips_none_snapshot_type() {
        let body = CreateSnapshotRequest {
            snapshot_type: None,
        };
        assert_eq!(serde_json::to_string(&body).unwrap(), "{}");
    }

    #[test]
    fn sign_blob_put_artifact_serializes_as_adt() {
        let body = SignBlobRequest {
            target: SignBlobTarget::Artifact {
                rel_path: "projects/p/sandbox-template-builds/b/s.tlsnap".to_string(),
            },
            op: SignBlobOp::PutArtifact {
                multipart_hint: Some(MultipartHint {
                    max_parts: 160,
                    part_size_bytes: 67_108_864,
                }),
            },
        };

        assert_eq!(
            serde_json::to_value(&body).unwrap(),
            serde_json::json!({
                "target": {
                    "kind": "artifact",
                    "rel_path": "projects/p/sandbox-template-builds/b/s.tlsnap"
                },
                "op": {
                    "kind": "put_artifact",
                    "multipart_hint": {
                        "max_parts": 160,
                        "part_size_bytes": 67_108_864
                    }
                }
            })
        );
    }

    #[test]
    fn sign_blob_get_blob_serializes_as_adt() {
        let body = SignBlobRequest {
            target: SignBlobTarget::Blob {
                uri: "gs://bucket/path/parent-manifest.json".to_string(),
            },
            op: SignBlobOp::GetBlob,
        };

        assert_eq!(
            serde_json::to_value(&body).unwrap(),
            serde_json::json!({
                "target": {
                    "kind": "blob",
                    "uri": "gs://bucket/path/parent-manifest.json"
                },
                "op": { "kind": "get_blob" }
            })
        );
    }

    #[test]
    fn run_process_event_deserializes_started() {
        let json = r#"{"pid": 42, "started_at": 1234567890.123}"#;
        let event: RunProcessEvent = serde_json::from_str(json).unwrap();
        assert!(matches!(event, RunProcessEvent::Started { pid: 42, .. }));
    }

    #[test]
    fn run_process_event_deserializes_output() {
        let json = r#"{"line": "hello", "timestamp": 1234567890.456, "stream": "stdout"}"#;
        let event: RunProcessEvent = serde_json::from_str(json).unwrap();
        match event {
            RunProcessEvent::Output(evt) => {
                assert_eq!(evt.line, "hello");
                assert_eq!(evt.stream.as_deref(), Some("stdout"));
            }
            _ => panic!("expected Output variant"),
        }
    }

    #[test]
    fn run_process_event_deserializes_exited() {
        let json = r#"{"exit_code": 0}"#;
        let event: RunProcessEvent = serde_json::from_str(json).unwrap();
        assert!(matches!(
            event,
            RunProcessEvent::Exited {
                exit_code: Some(0),
                signal: None,
                oom_killed: false,
            }
        ));
    }

    #[test]
    fn run_process_event_deserializes_signaled() {
        let json = r#"{"signal": 9}"#;
        let event: RunProcessEvent = serde_json::from_str(json).unwrap();
        assert!(matches!(
            event,
            RunProcessEvent::Exited {
                exit_code: None,
                signal: Some(9),
                oom_killed: false,
            }
        ));
    }

    #[test]
    fn run_process_event_deserializes_oom_killed() {
        let json = r#"{"signal": 9, "oom_killed": true}"#;
        let event: RunProcessEvent = serde_json::from_str(json).unwrap();
        assert!(matches!(
            event,
            RunProcessEvent::Exited {
                exit_code: None,
                signal: Some(9),
                oom_killed: true,
            }
        ));
    }

    #[test]
    fn process_info_deserializes_oom_killed() {
        let json = r#"{
            "pid": 42,
            "status": "oom_killed",
            "signal": 9,
            "oom_killed": true,
            "command": "/usr/local/bin/tl-rootfs-build",
            "args": [],
            "started_at": 123,
            "ended_at": 456
        }"#;
        let info: ProcessInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.status, "oom_killed");
        assert_eq!(info.signal, Some(9));
        assert!(info.oom_killed);
    }

    #[test]
    fn create_snapshot_request_serializes_filesystem() {
        let body = CreateSnapshotRequest {
            snapshot_type: Some(SnapshotType::Filesystem),
        };
        assert_eq!(
            serde_json::to_string(&body).unwrap(),
            r#"{"snapshot_type":"filesystem"}"#
        );
    }

    #[test]
    fn copy_sandbox_response_deserializes() {
        let json = r#"{
            "source_sandbox_id":"source-1",
            "sandboxes":[{"sandbox_id":"copy-1","status":"running"}]
        }"#;
        let response: CopySandboxResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.source_sandbox_id, "source-1");
        assert_eq!(response.sandboxes[0].sandbox_id, "copy-1");
        assert_eq!(response.sandboxes[0].status, "running");
    }

    #[test]
    fn sandbox_info_deserializes_routing_hint_and_sandbox_url() {
        let json = r#"{
            "id":"sbx-1",
            "namespace":"default",
            "status":"running",
            "resources":{"cpus":1.0,"memory_mb":512,"disk_mb":1024},
            "routing_hint":"hint-1",
            "sandbox_url":"https://sbx-1.sandbox.tensorlake.ai"
        }"#;
        let info: SandboxInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.sandbox_id, "sbx-1");
        assert_eq!(info.routing_hint.as_deref(), Some("hint-1"));
        assert_eq!(
            info.sandbox_url.as_deref(),
            Some("https://sbx-1.sandbox.tensorlake.ai")
        );
    }

    #[test]
    fn snapshot_info_deserializes_snapshot_type() {
        let json = r#"{
            "id":"snap-1",
            "namespace":"default",
            "sandbox_id":"sbx-1",
            "status":"completed",
            "snapshot_type":"filesystem"
        }"#;
        let info: SnapshotInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.snapshot_type, Some(SnapshotType::Filesystem));
    }

    #[test]
    fn gpu_models_use_server_wire_values() {
        let wire_values = [
            "A100-40GB",
            "A100-80GB",
            "H100",
            "T4",
            "A6000",
            "A10",
            "RTX-PRO-6000",
            "L40",
        ];
        for (model, wire_value) in GpuModel::ALL.into_iter().zip(wire_values) {
            assert_eq!(model.to_string(), wire_value);
            assert_eq!(wire_value.parse::<GpuModel>().unwrap(), model);
            assert_eq!(
                serde_json::to_string(&model).unwrap(),
                format!(r#""{wire_value}""#)
            );
        }
    }

    #[test]
    fn gpu_request_requires_positive_count() {
        assert!(GpuRequest::new(GpuModel::H100, 0).is_err());
        assert_eq!(
            GpuRequest::new(GpuModel::H100, 2).unwrap(),
            GpuRequest {
                count: 2,
                model: GpuModel::H100,
            }
        );
        assert_eq!(
            GPUResources::from(GpuRequest::new(GpuModel::H100, 2).unwrap()),
            GPUResources {
                count: 2,
                model: "H100".to_string(),
            }
        );
    }
}