phala-tee-deploy-rs 0.2.0

Rust client for deploying and managing Docker containers on Phala TEE Cloud (dstack)
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
use crate::{
    AdvancedFeatures, AttestationResponse, ComposeManifest, CvmInfo, CvmStateResponse,
    DeploymentConfig, DeploymentResponse, DockerConfig, Error, NetworkInfoResponse, PubkeyResponse,
    Result, SystemStatsResponse, TeeClient, TeePodDiscoveryResponse, VmConfig,
};
use std::time::Duration;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;

/// `TeeDeployer` provides a high-level interface for deploying Docker Compose applications
/// to the Phala TEE Cloud platform.
///
/// This struct provides a simplified API for deploying applications compared to the
/// lower-level `TeeClient`, with methods for common deployment scenarios and
/// configuration management using standard JSON.
///
/// # Features
///
/// * TEEPod discovery and selection
/// * Docker Compose application deployment from various sources
/// * Environment variable encryption
/// * Deployment updates
///
/// # Examples
///
/// ```no_run
/// use phala_tee_deploy_rs::{Result, TeeDeployerBuilder};
/// use std::collections::HashMap;
///
/// #[tokio::main]
/// async fn main() -> Result<()> {
///     // Create deployer using builder pattern
///     let mut deployer = TeeDeployerBuilder::new()
///         .with_api_key("your_api_key")
///         .build()?;
///
///     // Discover available TEEPods
///     deployer.discover_teepod().await?;
///
///     // Deploy a simple service
///     let mut env_vars = HashMap::new();
///     env_vars.insert("PORT".to_string(), "3000".to_string());
///
///     let result = deployer.deploy_simple_service(
///         "nginx:latest",
///         "web",
///         "my-webapp",
///         env_vars,
///         Some(vec!["80:80".to_string()]),
///         None,
///         None,
///         None,
///         None,
///         None,
///     ).await?;
///
///     println!("Deployment successful: {:?}", result);
///     Ok(())
/// }
/// ```
pub struct TeeDeployer {
    client: TeeClient,
    selected_teepod: Option<(u64, String)>,
}

impl TeeDeployer {
    /// Creates a new `TeeDeployer` with the specified API credentials.
    ///
    /// # Parameters
    ///
    /// * `api_key` - The API key for authenticating with the Phala Cloud API
    /// * `api_endpoint` - Optional custom API endpoint URL. If `None`, uses the default endpoint
    ///
    /// # Returns
    ///
    /// A new `TeeDeployer` instance or an error if initialization fails
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP client cannot be created
    pub fn new(api_key: String, api_endpoint: Option<String>) -> Result<Self> {
        let config = DeploymentConfig {
            api_key,
            api_url: api_endpoint
                .unwrap_or_else(|| "https://cloud-api.phala.network/api/v1".to_string()),
            docker_compose: String::new(),
            env_vars: HashMap::new(),
            teepod_id: 0,
            image: String::new(),
            vm_config: None,
        };

        Ok(Self {
            client: TeeClient::new(config)?,
            selected_teepod: None,
        })
    }

    /// Discovers and selects the first available TEEPod automatically.
    ///
    /// This method queries the Phala Cloud API for available TEEPods and selects
    /// the first one from the response. It's a convenient way to get started without
    /// needing to choose a specific TEEPod.
    ///
    /// # Returns
    ///
    /// `Ok(())` if a TEEPod was successfully discovered and selected
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * No TEEPods are available
    /// * The API response has an unexpected format
    pub async fn discover_teepod(&mut self) -> Result<TeePodDiscoveryResponse> {
        let teepods = self.client.get_available_teepods().await?;

        let nodes = &teepods.nodes;
        if nodes.is_empty() {
            return Err(Error::Api {
                status_code: 400,
                message: "No available TEEPods found".into(),
            });
        }

        let node = &nodes[0];
        let image = node.images[0].name.clone();
        self.selected_teepod = Some((node.teepod_id, image));
        Ok(teepods)
    }

