sprites 0.1.0

Official Rust SDK for Sprites - stateful sandbox environments from Fly.io
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
//! Command execution in sprites
//!
//! This module provides a `Command` builder that mirrors `std::process::Command`,
//! allowing you to execute commands inside sprites with a familiar API.
//!
//! # Streaming I/O
//!
//! For interactive commands or long-running processes, use `spawn()` to get a `Child`
//! handle with separate stdin/stdout/stderr streams:
//!
//! ```no_run
//! use sprites::SpritesClient;
//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = SpritesClient::new("token");
//!     let sprite = client.sprite("my-sprite");
//!
//!     let mut child = sprite.command("cat").spawn().await?;
//!
//!     // Write to stdin
//!     if let Some(stdin) = child.stdin() {
//!         stdin.write(b"hello\n").await?;
//!         stdin.close().await?;
//!     }
//!
//!     // Read from stdout
//!     if let Some(stdout) = child.stdout() {
//!         let mut buf = vec![0u8; 1024];
//!         let n = stdout.read(&mut buf).await?;
//!         println!("Got: {}", String::from_utf8_lossy(&buf[..n]));
//!     }
//!
//!     // Wait for completion
//!     let status = child.wait().await?;
//!     println!("Exit code: {}", status.code());
//!
//!     Ok(())
//! }
//! ```

use crate::error::{Error, Result};
use crate::sprite::Sprite;
use crate::types::{ExitStatus, Output};
use futures_util::{SinkExt, StreamExt};
use std::collections::HashMap;
use tokio::sync::{mpsc, oneshot};
use tokio_tungstenite::tungstenite::Message;

/// Stream identifiers for the WebSocket protocol
const STREAM_STDIN: u8 = 0;
const STREAM_STDOUT: u8 = 1;
const STREAM_STDERR: u8 = 2;
const STREAM_EXIT: u8 = 3;
const STREAM_STDIN_EOF: u8 = 4;

/// A command to execute in a sprite
///
/// This struct mirrors `std::process::Command` for familiar usage.
///
/// # Example
///
/// ```no_run
/// use sprites::SpritesClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = SpritesClient::new("token");
///     let sprite = client.sprite("my-sprite");
///
///     let output = sprite
///         .command("ls")
///         .arg("-la")
///         .current_dir("/home")
///         .output()
///         .await?;
///
///     println!("stdout: {}", output.stdout_str());
///
///     Ok(())
/// }
/// ```
pub struct Command {
    sprite: Sprite,
    program: String,
    args: Vec<String>,
    env: HashMap<String, String>,
    dir: Option<String>,
    tty: bool,
    control_mode: bool,
    max_run_after_disconnect: Option<u32>,
}

impl Command {
    /// Create a new command
    pub(crate) fn new(sprite: Sprite, program: impl Into<String>) -> Self {
        Self {
            sprite,
            program: program.into(),
            args: Vec::new(),
            env: HashMap::new(),
            dir: None,
            tty: false,
            control_mode: false,
            max_run_after_disconnect: None,
        }
    }

