agent-workspace-contract 0.7.0

Transport-neutral contracts for Agent Infra workspace 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
//! Workspace environment domain contracts, strongly typed resources, and provider ports.

use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::Stream;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Debug;
use std::pin::Pin;
use std::sync::Arc;

mod base64_bytes {
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(value: &[u8], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&STANDARD.encode(value))
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        STANDARD.decode(value).map_err(serde::de::Error::custom)
    }
}

mod catalog;
pub use catalog::*;

mod ports;
pub use ports::*;

mod owners;
pub use owners::*;

mod command_context;
pub use command_context::*;

mod application_execution;
pub use application_execution::*;

mod commands;
pub use commands::*;

mod resources;
pub use resources::*;

mod execution_operation;
pub use execution_operation::*;

mod skills;
pub use skills::*;

mod managed_workloads;
pub use managed_workloads::*;

pub const COMPUTERS_PATH: &str = "/internal/v1/workspace/computers";
/// Privileged inventory and terminal routes used only by the Infra Admin console.
/// They are intentionally separate from the owner-scoped public Environment API.
pub const ADMIN_COMPUTERS_PATH: &str = "/internal/v1/workspace/admin/computers";
pub const COMPUTER_PATH: &str = "/internal/v1/workspace/computers/{computerId}";
pub const SPACES_PATH: &str = "/internal/v1/workspace/spaces";
pub const ADMIN_SPACES_PATH: &str = "/internal/v1/workspace/admin/spaces";
pub const SPACE_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}";
pub const SPACE_GRANTS_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/grants";
pub const SPACE_GRANT_REVOKE_PATH: &str =
    "/internal/v1/workspace/spaces/{spaceId}/grants/{grantId}/revoke";
pub const SPACE_SESSIONS_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/sessions";
pub const SPACE_SESSION_HEARTBEAT_PATH: &str =
    "/internal/v1/workspace/space-sessions/{sessionId}/heartbeat";
pub const SPACE_SESSION_CLOSE_PATH: &str =
    "/internal/v1/workspace/space-sessions/{sessionId}/close";
pub const SPACE_TICKETS_PATH: &str = "/internal/v1/workspace/space-access-tickets";
pub const SPACE_LEASES_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/leases";
pub const SPACE_LEASE_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/leases/{leaseId}";
pub const SPACE_FILES_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/files/{*filePath}";
pub const SPACE_FILES_READ_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/files/read";
pub const SPACE_FILES_DOWNLOAD_PATH: &str =
    "/internal/v1/workspace/spaces/{spaceId}/files/download";
pub const SPACE_FILES_LIST_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/files/list";
pub const SPACE_SOURCE_ARCHIVE_PATH: &str =
    "/internal/v1/workspace/spaces/{spaceId}/source-archive";
pub const SPACE_CHANGE_SETS_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/change-sets";
pub const SPACE_CHANGE_SET_APPLY_PATH: &str =
    "/internal/v1/workspace/spaces/{spaceId}/change-sets/{changeSetId}/apply";
pub const SANDBOXES_PATH: &str = "/internal/v1/workspace/sandboxes";
pub const SANDBOX_PATH: &str = "/internal/v1/workspace/sandboxes/{sandboxId}";
pub const SANDBOX_STOP_PATH: &str = "/internal/v1/workspace/sandboxes/{sandboxId}/stop";
pub const COMPUTER_SNAPSHOTS_PATH: &str = "/internal/v1/workspace/computers/{computerId}/snapshots";
pub const SNAPSHOT_ARTIFACT_PATH: &str = "/internal/v1/workspace/snapshots/{snapshotId}/artifact";
pub const SNAPSHOTS_PATH: &str = "/internal/v1/workspace/snapshots";
pub const SNAPSHOT_PATH: &str = "/internal/v1/workspace/snapshots/{snapshotId}";
pub const BUILD_BUILTIN_SNAPSHOTS_PATH: &str = "/internal/v1/workspace/snapshots:build-builtin";
pub const CATALOG_SNAPSHOTS_PATH: &str = "/internal/v1/workspace/snapshots:catalog";
pub const TEMPLATES_PATH: &str = "/internal/v1/workspace/templates";
pub const TEMPLATE_VERSIONS_PATH: &str = "/internal/v1/workspace/templates/{templateId}/versions";
pub const TEMPLATE_VERSION_PATH: &str =
    "/internal/v1/workspace/templates/{templateId}/versions/{version}";