    /// Selects a specific TEEPod by ID and verifies its availability.
    ///
    /// This method allows you to choose a particular TEEPod for deployment instead
    /// of using the first available one.
    ///
    /// # Parameters
    ///
    /// * `teepod_id` - The ID of the TEEPod to select
    ///
    /// # Returns
    ///
    /// `Ok(())` if the TEEPod was found and selected successfully
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * The specified TEEPod is not found or not available
    /// * The API response has an unexpected format
    pub async fn select_teepod(&mut self, teepod_id: u64) -> Result<()> {
        let teepods = self.client.get_available_teepods().await?;

        for node in &teepods.nodes {
            if node.teepod_id == teepod_id {
                let image = node.images[0].name.clone();
                self.selected_teepod = Some((teepod_id, image));
                return Ok(());
            }
        }

        Err(Error::Api {
            status_code: 404,
            message: format!("TEEPod with ID {} not found or not available", teepod_id),
        })
    }

    /// Deploys a Docker Compose application using a YAML string configuration.
    ///
    /// This method takes a Docker Compose configuration as a string and deploys it to the
    /// selected TEEPod with the specified options.
    ///
    /// # Parameters
    ///
    /// * `docker_compose_file` - The Docker Compose configuration as a YAML string
    /// * `app_name` - Name for the deployed application
    /// * `env_vars` - Environment variables for the application (will be securely encrypted)
    /// * `vcpu` - Optional vCPU cores for the VM (defaults to 1)
    /// * `memory` - Optional memory in MB for the VM (defaults to 1024)
    /// * `disk_size` - Optional disk size in GB for the VM (defaults to 10)
    ///
    /// # Returns
    ///
    /// A `DeploymentResponse` containing deployment details including ID, status, and TEEPod information
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * No TEEPod has been selected
    /// * The API request fails
    /// * Environment variable encryption fails
    pub async fn deploy_compose(
        &self,
        docker_compose_file: &str,
        app_name: &str,
        env_vars: HashMap<String, String>,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<DeploymentResponse> {
        // Ensure we have a selected TEEPod
        let (teepod_id, image) = self.selected_teepod.as_ref().ok_or_else(|| Error::Api {
            status_code: 400,
            message: "No TEEPod selected. Call discover_teepod() or select_teepod() first".into(),
        })?;

        // Create VM configuration
        let vm_config = json!({
            "name": app_name,
            "compose_manifest": {
                "docker_compose_file": docker_compose_file,
                "name": app_name,
                "features": ["kms", "tproxy-net"]
            },
            "vcpu": vcpu.unwrap_or(1),
            "memory": memory.unwrap_or(1024),
            "disk_size": disk_size.unwrap_or(10),
            "teepod_id": teepod_id,
            "image": image
        });

        // Deploy the application with automatic encryption
        let env_vars_vec: Vec<(String, String)> = env_vars.into_iter().collect();

        // Get encryption keys
        let pubkey_response = self.client.get_pubkey_for_config(&vm_config).await?;
        let pubkey = pubkey_response.app_env_encrypt_pubkey;
        let salt = pubkey_response.app_id_salt;

        // Deploy with encrypted environment variables
        let deployment = self
            .client
            .deploy_with_config_do_encrypt(vm_config, &env_vars_vec, &pubkey, &salt)
            .await?;

        // Add extra details if needed
        if let Some(mut details) = deployment.details.clone() {
            details.insert(
                "teepod_id".to_string(),
                serde_json::Value::Number(serde_json::Number::from(*teepod_id)),
            );
            details.insert(
                "image".to_string(),
                serde_json::Value::String(image.clone()),
            );

            let mut deployment_with_details = deployment.clone();
            deployment_with_details.details = Some(details);
            Ok(deployment_with_details)
        } else {
            // Create new details if none exist
            let mut details = HashMap::new();
            details.insert(
                "teepod_id".to_string(),
                serde_json::Value::Number(serde_json::Number::from(*teepod_id)),
            );
            details.insert(
                "image".to_string(),
                serde_json::Value::String(image.clone()),
            );

            let mut deployment_with_details = deployment.clone();
            deployment_with_details.details = Some(details);
            Ok(deployment_with_details)
        }
    }

    /// Deploys a Docker Compose application from a file path.
    ///
    /// Reads a Docker Compose file from the specified path and deploys it to the selected TEEPod.
    ///
    /// # Parameters
    ///
    /// * `compose_path` - Path to the Docker Compose file
    /// * `app_name` - Name for the deployed application
    /// * `env_vars` - Environment variables for the application
    /// * `vcpu` - Optional vCPU cores for the VM
    /// * `memory` - Optional memory in MB for the VM
    /// * `disk_size` - Optional disk size in GB for the VM
    ///
    /// # Returns
    ///
    /// A `DeploymentResponse` containing deployment details
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The file cannot be read
    /// * The underlying `deploy_compose` call fails
    pub async fn deploy_compose_from_file<P: AsRef<Path>>(
        &self,
        compose_path: P,
        app_name: &str,
        env_vars: HashMap<String, String>,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<DeploymentResponse> {
        // Read compose file
        let content = std::fs::read_to_string(compose_path)
            .map_err(|e| Error::Configuration(format!("Failed to read compose file: {}", e)))?;

        self.deploy_compose(&content, app_name, env_vars, vcpu, memory, disk_size)
            .await
    }

    /// Deploys a Docker Compose application from a YAML string.
    ///
    /// Takes a Docker Compose YAML string and deploys it to the selected TEEPod.
    ///
    /// # Parameters
    ///
    /// * `yaml_content` - Docker Compose YAML content as a string
    /// * `app_name` - Name for the deployed application
    /// * `env_vars` - Environment variables for the application
    /// * `vcpu` - Optional vCPU cores for the VM
    /// * `memory` - Optional memory in MB for the VM
    /// * `disk_size` - Optional disk size in GB for the VM
    ///
    /// # Returns
    ///
    /// A `DeploymentResponse` containing deployment details
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying `deploy_compose` call fails
    pub async fn deploy_compose_from_string(
        &self,
        yaml_content: &str,
        app_name: &str,
        env_vars: HashMap<String, String>,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<DeploymentResponse> {
        self.deploy_compose(yaml_content, app_name, env_vars, vcpu, memory, disk_size)
            .await
    }

    /// Deploys a simple service using just an image name and basic configuration.
    ///
    /// This is a convenience method for quickly deploying a single service
    /// without needing to create a full Docker Compose configuration.
    ///
    /// # Parameters
    ///
    /// * `image` - Docker image name (e.g. "nginx:latest")
    /// * `service_name` - Name for the service
    /// * `app_name` - Name for the deployed application
    /// * `env_vars` - Environment variables for the service
    /// * `ports` - Optional port mappings (e.g. ["80:80"])
    /// * `volumes` - Optional volume mappings
    /// * `command` - Optional command override for the container
    /// * `vcpu` - Optional vCPU cores for the VM
    /// * `memory` - Optional memory in MB for the VM
    /// * `disk_size` - Optional disk size in GB for the VM
    ///
    /// # Returns
    ///
    /// A `DeploymentResponse` containing deployment details
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying `deploy_compose` call fails
    pub async fn deploy_simple_service(
        &self,
        image: &str,
        service_name: &str,
        app_name: &str,
        env_vars: HashMap<String, String>,
        ports: Option<Vec<String>>,
        volumes: Option<Vec<String>>,
        command: Option<Vec<String>>,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<DeploymentResponse> {
        // Create a simple Docker Compose YAML configuration
        let mut yaml = String::from("services:\n");
        yaml.push_str(&format!("  {}:\n", service_name));
        yaml.push_str(&format!("    image: {}\n", image));

        if let Some(ports) = &ports {
            yaml.push_str("    ports:\n");
            for port in ports {
                yaml.push_str(&format!("      - \"{}\"\n", port));
            }
        }

        if let Some(volumes) = &volumes {
            yaml.push_str("    volumes:\n");
            for volume in volumes {
                yaml.push_str(&format!("      - {}\n", volume));
            }
        }

        if let Some(command) = &command {
            yaml.push_str("    command: [");
            for (i, cmd) in command.iter().enumerate() {
                if i > 0 {
                    yaml.push_str(", ");
                }
                yaml.push_str(&format!("\"{}\"", cmd));
            }
            yaml.push_str("]\n");
        }

        if !env_vars.is_empty() {
            yaml.push_str("    environment:\n");
            for (key, value) in &env_vars {
                yaml.push_str(&format!("      {}: {}\n", key, value));
            }
        }

        // Deploy
        self.deploy_compose(&yaml, app_name, env_vars, vcpu, memory, disk_size)
            .await
    }

    /// Updates an existing deployment with new configuration and/or environment variables.
    ///
    /// # Parameters
    ///
    /// * `app_id` - The ID of the application to update
    /// * `compose_content` - Optional new Docker Compose configuration as a YAML string
    /// * `env_vars` - Optional new environment variables
    ///
    /// # Returns
    ///
    /// A `Value` containing details about the update operation
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The application cannot be found
    /// * The API request fails
    pub async fn update_deployment(
        &self,
        app_id: &str,
        compose_content: Option<&str>,
        env_vars: Option<HashMap<String, String>>,
    ) -> Result<Value> {
        // Get the current compose configuration
        let compose_response = self.client.get_compose(app_id).await?;
        let mut compose_file = compose_response.compose_file;

        // Update compose file if provided
        if let Some(new_config) = compose_content {
            if let Some(manifest) = compose_file.get_mut("compose_manifest") {
                if let Some(obj) = manifest.as_object_mut() {
                    obj.insert("docker_compose_file".to_string(), json!(new_config));
                }
            }
        }

        // Apply the update
        let response = self
            .client
            .update_compose(app_id, compose_file, env_vars, compose_response.env_pubkey)
            .await?;

        Ok(json!({
            "status": "updated",
            "app_id": app_id,
            "details": response
        }))
    }

    /// Creates a VM configuration for a Docker Compose application.
    ///
    /// This method creates a VM configuration without actually deploying it,
    /// which can be used to request encryption keys or for later deployment.
    ///
    /// # Parameters
    ///
    /// * `docker_compose_file` - The Docker Compose configuration as a YAML string
    /// * `app_name` - Name for the application
    /// * `vcpu` - Optional vCPU cores for the VM (defaults to 1)
    /// * `memory` - Optional memory in MB for the VM (defaults to 1024)
    /// * `disk_size` - Optional disk size in GB for the VM (defaults to 10)
    ///
    /// # Returns
    ///
    /// A VM configuration object
    ///
    /// # Errors
    ///
    /// Returns an error if no TEEPod has been selected
    pub fn create_vm_config(
        &self,
        docker_compose_file: &str,
        app_name: &str,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<VmConfig> {
        // Ensure we have a selected TEEPod
        let (teepod_id, image) = self.selected_teepod.as_ref().ok_or_else(|| Error::Api {
            status_code: 400,
            message: "No TEEPod selected. Call discover_teepod() or select_teepod() first".into(),
        })?;

        // Create VM configuration
        let vm_config = VmConfig {
            name: app_name.to_string(),
            compose_manifest: ComposeManifest {
                name: app_name.to_string(),
                features: vec!["kms".to_string(), "tproxy-net".to_string()],
                docker_compose_file: docker_compose_file.to_string(),
            },
            vcpu: vcpu.unwrap_or(1) as u32,
            memory: memory.unwrap_or(1024) as u32,
            disk_size: disk_size.unwrap_or(10) as u32,
            teepod_id: *teepod_id,
            image: image.to_string(),
            advanced_features: AdvancedFeatures {
                tproxy: true,
                kms: true,
                public_sys_info: true,
                public_logs: true,
                docker_config: DockerConfig {
                    username: String::new(),
                    password: String::new(),
                    registry: None,
                },
                listed: true,
            },
        };

        Ok(vm_config)
    }

    /// Creates a VM configuration from a Docker Compose file path.
    ///
    /// This is a convenience method that reads a Docker Compose file
    /// and creates a VM configuration for it.
    ///
    /// # Parameters
    ///
    /// * `compose_path` - Path to the Docker Compose file
    /// * `app_name` - Name for the application
    /// * `vcpu` - Optional vCPU cores for the VM
    /// * `memory` - Optional memory in MB for the VM
    /// * `disk_size` - Optional disk size in GB for the VM
    ///
    /// # Returns
    ///
    /// A VM configuration object
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The file cannot be read
    /// * The `create_vm_config` call fails
    pub fn create_vm_config_from_file<P: AsRef<Path>>(
        &self,
        compose_path: P,
        app_name: &str,
        vcpu: Option<u64>,
        memory: Option<u64>,
        disk_size: Option<u64>,
    ) -> Result<VmConfig> {
        // Read compose file
        let content = std::fs::read_to_string(compose_path)
            .map_err(|e| Error::Configuration(format!("Failed to read compose file: {}", e)))?;

        self.create_vm_config(&content, app_name, vcpu, memory, disk_size)
    }

    /// Retrieves the encryption public key for a VM configuration.
    ///
    /// This method requests a public key from the API that can be used to
    /// encrypt environment variables for a specific VM configuration.
    ///
    /// # Parameters
    ///
    /// * `vm_config` - The VM configuration as a JSON value
    ///
    /// # Returns
    ///
    /// A JSON value containing the public key and salt for encryption
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails
    pub async fn get_pubkey_for_config(&self, vm_config: &Value) -> Result<PubkeyResponse> {
        self.client
            .get_pubkey_for_config(vm_config)
            .await
                }

    /// Deploys a VM configuration with pre-encrypted environment variables.
    ///
    /// This method is useful for workflows where the user encrypts their own
    /// environment variables and the operator deploys the application. It allows
    /// for a separation of concerns between compute management and sensitive data.
    ///
    /// # Parameters
    ///
    /// * `vm_config` - The VM configuration as a JSON value
    /// * `encrypted_env` - Pre-encrypted environment variables as a hex string
    /// * `app_env_encrypt_pubkey` - The public key used for encryption
    /// * `app_id_salt` - The salt value used for encryption
    ///
    /// # Returns
    ///
    /// A JSON value containing the deployment details
    ///
    /// # Errors
    ///
    /// Returns an error if the API request fails
    pub async fn deploy_with_encrypted_env(
        &self,
        vm_config: Value,
        encrypted_env: String,
        app_env_encrypt_pubkey: &str,
        app_id_salt: &str,
    ) -> Result<DeploymentResponse> {
        let response = self
            .client
            .deploy_with_config_encrypted_env(
                vm_config,
                encrypted_env,
                app_env_encrypt_pubkey,
                app_id_salt,
            )
            .await?;

        Ok(response)
    }

    /// Provisions a new ELIZA chatbot deployment.
    ///
    /// This method initiates the ELIZA deployment process by requesting an app_id
    /// and encryption key from the API. This is the first step in the two-step
    /// deployment process.
    ///
    /// # Parameters
    ///
    /// * `name` - Name for the ELIZA deployment
    /// * `character_file` - Character configuration file content
    /// * `env_keys` - List of environment variable keys to include
    /// * `image` - Docker image to use for the deployment
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// * `app_id` - The ID of the provisioned application
    /// * `app_env_encrypt_pubkey` - The public key for encrypting environment variables
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * Invalid configuration is provided
    /// * The response cannot be parsed
    pub async fn provision_eliza(
        &self,
        name: String,
        character_file: String,
        env_keys: Vec<String>,
        image: String,
    ) -> Result<(String, String)> {
        self.client
            .provision_eliza(name, character_file, env_keys, image)
            .await
    }

    /// Creates a VM for an ELIZA deployment with encrypted environment variables.
    ///
    /// This method is the second step in the ELIZA deployment process, creating
    /// the actual VM with the provided encrypted environment variables.
    ///
    /// # Parameters
    ///
    /// * `app_id` - The ID of the provisioned application
    /// * `encrypted_env` - Pre-encrypted environment variables
    ///
    /// # Returns
    ///
    /// A `DeploymentResponse` containing the deployment details and status
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * The deployment cannot be created
    /// * The response cannot be parsed
    pub async fn create_eliza_vm(
        &self,
        app_id: &str,
        encrypted_env: &str,
    ) -> Result<DeploymentResponse> {
        self.client.create_eliza_vm(app_id, encrypted_env).await
    }

    /// Retrieves network information for a deployed application.
    ///
    /// This method fetches network connectivity details, status, and public URLs
    /// for accessing a deployed application.
    ///
    /// # Parameters
    ///
    /// * `app_id` - The ID of the application to get network information for
    ///
    /// # Returns
    ///
    /// A `NetworkInfoResponse` containing network details including status and URLs
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * The application is not found
    /// * The network information cannot be retrieved
    pub async fn get_network_info(&self, app_id: &str) -> Result<NetworkInfoResponse> {
        self.client.get_network_info(app_id).await
    }

    /// Retrieves system statistics for a deployed application.
    ///
    /// This method fetches detailed system information including OS details,
    /// CPU, memory, disk usage, and load averages for a deployed application.
    ///
    /// # Parameters
    ///
    /// * `app_id` - The ID of the application to get system statistics for
    ///
    /// # Returns
    ///
    /// A `SystemStatsResponse` containing system information including resource usage
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// * The API request fails
    /// * The application is not found
    /// * The system statistics cannot be retrieved
    pub async fn get_system_stats(&self, app_id: &str) -> Result<SystemStatsResponse> {
        self.client.get_system_stats(app_id).await
    }

    // ─────────────────────────────────────────────────────────────────────
    // CVM lifecycle
    // ─────────────────────────────────────────────────────────────────────

    /// Stop a CVM (force).
    pub async fn stop(&self, app_id: &str) -> Result<CvmInfo> {
        self.client.stop_cvm(app_id).await    }

    /// Graceful shutdown of a CVM.
    pub async fn shutdown(&self, app_id: &str) -> Result<CvmInfo> {
        self.client.shutdown_cvm(app_id).await    }

    /// Start a stopped CVM.
    pub async fn start(&self, app_id: &str) -> Result<CvmInfo> {
        self.client.start_cvm(app_id).await    }

    /// Permanently delete a CVM.
    pub async fn delete(&self, app_id: &str) -> Result<()> {
        self.client.delete_cvm(app_id).await    }

    /// Get TEE attestation for a CVM.
    pub async fn get_attestation(&self, app_id: &str) -> Result<AttestationResponse> {
        self.client.get_attestation(app_id).await    }

    /// Get CVM state (running, stopped, etc.).
    pub async fn get_status(&self, app_id: &str) -> Result<CvmStateResponse> {
        self.client.get_state(app_id).await    }

    /// Poll until the CVM reaches "running" state or the timeout expires.
    pub async fn wait_until_running(&self, app_id: &str, timeout: Duration) -> Result<()> {
        let start = std::time::Instant::now();
        loop {
            if start.elapsed() > timeout {
                return Err(Error::Api {
                    status_code: 408,
                    message: format!(
                        "CVM {} did not reach running state within {:?}",
                        app_id, timeout
                    ),
                });
            }
            match self.client.get_state(app_id).await {
                Ok(state) if state.is_running => return Ok(()),
                Ok(_) => {}
                Err(_) => {}
            }
            tokio::time::sleep(Duration::from_secs(2)).await;
        }
    }

    /// Returns a reference to the underlying `TeeClient` for direct access to lower-level operations.
    ///
    /// # Returns
    ///
    /// A reference to the internal `TeeClient` instance
    pub fn get_client(&self) -> &TeeClient {
        &self.client
    }
}

/// Builder for creating a `TeeDeployer` with a fluent interface.
///
/// This builder pattern allows for a more ergonomic API when constructing
/// a `TeeDeployer` instance with various optional parameters.
///
/// # Examples
///
/// ```no_run
/// use phala_tee_deploy_rs::TeeDeployerBuilder;
///
/// let deployer = TeeDeployerBuilder::new()
///     .with_api_key("your_api_key_here")
///     .with_api_endpoint("https://custom-endpoint.example.com/api/v1")
///     .build()
///     .expect("Failed to create deployer");
/// ```
pub struct TeeDeployerBuilder {
    api_key: Option<String>,
    api_endpoint: Option<String>,
}

impl TeeDeployerBuilder {
    /// Creates a new empty `TeeDeployerBuilder`.
    ///
    /// # Returns
    ///
    /// A new `TeeDeployerBuilder` instance with no parameters set
    pub fn new() -> Self {
        Self {
            api_key: None,
            api_endpoint: None,
        }
    }

    /// Sets the API key for authenticating with the Phala Cloud API.
    ///
    /// # Parameters
    ///
    /// * `api_key` - The API key to use
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// Sets a custom API endpoint URL.
    ///
    /// # Parameters
    ///
    /// * `endpoint` - The custom API endpoint URL
    ///
    /// # Returns
    ///
    /// The builder instance for method chaining
    pub fn with_api_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.api_endpoint = Some(endpoint.into());
        self
    }

    /// Builds a `TeeDeployer` instance with the configured parameters.
    ///
    /// # Returns
    ///
    /// A new `TeeDeployer` instance if successful
    ///
    /// # Errors
    ///
    /// Returns an error if the API key is not set or if the `TeeDeployer` creation fails
    pub fn build(self) -> Result<TeeDeployer> {
        let api_key = self
            .api_key
            .ok_or_else(|| Error::Configuration("API key is required".into()))?;

        TeeDeployer::new(api_key, self.api_endpoint)
    }
}