    /// Add an argument
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Add multiple arguments
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(|s| s.into()));
        self
    }

    /// Set an environment variable
    pub fn env(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
        self.env.insert(key.into(), val.into());
        self
    }

    /// Set multiple environment variables
    pub fn envs<I, K, V>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = (K, V)>,
        K: Into<String>,
        V: Into<String>,
    {
        for (k, v) in vars {
            self.env.insert(k.into(), v.into());
        }
        self
    }

    /// Set the working directory
    pub fn current_dir(mut self, dir: impl Into<String>) -> Self {
        self.dir = Some(dir.into());
        self
    }

    /// Enable TTY mode
    pub fn tty(mut self, enable: bool) -> Self {
        self.tty = enable;
        self
    }

    /// Enable control mode for advanced interactive sessions
    ///
    /// Control mode enables advanced features for interactive sessions,
    /// including better signal handling and terminal control.
    pub fn control_mode(mut self, enable: bool) -> Self {
        self.control_mode = enable;
        self
    }

    /// Set max duration (in seconds) to keep process running after disconnect
    ///
    /// This allows the process to continue running in the background after
    /// the client disconnects. Useful for long-running tasks that shouldn't
    /// be interrupted if the connection drops.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = SpritesClient::new("token");
    ///     let sprite = client.sprite("my-sprite");
    ///
    ///     // Process will run for up to 300 seconds after disconnect
    ///     let output = sprite
    ///         .command("long-running-task")
    ///         .max_run_after_disconnect(300)
    ///         .output()
    ///         .await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn max_run_after_disconnect(mut self, seconds: u32) -> Self {
        self.max_run_after_disconnect = Some(seconds);
        self
    }

    /// Build the WebSocket URL for exec
    ///
    /// The Go SDK sends each argument as a separate `cmd` query parameter,
    /// along with a `path` parameter for the program name.
    fn build_ws_url(&self) -> Result<String> {
        let base_url = self.sprite.client().base_url();
        let ws_base = base_url
            .replace("https://", "wss://")
            .replace("http://", "ws://");

        // Build URL with path and cmd parameters like the Go SDK
        let mut url = format!(
            "{}/v1/sprites/{}/exec?path={}",
            ws_base,
            self.sprite.name(),
            urlencoding::encode(&self.program)
        );

        // Add program as first cmd parameter
        url.push_str(&format!("&cmd={}", urlencoding::encode(&self.program)));

        // Add each argument as a separate cmd parameter
        for arg in &self.args {
            url.push_str(&format!("&cmd={}", urlencoding::encode(arg)));
        }

        if self.tty {
            url.push_str("&tty=true");
        }

        if self.control_mode {
            url.push_str("&control=true");
        }

        if let Some(seconds) = self.max_run_after_disconnect {
            url.push_str(&format!("&max_run_after_disconnect={seconds}"));
        }

        if let Some(ref dir) = self.dir {
            url.push_str(&format!("&cwd={}", urlencoding::encode(dir)));
        }

        for (key, val) in &self.env {
            url.push_str(&format!(
                "&env={}={}",
                urlencoding::encode(key),
                urlencoding::encode(val)
            ));
        }

        Ok(url)
    }

    /// Execute the command and wait for output
    ///
    /// This collects stdout and stderr and returns them along with the exit status.
    pub async fn output(&self) -> Result<Output> {
        let url = self.build_ws_url()?;
        let token = self.sprite.client().token();

        // Generate WebSocket key (16 random bytes, base64 encoded)
        let ws_key = {
            use std::time::{SystemTime, UNIX_EPOCH};
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system time before UNIX epoch")
                .as_nanos();
            base64_encode(&nanos.to_le_bytes()[..16])
        };

        // Create request with auth header and required WebSocket upgrade headers
        // Note: We don't request a sub-protocol since the server may not support it
        let request = tokio_tungstenite::tungstenite::http::Request::builder()
            .method("GET")
            .uri(&url)
            .header("Authorization", format!("Bearer {token}"))
            .header("Connection", "Upgrade")
            .header("Upgrade", "websocket")
            .header("Sec-WebSocket-Version", "13")
            .header("Sec-WebSocket-Key", &ws_key)
            .header("Host", extract_host(&url).unwrap_or("api.sprites.dev"))
            .body(())
            .map_err(|e| Error::InvalidResponse(e.to_string()))?;

        let (ws_stream, _) = tokio_tungstenite::connect_async(request).await?;
        let (mut _write, mut read) = ws_stream.split();

        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let mut exit_code: Option<i32> = None;

        // Stream identifiers (for non-TTY mode):
        // 0 = stdin (client -> server)
        // 1 = stdout (server -> client)
        // 2 = stderr (server -> client)
        // 3 = exit code

        while let Some(msg) = read.next().await {
            match msg? {
                Message::Binary(data) => {
                    if data.is_empty() {
                        continue;
                    }

                    if self.tty {
                        // TTY mode: all data is stdout
                        stdout.extend_from_slice(&data);
                    } else {
                        // Non-TTY mode: first byte is stream identifier
                        let stream_id = data[0];
                        let payload = &data[1..];

                        match stream_id {
                            1 => stdout.extend_from_slice(payload),
                            2 => stderr.extend_from_slice(payload),
                            3 => {
                                // Exit code (as string)
                                if let Ok(code_str) = std::str::from_utf8(payload) {
                                    exit_code = code_str.trim().parse().ok();
                                }
                            }
                            _ => {}
                        }
                    }
                }
                Message::Text(text) => {
                    // Try to parse as JSON for exit code
                    if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
                        if let Some(code) = val.get("exit_code").and_then(|c| c.as_i64()) {
                            exit_code = Some(code as i32);
                        }
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }

        Ok(Output {
            status: exit_code.unwrap_or(0),
            stdout,
            stderr,
        })
    }

    /// Execute the command and return just the exit status
    pub async fn status(&self) -> Result<ExitStatus> {
        let output = self.output().await?;
        Ok(ExitStatus::new(output.status))
    }

    /// Execute the command and return combined stdout and stderr
    ///
    /// This merges stdout and stderr into a single stream.
    pub async fn combined_output(&self) -> Result<Output> {
        let url = self.build_ws_url()?;
        let token = self.sprite.client().token();

        let ws_key = {
            use std::time::{SystemTime, UNIX_EPOCH};
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system time before UNIX epoch")
                .as_nanos();
            base64_encode(&nanos.to_le_bytes()[..16])
        };

        let request = tokio_tungstenite::tungstenite::http::Request::builder()
            .method("GET")
            .uri(&url)
            .header("Authorization", format!("Bearer {token}"))
            .header("Connection", "Upgrade")
            .header("Upgrade", "websocket")
            .header("Sec-WebSocket-Version", "13")
            .header("Sec-WebSocket-Key", &ws_key)
            .header("Host", extract_host(&url).unwrap_or("api.sprites.dev"))
            .body(())
            .map_err(|e| Error::InvalidResponse(e.to_string()))?;

        let (ws_stream, _) = tokio_tungstenite::connect_async(request).await?;
        let (mut _write, mut read) = ws_stream.split();

        let mut combined = Vec::new();
        let mut exit_code: Option<i32> = None;

        while let Some(msg) = read.next().await {
            match msg? {
                Message::Binary(data) => {
                    if data.is_empty() {
                        continue;
                    }

                    if self.tty {
                        combined.extend_from_slice(&data);
                    } else {
                        let stream_id = data[0];
                        let payload = &data[1..];

                        match stream_id {
                            STREAM_STDOUT | STREAM_STDERR => combined.extend_from_slice(payload),
                            STREAM_EXIT => {
                                if let Ok(code_str) = std::str::from_utf8(payload) {
                                    exit_code = code_str.trim().parse().ok();
                                }
                            }
                            _ => {}
                        }
                    }
                }
                Message::Text(text) => {
                    if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
                        if let Some(code) = val.get("exit_code").and_then(|c| c.as_i64()) {
                            exit_code = Some(code as i32);
                        }
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }

        Ok(Output {
            status: exit_code.unwrap_or(0),
            stdout: combined,
            stderr: Vec::new(), // Empty since everything is in stdout
        })
    }

    /// Start the command without waiting for it to complete
    ///
    /// Returns a `Child` handle that provides access to stdin, stdout, and stderr
    /// streams, and allows waiting for completion.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use sprites::SpritesClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = SpritesClient::new("token");
    ///     let sprite = client.sprite("my-sprite");
    ///
    ///     let mut child = sprite.command("long-running-task").spawn().await?;
    ///
    ///     // Do other work while the command runs...
    ///
    ///     // Eventually wait for it
    ///     let status = child.wait().await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn spawn(self) -> Result<Child> {
        let url = self.build_ws_url()?;
        let token = self.sprite.client().token().to_string();
        let tty = self.tty;

        let ws_key = {
            use std::time::{SystemTime, UNIX_EPOCH};
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .expect("system time before UNIX epoch")
                .as_nanos();
            base64_encode(&nanos.to_le_bytes()[..16])
        };

        let request = tokio_tungstenite::tungstenite::http::Request::builder()
            .method("GET")
            .uri(&url)
            .header("Authorization", format!("Bearer {token}"))
            .header("Connection", "Upgrade")
            .header("Upgrade", "websocket")
            .header("Sec-WebSocket-Version", "13")
            .header("Sec-WebSocket-Key", &ws_key)
            .header("Host", extract_host(&url).unwrap_or("api.sprites.dev"))
            .body(())
            .map_err(|e| Error::InvalidResponse(e.to_string()))?;

        let (ws_stream, _) = tokio_tungstenite::connect_async(request).await?;
        let (mut ws_write, mut ws_read) = ws_stream.split();

        // Create channels for stdin/stdout/stderr
        let (control_tx, mut control_rx) = mpsc::channel::<ControlMessage>(32);
        let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(32);
        let (stderr_tx, stderr_rx) = mpsc::channel::<Vec<u8>>(32);
        let (exit_tx, exit_rx) = oneshot::channel::<i32>();

        // Spawn the WebSocket handler task
        tokio::spawn(async move {
            let mut exit_code: Option<i32> = None;

            loop {
                tokio::select! {
                    // Handle control messages (stdin, resize, kill)
                    Some(msg) = control_rx.recv() => {
                        match msg {
                            ControlMessage::Stdin(data) => {
                                let mut frame = vec![STREAM_STDIN];
                                frame.extend(data);
                                if ws_write.send(Message::Binary(frame)).await.is_err() {
                                    break;
                                }
                            }
                            ControlMessage::StdinClose => {
                                let frame = vec![STREAM_STDIN_EOF];
                                let _ = ws_write.send(Message::Binary(frame)).await;
                            }
                            ControlMessage::Resize { rows, cols } => {
                                let resize_msg = serde_json::json!({
                                    "type": "resize",
                                    "rows": rows,
                                    "cols": cols
                                });
                                let _ = ws_write.send(Message::Text(resize_msg.to_string())).await;
                            }
                            ControlMessage::Kill => {
                                let _ = ws_write.close().await;
                                break;
                            }
                        }
                    }

                    // Handle incoming WebSocket messages
                    Some(msg) = ws_read.next() => {
                        match msg {
                            Ok(Message::Binary(data)) => {
                                if data.is_empty() {
                                    continue;
                                }

                                if tty {
                                    // TTY mode: all data goes to stdout
                                    let _ = stdout_tx.send(data.clone()).await;
                                } else {
                                    let stream_id = data[0];
                                    let payload = data[1..].to_vec();

                                    match stream_id {
                                        STREAM_STDOUT => {
                                            let _ = stdout_tx.send(payload).await;
                                        }
                                        STREAM_STDERR => {
                                            let _ = stderr_tx.send(payload).await;
                                        }
                                        STREAM_EXIT => {
                                            if let Ok(code_str) = std::str::from_utf8(&payload) {
                                                exit_code = code_str.trim().parse().ok();
                                            }
                                        }
                                        _ => {}
                                    }
                                }
                            }
                            Ok(Message::Text(text)) => {
                                if let Ok(val) = serde_json::from_str::<serde_json::Value>(&text) {
                                    if let Some(code) = val.get("exit_code").and_then(|c| c.as_i64()) {
                                        exit_code = Some(code as i32);
                                    }
                                }
                            }
                            Ok(Message::Close(_)) => break,
                            Err(_) => break,
                            _ => {}
                        }
                    }

                    else => break,
                }
            }

            // Send the exit code
            let _ = exit_tx.send(exit_code.unwrap_or(1));
        });

        Ok(Child {
            stdin: Some(ChildStdin {
                control_tx: control_tx.clone(),
            }),
            stdout: Some(ChildStdout {
                rx: stdout_rx,
                buffer: Vec::new(),
            }),
            stderr: Some(ChildStderr {
                rx: stderr_rx,
                buffer: Vec::new(),
            }),
            control_tx,
            exit_rx: Some(exit_rx),
            tty,
        })
    }
}

impl std::fmt::Debug for Command {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Command")
            .field("sprite", &self.sprite.name())
            .field("program", &self.program)
            .field("args", &self.args)
            .field("dir", &self.dir)
            .field("tty", &self.tty)
            .finish()
    }
}

// Add urlencoding as a lightweight alternative to full URL parsing
mod urlencoding {
    pub fn encode(s: &str) -> String {
        let mut result = String::new();
        for c in s.chars() {
            match c {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' | '~' => result.push(c),
                _ => {
                    for byte in c.to_string().as_bytes() {
                        result.push_str(&format!("%{byte:02X}"));
                    }
                }
            }
        }
        result
    }
}

// Base64 encoding for WebSocket key
fn base64_encode(data: &[u8]) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    let mut result = String::new();
    let mut i = 0;

    while i < data.len() {
        let b0 = data[i];
        let b1 = if i + 1 < data.len() { data[i + 1] } else { 0 };
        let b2 = if i + 2 < data.len() { data[i + 2] } else { 0 };

        result.push(ALPHABET[(b0 >> 2) as usize] as char);
        result.push(ALPHABET[((b0 & 0x03) << 4 | b1 >> 4) as usize] as char);

        if i + 1 < data.len() {
            result.push(ALPHABET[((b1 & 0x0f) << 2 | b2 >> 6) as usize] as char);
        } else {
            result.push('=');
        }

        if i + 2 < data.len() {
            result.push(ALPHABET[(b2 & 0x3f) as usize] as char);
        } else {
            result.push('=');
        }

        i += 3;
    }

    result
}