pub const TEMPLATE_VERSION_PUBLISH_PATH: &str =
    "/internal/v1/workspace/templates/{templateId}/versions/{version}/publish";
pub const TEMPLATE_VERSION_DEPRECATE_PATH: &str =
    "/internal/v1/workspace/templates/{templateId}/versions/{version}/deprecate";
pub const DELEGATIONS_PATH: &str = "/internal/v1/workspace/delegations";
pub const DELEGATION_REVOKE_PATH: &str = "/internal/v1/workspace/delegations/{delegationId}/revoke";
pub const ENVIRONMENT_MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const ENVIRONMENT_MAX_PATH_BYTES: usize = 4096;

/// System resources assigned to one provider Computer/Sandbox. Units match
/// the provider control planes and keep invalid budgets out of Runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxResources {
    cpu_count: u32,
    memory_mb: u32,
    disk_mb: u32,
}

impl SandboxResources {
    pub fn new(cpu_count: u32, memory_mb: u32, disk_mb: u32) -> std::result::Result<Self, String> {
        if !(1..=64).contains(&cpu_count) {
            return Err("cpuCount must be between 1 and 64".into());
        }
        if !(128..=131_072).contains(&memory_mb) {
            return Err("memoryMb must be between 128 and 131072".into());
        }
        if !(512..=1_048_576).contains(&disk_mb) {
            return Err("diskMb must be between 512 and 1048576".into());
        }
        Ok(Self {
            cpu_count,
            memory_mb,
            disk_mb,
        })
    }

    pub const fn cpu_count(self) -> u32 {
        self.cpu_count
    }

    pub const fn memory_mb(self) -> u32 {
        self.memory_mb
    }

    pub const fn disk_mb(self) -> u32 {
        self.disk_mb
    }
}

impl Default for SandboxResources {
    fn default() -> Self {
        Self::new(1, 1_024, 2_048).expect("system resource defaults are valid")
    }
}

impl<'de> Deserialize<'de> for SandboxResources {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase", deny_unknown_fields)]
        struct WireResources {
            cpu_count: u32,
            memory_mb: u32,
            disk_mb: u32,
        }

        let value = WireResources::deserialize(deserializer)?;
        Self::new(value.cpu_count, value.memory_mb, value.disk_mb).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ExportSpaceSourceArchiveQuery {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_revision: Option<u64>,
}

/// Logical directory for a Space on its parent Computer filesystem.
pub fn space_directory_path(space_id: &str) -> String {
    format!("spaces/{space_id}")
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum EnvironmentErrorCode {
    NotFound,
    Forbidden,
    Conflict,
    InvalidState,
    ArtifactUnavailable,
    CapabilityUnsupported,
    TicketExpired,
    LeaseRequired,
    StaleFencingToken,
    RevisionConflict,
}

#[derive(Debug, Clone)]
pub struct EnvironmentDomainError {
    pub code: EnvironmentErrorCode,
    pub message: String,
}

impl EnvironmentDomainError {
    pub fn new(code: EnvironmentErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
        }
    }
}

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

impl std::error::Error for EnvironmentDomainError {}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrincipalKind {
    User,
    Agent,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct PrincipalRef {
    pub kind: PrincipalKind,
    pub id: String,
}

impl PrincipalRef {
    pub fn user(id: impl Into<String>) -> Self {
        Self {
            kind: PrincipalKind::User,
            id: id.into(),
        }
    }