// Extract host from URL
fn extract_host(url: &str) -> Option<&str> {
    // Parse wss://host.example.com/path -> host.example.com
    let without_scheme = url.strip_prefix("wss://").or_else(|| url.strip_prefix("ws://"))?;
    without_scheme.split('/').next()
}

// ============================================================================
// Child Process and Streaming I/O
// ============================================================================

/// A handle to a running command in a sprite
///
/// Created by [`Command::spawn`]. Provides access to stdin, stdout, and stderr
/// streams, and allows waiting for the command to complete.
///
/// # Example
///
/// ```no_run
/// use sprites::SpritesClient;
/// use tokio::io::{AsyncReadExt, AsyncWriteExt};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = SpritesClient::new("token");
///     let sprite = client.sprite("my-sprite");
///
///     let mut child = sprite.command("bash").tty(true).spawn().await?;
///
///     // Resize the terminal
///     child.resize(24, 80)?;
///
///     // Wait for it to complete
///     let status = child.wait().await?;
///     Ok(())
/// }
/// ```
pub struct Child {
    /// Handle for sending stdin data
    stdin: Option<ChildStdin>,
    /// Handle for receiving stdout data
    stdout: Option<ChildStdout>,
    /// Handle for receiving stderr data
    stderr: Option<ChildStderr>,
    /// Channel to send control messages (resize, kill)
    control_tx: mpsc::Sender<ControlMessage>,
    /// Receiver for exit status
    exit_rx: Option<oneshot::Receiver<i32>>,
    /// Whether this is a TTY session
    tty: bool,
}

/// Control messages sent to the WebSocket handler
enum ControlMessage {
    /// Send data to stdin
    Stdin(Vec<u8>),
    /// Close stdin (send EOF)
    StdinClose,
    /// Resize the terminal (rows, cols)
    Resize { rows: u16, cols: u16 },
    /// Kill the process
    Kill,
}

impl Child {
    /// Get a mutable reference to the stdin handle
    ///
    /// Returns `None` if stdin was already taken.
    pub fn stdin(&mut self) -> Option<&mut ChildStdin> {
        self.stdin.as_mut()
    }

    /// Get a mutable reference to the stdout handle
    ///
    /// Returns `None` if stdout was already taken.
    pub fn stdout(&mut self) -> Option<&mut ChildStdout> {
        self.stdout.as_mut()
    }

    /// Get a mutable reference to the stderr handle
    ///
    /// Returns `None` if stderr was already taken.
    pub fn stderr(&mut self) -> Option<&mut ChildStderr> {
        self.stderr.as_mut()
    }

    /// Take ownership of the stdin handle
    ///
    /// After calling this, `stdin()` will return `None`.
    pub fn take_stdin(&mut self) -> Option<ChildStdin> {
        self.stdin.take()
    }

    /// Take ownership of the stdout handle
    ///
    /// After calling this, `stdout()` will return `None`.
    pub fn take_stdout(&mut self) -> Option<ChildStdout> {
        self.stdout.take()
    }