    pub fn agent(id: impl Into<String>) -> Self {
        Self {
            kind: PrincipalKind::Agent,
            id: id.into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ResourceScope {
    pub tenant_id: String,
    pub project_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ProviderResourceRef {
    pub provider: String,
    pub external_id: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ProviderCapabilities {
    #[serde(default)]
    pub capabilities: BTreeSet<String>,
}

impl ProviderCapabilities {
    pub fn supports(&self, capability: &str) -> bool {
        self.capabilities.contains(capability)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ComputerLifecycle {
    Ready,
    Deleted,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ComputerRecord {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    pub scope: ResourceScope,
    pub provider_ref: ProviderResourceRef,
    /// Effective system resources after resolving the Admin default and any
    /// developer override. Old persisted records inherit the compatible default.
    #[serde(default)]
    pub resources: SandboxResources,
    pub lifecycle: ComputerLifecycle,
    pub capabilities: ProviderCapabilities,
    pub owners: Vec<OwnerRef>,
    pub version: u64,
    pub created_at_ms: u64,
    pub updated_at_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ComputerBinding {
    pub computer_id: String,
    pub principal: PrincipalRef,
    pub role: String,
    pub active: bool,
    pub bound_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub released_at_ms: Option<u64>,
    pub version: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[serde(rename_all = "snake_case")]
pub enum SpacePersistence {
    Persistent,
    CopyOnWrite,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpaceLifecycle {
    Ready,
    Deleted,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceRecord {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    pub computer_id: String,
    pub scope: ResourceScope,
    pub persistence: SpacePersistence,
    pub lifecycle: SpaceLifecycle,
    pub capabilities: ProviderCapabilities,
    pub owners: Vec<OwnerRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_snapshot_id: Option<String>,
    pub revision: u64,
    pub version: u64,
    /// Durable ownership journal for Skill assets and their CLI dependencies.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub installed_skills: BTreeMap<String, SpaceSkillInstallation>,
    /// Merged environment from Space skill installs. Applied to later execs.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub skill_env: BTreeMap<String, String>,
    pub created_at_ms: u64,
    pub updated_at_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxPlacement {
    Computer(String),
    ProviderPool(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SandboxLifecycle {
    Ready,
    Stopped,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SandboxMount {
    pub alias: String,
    pub space_id: String,
    pub mode: SpaceAccessMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_prefix: Option<String>,
    pub access_ticket_token: String,
}

/// Persisted mount metadata. The bearer token from [`SandboxMount`] is
/// deliberately replaced by its non-secret ticket id before persistence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SandboxMountRecord {
    pub alias: String,
    pub space_id: String,
    pub mode: SpaceAccessMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_prefix: Option<String>,
    pub access_ticket_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SandboxRecord {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    pub scope: ResourceScope,
    pub provider_ref: ProviderResourceRef,
    /// Effective system resources after resolving the Admin default and any
    /// developer override. Old persisted records inherit the compatible default.
    #[serde(default)]
    pub resources: SandboxResources,
    pub placement: SandboxPlacement,
    pub lifecycle: SandboxLifecycle,
    pub owners: Vec<OwnerRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub access_delegation_id: Option<String>,
    pub capabilities: ProviderCapabilities,
    #[serde(default)]
    pub mounts: Vec<SandboxMountRecord>,
    pub expires_at_ms: u64,
    pub version: u64,
    /// Merged environment from Sandbox skill installs. Applied to later execs.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub skill_env: BTreeMap<String, String>,
    pub created_at_ms: u64,
    pub updated_at_ms: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SnapshotLifecycle {
    Building,
    Ready,
    Failed,
    Deleted,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SnapshotSourceRecord {
    Build { spec: SnapshotBuildSpec },
    Computer { computer_id: String },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SnapshotRecord {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    pub scope: ResourceScope,
    pub provider: String,
    pub provider_ref: ProviderResourceRef,
    pub source: SnapshotSourceRecord,
    pub visibility: SnapshotVisibility,
    pub owners: Vec<OwnerRef>,
    #[serde(default)]
    pub builtin: bool,
    pub created_by: PrincipalRef,
    pub lifecycle: SnapshotLifecycle,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_build_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build_stage: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub build_logs: Vec<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub build_key: String,
    pub created_at_ms: u64,
    pub updated_at_ms: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TemplateTarget {
    Computer,
    Sandbox,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TemplateVersionState {
    Draft,
    Published,
    Deprecated,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TemplateVersionRecord {
    pub template_id: String,
    pub version: String,
    pub scope: ResourceScope,
    pub provider: String,
    pub created_by: PrincipalRef,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_template_id: Option<String>,
    pub target: TemplateTarget,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_snapshot_id: Option<String>,
    #[serde(default)]
    pub resource_profile: BTreeMap<String, String>,
    #[serde(default)]
    pub parameter_schema: BTreeMap<String, String>,
    pub state: TemplateVersionState,
    pub created_at_ms: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpaceCapability {
    Read,
    Execute,
    Write,
    Share,
    Manage,
    Mount,
    Snapshot,
    Restore,
    Delete,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceGrant {
    pub id: String,
    pub scope: ResourceScope,
    pub space_id: String,
    pub principal: PrincipalRef,
    pub capabilities: BTreeSet<SpaceCapability>,
    #[serde(default)]
    pub path_prefixes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<u64>,
    pub active: bool,
    pub version: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[serde(rename_all = "snake_case")]
pub enum SpaceAccessMode {
    ReadOnly,
    DirectWrite,
    CopyOnWrite,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpaceSessionLifecycle {
    Opening,
    Active,
    Closing,
    Closed,
    Expired,
    Revoked,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceCollaborationSession {
    pub id: String,
    pub scope: ResourceScope,
    pub space_id: String,
    pub principal: PrincipalRef,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegation_id: Option<String>,
    pub requested_mode: SpaceAccessMode,
    pub effective_mode: SpaceAccessMode,
    pub lifecycle: SpaceSessionLifecycle,
    pub last_heartbeat_at_ms: u64,
    pub expires_at_ms: u64,
    pub version: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceAccessTicketRecord {
    pub id: String,
    pub token_hash: String,
    pub scope: ResourceScope,
    pub space_id: String,
    pub session_id: String,
    pub mode: SpaceAccessMode,
    /// Capability-specific path rules captured at issue time. Runtime
    /// intersects these with current Grant/Delegation authority on every use.
    #[serde(default)]
    pub capability_paths: BTreeMap<SpaceCapability, Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fencing_token: Option<u64>,
    pub expires_at_ms: u64,
    pub revoked: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct IssuedSpaceAccessTicket {
    pub ticket: SpaceAccessTicketRecord,
    /// Returned exactly once. Repositories and logs must never persist this
    /// bearer value.
    pub token: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceWriteLease {
    pub id: String,
    pub scope: ResourceScope,
    pub space_id: String,
    pub session_id: String,
    pub fencing_token: u64,
    pub version: u64,
    pub acquired_at_ms: u64,
    pub expires_at_ms: u64,
    pub active: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct DelegationRecord {
    pub id: String,
    pub scope: ResourceScope,
    pub grantor_user_id: String,
    pub delegate_agent_id: String,
    #[serde(default)]
    pub computer_ids: BTreeSet<String>,
    #[serde(default)]
    pub space_ids: BTreeSet<String>,
    pub capabilities: BTreeSet<SpaceCapability>,
    #[serde(default)]
    pub path_prefixes: Vec<String>,
    pub purpose: String,
    pub expires_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revoked_at_ms: Option<u64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeSetLifecycle {
    Ready,
    Applied,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceChangeSetRecord {
    pub id: String,
    pub scope: ResourceScope,
    pub source_space_id: String,
    pub target_space_id: String,
    pub base_revision: u64,
    pub created_by_session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_change_ref: Option<String>,
    pub lifecycle: ChangeSetLifecycle,
    pub created_at_ms: u64,
}

/// Default runtime provider for newly created remote Workspace resources.
pub fn default_workspace_provider() -> String {
    "e2b".into()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateComputerRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    #[serde(default = "default_workspace_provider")]
    pub provider: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template_version: Option<String>,
    #[serde(default)]
    pub profile: BTreeMap<String, String>,
    /// Optional developer override. Missing inherits the Admin default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources: Option<SandboxResources>,
    /// Optional per-computer override. Missing inherits the Moulin provider
    /// default; an explicit empty list requests unrestricted egress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub egress_rules: Option<Vec<crate::MoulinEgressRule>>,
    /// Additional owners beyond the authenticated creator.
    #[serde(default)]
    pub owners: Vec<OwnerRef>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateSpaceRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    pub computer_id: String,
    pub persistence: SpacePersistence,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_snapshot_id: Option<String>,
    /// Must be a subset of the parent Computer owners when non-empty.
    #[serde(default)]
    pub owners: Vec<OwnerRef>,
}

/// Mutable human label for an existing Environment resource; identity remains unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct PatchResourceAliasRequest {
    pub alias: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateSandboxRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    #[serde(default = "default_workspace_provider")]
    pub provider: String,
    pub placement: SandboxPlacement,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegation_id: Option<String>,
    pub ttl_ms: u64,
    #[serde(default)]
    pub mounts: Vec<SandboxMount>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub template_version: Option<String>,
    #[serde(default)]
    pub profile: BTreeMap<String, String>,
    /// Optional developer override. Missing inherits the Admin default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources: Option<SandboxResources>,
    /// Optional per-sandbox override. Missing inherits the Moulin provider
    /// default; an explicit empty list requests unrestricted egress.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub egress_rules: Option<Vec<crate::MoulinEgressRule>>,
}

/// Provider-facing request after product identifiers and access tickets have
/// been resolved. These DTOs cannot be supplied by HTTP callers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderComputerRequest {
    pub template_external_id: Option<String>,
    pub profile: BTreeMap<String, String>,
    pub resources: SandboxResources,
    pub egress_rules: Option<Vec<crate::MoulinEgressRule>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderSpaceRequest {
    pub persistence: SpacePersistence,
    pub source_snapshot_external_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderSandboxMount {
    pub alias: String,
    pub space_directory: String,
    pub mode: SpaceAccessMode,
    pub path_prefix: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderSandboxPlacement {
    Computer(String),
    ProviderPool(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderSandboxRequest {
    pub placement: ProviderSandboxPlacement,
    pub ttl_ms: u64,
    pub mounts: Vec<ProviderSandboxMount>,
    pub template_external_id: Option<String>,
    pub source_snapshot_external_id: Option<String>,
    pub profile: BTreeMap<String, String>,
    pub resources: SandboxResources,
    pub egress_rules: Option<Vec<crate::MoulinEgressRule>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderSnapshotSource {
    Computer(String),
    Sandbox(String),
    Space(String),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ListEnvironmentResourcesQuery {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_kind: Option<OwnerKind>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_id: Option<String>,
    /// When set, resource owners must contain every listed owner (JSON array).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contains_all: Vec<OwnerRef>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct RevokeSpaceGrantRequest {
    pub expected_version: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateSpaceGrantRequest {
    pub principal: PrincipalRef,
    pub capabilities: BTreeSet<SpaceCapability>,
    #[serde(default)]
    pub path_prefixes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at_ms: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct OpenSpaceSessionRequest {
    pub mode: SpaceAccessMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegation_id: Option<String>,
    pub ttl_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct IssueSpaceAccessTicketRequest {
    pub session_id: String,
    pub ttl_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct AcquireSpaceWriteLeaseRequest {
    pub session_id: String,
    pub ttl_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ReleaseSpaceWriteLeaseRequest {
    pub session_id: String,
    pub fencing_token: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct HeartbeatSpaceSessionRequest {
    pub ttl_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateDelegationRequest {
    pub delegate_agent_id: String,
    #[serde(default)]
    pub computer_ids: BTreeSet<String>,
    #[serde(default)]
    pub space_ids: BTreeSet<String>,
    pub capabilities: BTreeSet<SpaceCapability>,
    #[serde(default)]
    pub path_prefixes: Vec<String>,
    pub purpose: String,
    pub expires_at_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateTemplateVersionRequest {
    pub template_id: String,
    pub version: String,
    pub provider: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_template_id: Option<String>,
    pub target: TemplateTarget,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_snapshot_id: Option<String>,
    #[serde(default)]
    pub resource_profile: BTreeMap<String, String>,
    #[serde(default)]
    pub parameter_schema: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct CreateSpaceChangeSetRequest {
    pub source_space_id: String,
    pub target_space_id: String,
    pub created_by_session_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ApplySpaceChangeSetRequest {
    pub access_ticket_token: String,
    pub fencing_token: u64,
    pub expected_revision: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct WriteSpaceFileRequest {
    pub access_ticket_token: String,
    pub fencing_token: u64,
    pub expected_revision: u64,
    #[serde(with = "base64_bytes")]
    pub content: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ReadSpaceFileRequest {
    pub access_ticket_token: String,
    pub path: String,
}

/// Directory archive format; regular files always retain their original bytes.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkspaceArchiveFormat {
    #[default]
    #[serde(rename = "zip")]
    Zip,
    #[serde(rename = "tar.gz")]
    TarGz,
    #[serde(rename = "tar")]
    Tar,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct DownloadSpaceFileRequest {
    pub access_ticket_token: String,
    pub path: String,
    #[serde(default)]
    pub archive_format: WorkspaceArchiveFormat,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ListSpaceFilesRequest {
    pub access_ticket_token: String,
    #[serde(default)]
    pub path: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct DeleteSpaceFileRequest {
    pub access_ticket_token: String,
    pub fencing_token: u64,
    pub expected_revision: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ProviderFileContent {
    pub bytes: Vec<u8>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_revision: Option<String>,
}

pub type ProviderByteStream = Pin<Box<dyn Stream<Item = Result<Bytes>> + Send + 'static>>;

pub struct ProviderSourceArchive {
    pub stream: ProviderByteStream,
    pub digest: String,
    pub size_bytes: u64,
}

impl Debug for ProviderSourceArchive {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ProviderSourceArchive")
            .field("digest", &self.digest)
            .field("size_bytes", &self.size_bytes)
            .finish_non_exhaustive()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ProviderFileEntry {
    pub path: String,
    pub is_dir: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct ProviderWriteResult {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_revision: Option<String>,
}