    /// Take ownership of the stderr handle
    ///
    /// After calling this, `stderr()` will return `None`.
    pub fn take_stderr(&mut self) -> Option<ChildStderr> {
        self.stderr.take()
    }

    /// Resize the terminal
    ///
    /// Only works in TTY mode. Sends a resize message to the server.
    pub fn resize(&mut self, rows: u16, cols: u16) -> Result<()> {
        if !self.tty {
            return Err(Error::InvalidResponse(
                "resize() only works in TTY mode".to_string(),
            ));
        }
        self.control_tx
            .try_send(ControlMessage::Resize { rows, cols })
            .map_err(|_| Error::InvalidResponse("Child process already exited".to_string()))
    }

    /// Attempt to kill the process
    ///
    /// This closes the WebSocket connection, which should terminate the process.
    pub fn kill(&mut self) -> Result<()> {
        self.control_tx
            .try_send(ControlMessage::Kill)
            .map_err(|_| Error::InvalidResponse("Child process already exited".to_string()))
    }

    /// Wait for the process to complete and return the exit status
    pub async fn wait(&mut self) -> Result<ExitStatus> {
        match self.exit_rx.take() {
            Some(rx) => {
                let code = rx.await.unwrap_or(1);
                Ok(ExitStatus::new(code))
            }
            None => Err(Error::InvalidResponse(
                "wait() already called or child not started".to_string(),
            )),
        }
    }

    /// Check if the process is running in TTY mode
    pub fn is_tty(&self) -> bool {
        self.tty
    }
}

/// Handle for writing to a child's stdin
pub struct ChildStdin {
    control_tx: mpsc::Sender<ControlMessage>,
}

impl ChildStdin {
    /// Write data to stdin
    pub async fn write(&self, data: &[u8]) -> Result<()> {
        self.control_tx
            .send(ControlMessage::Stdin(data.to_vec()))
            .await
            .map_err(|_| Error::InvalidResponse("Child process already exited".to_string()))
    }

    /// Write all data to stdin
    pub async fn write_all(&self, data: &[u8]) -> Result<()> {
        self.write(data).await
    }

    /// Close stdin (send EOF)
    pub async fn close(&self) -> Result<()> {
        self.control_tx
            .send(ControlMessage::StdinClose)
            .await
            .map_err(|_| Error::InvalidResponse("Child process already exited".to_string()))
    }
}

/// Handle for reading from a child's stdout
pub struct ChildStdout {
    rx: mpsc::Receiver<Vec<u8>>,
    buffer: Vec<u8>,
}

impl ChildStdout {
    /// Read data from stdout
    ///
    /// Returns the number of bytes read, or 0 if the stream is closed.
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // First, drain any buffered data
        if !self.buffer.is_empty() {
            let n = std::cmp::min(buf.len(), self.buffer.len());
            buf[..n].copy_from_slice(&self.buffer[..n]);
            self.buffer.drain(..n);
            return Ok(n);
        }

        // Wait for new data
        match self.rx.recv().await {
            Some(data) => {
                let n = std::cmp::min(buf.len(), data.len());
                buf[..n].copy_from_slice(&data[..n]);
                if n < data.len() {
                    self.buffer.extend_from_slice(&data[n..]);
                }
                Ok(n)
            }
            None => Ok(0), // Stream closed
        }
    }

    /// Read all available data into a Vec
    pub async fn read_to_end(&mut self) -> Result<Vec<u8>> {
        let mut result = std::mem::take(&mut self.buffer);
        while let Some(data) = self.rx.recv().await {
            result.extend(data);
        }
        Ok(result)
    }

    /// Read all available data as a string
    pub async fn read_to_string(&mut self) -> Result<String> {
        let data = self.read_to_end().await?;
        Ok(String::from_utf8_lossy(&data).to_string())
    }
}

/// Handle for reading from a child's stderr
pub struct ChildStderr {
    rx: mpsc::Receiver<Vec<u8>>,
    buffer: Vec<u8>,
}

impl ChildStderr {
    /// Read data from stderr
    ///
    /// Returns the number of bytes read, or 0 if the stream is closed.
    pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // First, drain any buffered data
        if !self.buffer.is_empty() {
            let n = std::cmp::min(buf.len(), self.buffer.len());
            buf[..n].copy_from_slice(&self.buffer[..n]);
            self.buffer.drain(..n);
            return Ok(n);
        }

        // Wait for new data
        match self.rx.recv().await {
            Some(data) => {
                let n = std::cmp::min(buf.len(), data.len());
                buf[..n].copy_from_slice(&data[..n]);
                if n < data.len() {
                    self.buffer.extend_from_slice(&data[n..]);
                }
                Ok(n)
            }
            None => Ok(0), // Stream closed
        }
    }

    /// Read all available data into a Vec
    pub async fn read_to_end(&mut self) -> Result<Vec<u8>> {
        let mut result = std::mem::take(&mut self.buffer);
        while let Some(data) = self.rx.recv().await {
            result.extend(data);
        }
        Ok(result)
    }

    /// Read all available data as a string
    pub async fn read_to_string(&mut self) -> Result<String> {
        let data = self.read_to_end().await?;
        Ok(String::from_utf8_lossy(&data).to_string())
    }

    /// Create a new ChildStderr (for internal use)
    #[doc(hidden)]
    pub fn new_public(rx: mpsc::Receiver<Vec<u8>>) -> Self {
        Self {
            rx,
            buffer: Vec::new(),
        }
    }
}

// ============================================================================
// Public constructors for internal use by other modules
// ============================================================================

/// Control messages for public API
pub enum ControlMessagePublic {
    /// Send data to stdin
    Stdin(Vec<u8>),
    /// Resize the terminal
    Resize { rows: u16, cols: u16 },
    /// Kill the process
    Kill,
}

impl Child {
    /// Create a new Child (for internal use)
    #[doc(hidden)]
    pub fn new_public(
        stdin: Option<ChildStdin>,
        stdout: Option<ChildStdout>,
        stderr: Option<ChildStderr>,
        control_tx: mpsc::Sender<ControlMessagePublic>,
        exit_rx: Option<oneshot::Receiver<i32>>,
        tty: bool,
    ) -> Self {
        // We need to convert control_tx to accept ControlMessage
        // For now, just use a simple wrapper
        let (internal_tx, mut internal_rx) = mpsc::channel::<ControlMessage>(32);

        // Spawn a task to forward public control messages to internal ones
        let external_tx = control_tx;
        tokio::spawn(async move {
            while let Some(msg) = internal_rx.recv().await {
                let public_msg = match msg {
                    ControlMessage::Stdin(data) => ControlMessagePublic::Stdin(data),
                    ControlMessage::StdinClose => continue, // Not supported in public API
                    ControlMessage::Resize { rows, cols } => {
                        ControlMessagePublic::Resize { rows, cols }
                    }
                    ControlMessage::Kill => ControlMessagePublic::Kill,
                };
                if external_tx.send(public_msg).await.is_err() {
                    break;
                }
            }
        });

        Self {
            stdin,
            stdout,
            stderr,
            control_tx: internal_tx,
            exit_rx,
            tty,
        }
    }
}

impl ChildStdin {
    /// Create a new ChildStdin (for internal use)
    #[doc(hidden)]
    pub fn new_public(control_tx: mpsc::Sender<ControlMessagePublic>) -> Self {
        // Convert to internal control message channel
        let (internal_tx, mut internal_rx) = mpsc::channel::<ControlMessage>(32);

        let external_tx = control_tx;
        tokio::spawn(async move {
            while let Some(msg) = internal_rx.recv().await {
                let public_msg = match msg {
                    ControlMessage::Stdin(data) => ControlMessagePublic::Stdin(data),
                    ControlMessage::StdinClose => continue,
                    ControlMessage::Resize { rows, cols } => {
                        ControlMessagePublic::Resize { rows, cols }
                    }
                    ControlMessage::Kill => ControlMessagePublic::Kill,
                };
                if external_tx.send(public_msg).await.is_err() {
                    break;
                }
            }
        });

        Self {
            control_tx: internal_tx,
        }
    }
}

impl ChildStdout {
    /// Create a new ChildStdout (for internal use)
    #[doc(hidden)]
    pub fn new_public(rx: mpsc::Receiver<Vec<u8>>) -> Self {
        Self {
            rx,
            buffer: Vec::new(),
        }
    }
}

/// Public base64 encoder (for internal use by other modules)
#[doc(hidden)]
pub fn base64_encode_public(data: &[u8]) -> String {
    base64_encode(data)
}