libtmux 0.1.0-alpha.1

Async typed tmux client and object model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
use std::borrow::Cow;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::process::ExitStatusExt;
use std::process::ExitStatus;

const MAX_DIAGNOSTIC_BYTES: usize = 64;
const REDACTED_ARGUMENT: &str = "<redacted>";
const TRUNCATED_TOKEN: &str = "<truncated>";

#[derive(Clone, Copy)]
enum ArgumentSensitivity {
    Public,
    Sensitive,
}

#[derive(Clone)]
struct CommandArg {
    value: OsString,
    sensitivity: ArgumentSensitivity,
}

impl CommandArg {
    fn public(value: OsString) -> Self {
        Self {
            value,
            sensitivity: ArgumentSensitivity::Public,
        }
    }

    fn sensitive(value: OsString) -> Self {
        Self {
            value,
            sensitivity: ArgumentSensitivity::Sensitive,
        }
    }

    fn diagnostic(&self) -> SummaryArgument {
        match self.sensitivity {
            ArgumentSensitivity::Public => SummaryArgument::Public(escape_diagnostic(&self.value)),
            ArgumentSensitivity::Sensitive => SummaryArgument::Sensitive,
        }
    }

    fn lower(&self) -> OsString {
        lower_logical_token(&self.value)
    }

    /// Return the argument's own bytes.
    ///
    /// Only used to recover a target from a failed request, which is a
    /// public value; a sensitive argument is never a `-t` target.
    fn value(&self) -> &OsStr {
        &self.value
    }
}

impl fmt::Debug for CommandArg {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandArg")
            .field("diagnostic", &self.diagnostic().as_str())
            .finish()
    }
}

#[derive(Clone, Eq, PartialEq)]
enum SummaryArgument {
    Public(String),
    Sensitive,
}

impl SummaryArgument {
    fn as_str(&self) -> &str {
        match self {
            Self::Public(value) => value,
            Self::Sensitive => REDACTED_ARGUMENT,
        }
    }
}

/// A logical tmux command with classified diagnostic arguments.
///
/// Commands retain operating-system strings so dispatch can preserve arbitrary
/// Unix bytes. Use [`Command::summary`] for a bounded, sanitized diagnostic
/// representation.
///
/// # Examples
///
/// ```
/// use libtmux::Command;
///
/// let command = Command::new("display-message").arg("hello");
/// assert_eq!(command.summary().argument_count(), 1);
/// ```
#[derive(Clone)]
#[must_use = "a command has no effect until it is dispatched"]
pub struct Command {
    subcommand: CommandArg,
    arguments: Vec<CommandArg>,
}

impl Command {
    /// Start a command with one logical tmux subcommand token.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let command = Command::new("list-sessions");
    /// assert_eq!(command.summary().to_string(), r#""list-sessions""#);
    /// ```
    #[must_use = "a command has no effect until it is dispatched"]
    pub fn new(subcommand: impl Into<OsString>) -> Self {
        Self {
            subcommand: CommandArg::public(subcommand.into()),
            arguments: Vec::new(),
        }
    }

    /// Append one public logical argument.
    ///
    /// Public arguments appear in bounded, escaped diagnostic summaries.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let command = Command::new("display-message").arg("hello");
    /// assert_eq!(command.summary().public_argument_count(), 1);
    /// ```
    #[must_use = "use the returned command to retain the appended argument"]
    /// Render this command as one control-mode line.
    ///
    /// Returns `None` when a token is not valid UTF-8, because control mode
    /// is a text protocol and no escaping in it can carry those bytes.
    /// Return the value of the command's `-t` flag, when it has one.
    ///
    /// Used to name the object in a failure. tmux does not always repeat the
    /// target it could not resolve, so this recovers it from the request.
    ///
    /// The first `-t` wins, which is what tmux does: it parses flags before
    /// positionals. A positional that happens to read `-t` can only be
    /// reached after tmux has already taken the flag, so the worst case is a
    /// mislabelled error rather than a wrong one.
    pub(crate) fn target(&self) -> Option<&OsStr> {
        let mut arguments = self.arguments.iter();
        while let Some(argument) = arguments.next() {
            if argument.value() == OsStr::new("-t") {
                return arguments.next().map(CommandArg::value);
            }
        }

        None
    }

    #[cfg(feature = "control-mode")]
    pub(crate) fn control_mode_line(&self) -> Option<String> {
        let mut line = render_control_mode_token(&self.subcommand.value)?;
        for argument in &self.arguments {
            line.push(' ');
            line.push_str(&render_control_mode_token(&argument.value)?);
        }

        Some(line)
    }

    /// Append one public argument.
    pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
        self.arguments.push(CommandArg::public(argument.into()));
        self
    }

    /// Append one sensitive logical argument.
    ///
    /// The value is dispatched exactly but diagnostics use one
    /// length-independent redaction marker.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let command = Command::new("set-environment")
    ///     .arg("TOKEN")
    ///     .sensitive_arg("secret");
    /// assert_eq!(command.summary().sensitive_argument_count(), 1);
    /// assert!(!command.summary().to_string().contains("secret"));
    /// ```
    #[must_use = "use the returned command to retain the appended sensitive argument"]
    pub fn sensitive_arg(mut self, argument: impl Into<OsString>) -> Self {
        self.arguments.push(CommandArg::sensitive(argument.into()));
        self
    }

    /// Build a bounded, sanitized summary of the logical command.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let summary = Command::new("display-message").arg("value;").summary();
    /// assert_eq!(summary.to_string(), r#""display-message" "value;""#);
    /// ```
    #[must_use]
    pub fn summary(&self) -> CommandSummary {
        let arguments: Vec<_> = self.arguments.iter().map(CommandArg::diagnostic).collect();
        let sensitive_argument_count = arguments
            .iter()
            .filter(|argument| matches!(argument, SummaryArgument::Sensitive))
            .count();

        CommandSummary {
            subcommand: escape_diagnostic(&self.subcommand.value),
            public_argument_count: arguments.len() - sensitive_argument_count,
            sensitive_argument_count,
            arguments,
        }
    }
}

impl fmt::Debug for Command {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Command")
            .field("summary", &self.summary())
            .finish()
    }
}

/// A bounded, sanitized diagnostic view of a logical [`Command`].
///
/// Render one token for a control-mode command line.
///
/// Control mode takes a line that tmux parses, not an argv, so a token
/// holding a space or a quote has to survive that parse. Anything outside a
/// conservative safe set is double quoted with `\` and `"` escaped, which is
/// what tmux's own parser undoes.
///
/// A token holding a byte that is not valid UTF-8 cannot be written to a text
/// protocol at all, so this reports that rather than corrupting it.
#[cfg(feature = "control-mode")]
fn render_control_mode_token(value: &OsStr) -> Option<String> {
    use std::os::unix::ffi::OsStrExt as _;

    let text = std::str::from_utf8(value.as_bytes()).ok()?;
    let safe = !text.is_empty()
        && text
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b"-_./=@%:,+".contains(&byte));
    if safe {
        return Some(text.to_owned());
    }

    let mut rendered = String::with_capacity(text.len() + 2);
    rendered.push('"');
    for character in text.chars() {
        if matches!(character, '\\' | '"') {
            rendered.push('\\');
        }
        rendered.push(character);
    }
    rendered.push('"');

    Some(rendered)
}

/// Every public token is ASCII escaped. Sensitive arguments are represented by
/// a fixed marker that discloses neither their bytes nor their length.
#[derive(Clone, Eq, PartialEq)]
pub struct CommandSummary {
    subcommand: String,
    arguments: Vec<SummaryArgument>,
    public_argument_count: usize,
    sensitive_argument_count: usize,
}

impl CommandSummary {
    /// Return the number of logical arguments after the subcommand.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let summary = Command::new("set-option").arg("-g").arg("mouse").summary();
    /// assert_eq!(summary.argument_count(), 2);
    /// ```
    #[must_use]
    pub const fn argument_count(&self) -> usize {
        self.public_argument_count + self.sensitive_argument_count
    }

    /// Return the number of public logical arguments.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let summary = Command::new("set-option").arg("mouse").summary();
    /// assert_eq!(summary.public_argument_count(), 1);
    /// ```
    #[must_use]
    pub const fn public_argument_count(&self) -> usize {
        self.public_argument_count
    }

    /// Return the number of sensitive logical arguments.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::Command;
    ///
    /// let summary = Command::new("set-environment").sensitive_arg("secret").summary();
    /// assert_eq!(summary.sensitive_argument_count(), 1);
    /// ```
    #[must_use]
    pub const fn sensitive_argument_count(&self) -> usize {
        self.sensitive_argument_count
    }
}

impl fmt::Display for CommandSummary {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "\"{}\"", self.subcommand)?;
        for argument in &self.arguments {
            match argument {
                SummaryArgument::Public(value) => write!(formatter, " \"{value}\"")?,
                SummaryArgument::Sensitive => write!(formatter, " {REDACTED_ARGUMENT}")?,
            }
        }
        Ok(())
    }
}

impl fmt::Debug for CommandSummary {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandSummary")
            .field("diagnostic", &self.to_string())
            .field("argument_count", &self.argument_count())
            .field("public_argument_count", &self.public_argument_count)
            .field("sensitive_argument_count", &self.sensitive_argument_count)
            .finish_non_exhaustive()
    }
}

fn escape_diagnostic(value: &OsStr) -> String {
    let bytes = value.as_bytes();
    let mut escaped = String::with_capacity(bytes.len().min(MAX_DIAGNOSTIC_BYTES));

    for &byte in bytes.iter().take(MAX_DIAGNOSTIC_BYTES) {
        match byte {
            b'\n' => escaped.push_str("\\n"),
            b'\r' => escaped.push_str("\\r"),
            b'\t' => escaped.push_str("\\t"),
            b'\\' => escaped.push_str("\\\\"),
            b'"' => escaped.push_str("\\\""),
            b' '..=b'~' => escaped.push(char::from(byte)),
            _ => push_hex_escape(&mut escaped, byte),
        }
    }
    if bytes.len() > MAX_DIAGNOSTIC_BYTES {
        escaped.push_str(TRUNCATED_TOKEN);
    }
    escaped
}

fn push_hex_escape(output: &mut String, byte: u8) {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    output.push_str("\\x");
    output.push(char::from(HEX[usize::from(byte >> 4)]));
    output.push(char::from(HEX[usize::from(byte & 0x0f)]));
}

fn lower_logical_token(value: &OsStr) -> OsString {
    let bytes = value.as_bytes();
    if bytes.last() != Some(&b';') {
        return value.to_os_string();
    }

    let mut lowered = Vec::with_capacity(bytes.len() + 1);
    lowered.extend_from_slice(&bytes[..bytes.len() - 1]);
    lowered.push(b'\\');
    lowered.push(b';');
    OsString::from_vec(lowered)
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct RequestId(u64);

impl RequestId {
    pub(crate) const fn new(value: u64) -> Self {
        Self(value)
    }

    pub(crate) const fn get(self) -> u64 {
        self.0
    }
}

pub(crate) struct CommandRequest {
    request_id: RequestId,
    command: CommandSummary,
    argv: Vec<OsString>,
    logical_subcommand_index: usize,
}

impl CommandRequest {
    pub(crate) fn new(request_id: RequestId, command: Command) -> Self {
        Self::with_global_argv(request_id, &[], command)
    }

    pub(crate) fn with_global_argv(
        request_id: RequestId,
        global_argv: &[OsString],
        command: Command,
    ) -> Self {
        let summary = command.summary();
        let Command {
            subcommand,
            arguments,
        } = command;
        let mut argv = Vec::with_capacity(global_argv.len() + arguments.len() + 1);
        argv.extend_from_slice(global_argv);
        let logical_subcommand_index = argv.len();
        argv.push(subcommand.lower());
        argv.extend(arguments.iter().map(CommandArg::lower));

        Self {
            request_id,
            command: summary,
            argv,
            logical_subcommand_index,
        }
    }

    pub(crate) const fn request_id(&self) -> RequestId {
        self.request_id
    }

    pub(crate) fn summary(&self) -> &CommandSummary {
        &self.command
    }

    pub(crate) fn argv(&self) -> &[OsString] {
        &self.argv
    }

    pub(crate) const fn logical_subcommand_index(&self) -> usize {
        self.logical_subcommand_index
    }
}

impl fmt::Debug for CommandRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandRequest")
            .field("request_id", &self.request_id)
            .field("command", &self.command)
            .finish_non_exhaustive()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ProcessStatus {
    success: bool,
    code: Option<i32>,
    signal: Option<i32>,
}

impl ProcessStatus {
    pub(crate) fn from_exit_status(status: ExitStatus) -> Self {
        Self {
            success: status.success(),
            code: status.code(),
            signal: status.signal(),
        }
    }

    pub(crate) const fn success(self) -> bool {
        self.success
    }

    pub(crate) const fn code(self) -> Option<i32> {
        self.code
    }

    pub(crate) const fn signal(self) -> Option<i32> {
        self.signal
    }
}

/// The exact status and output captured for one tmux command.
///
/// A non-zero exit status is returned as data. Output bytes are never trimmed,
/// decoded, or mirrored between streams.
pub struct CommandResult {
    request_id: RequestId,
    command: CommandSummary,
    status: ProcessStatus,
    stdout: Vec<u8>,
    stderr: Vec<u8>,
}

impl CommandResult {
    pub(crate) fn new(
        request_id: RequestId,
        command: CommandSummary,
        status: ProcessStatus,
        stdout: Vec<u8>,
        stderr: Vec<u8>,
    ) -> Self {
        Self {
            request_id,
            command,
            status,
            stdout,
            stderr,
        }
    }

    /// Return the Core-scoped dispatch-request identity.
    ///
    /// The Core allocates this value before validation, so an error can expose
    /// an ID even when no process was spawned. Clones of one [`crate::Server`]
    /// share the allocating Core. The ID is not globally unique, a process ID,
    /// an internal attempt ID, or a control-mode protocol-block ID.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-id.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// assert!(result.request_id() > 0);
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn request_id(&self) -> u64 {
        self.request_id.get()
    }

    /// Return the sanitized logical command summary.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-command.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// assert_eq!(result.command().to_string(), r#""list-sessions""#);
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn command(&self) -> &CommandSummary {
        &self.command
    }

    /// Return stdout exactly as captured.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stdout.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _: &[u8] = result.stdout();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn stdout(&self) -> &[u8] {
        &self.stdout
    }

    /// Return stderr exactly as captured.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stderr.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _: &[u8] = result.stderr();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn stderr(&self) -> &[u8] {
        &self.stderr
    }

    /// Consume the result and return its exact stdout and stderr buffers.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-streams.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let (_stdout, _stderr) = result.into_streams();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn into_streams(self) -> (Vec<u8>, Vec<u8>) {
        (self.stdout, self.stderr)
    }

    /// Borrow stdout as UTF-8 without copying or replacement.
    ///
    /// # Errors
    ///
    /// Returns the borrowed decoding error when stdout is not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stdout-utf8.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _text = result.stdout_utf8()?;
    /// server.shutdown().await?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn stdout_utf8(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.stdout)
    }

    /// Borrow stderr as UTF-8 without copying or replacement.
    ///
    /// # Errors
    ///
    /// Returns the borrowed decoding error when stderr is not valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stderr-utf8.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _text = result.stderr_utf8()?;
    /// server.shutdown().await?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn stderr_utf8(&self) -> Result<&str, std::str::Utf8Error> {
        std::str::from_utf8(&self.stderr)
    }

    /// Return a named lossy UTF-8 view of stdout.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stdout-lossy.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _text = result.stdout_lossy();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn stdout_lossy(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stdout)
    }

    /// Return a named lossy UTF-8 view of stderr.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-stderr-lossy.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _text = result.stderr_lossy();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn stderr_lossy(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stderr)
    }

    /// Return whether the process exited successfully.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-success.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// let _success = result.success();
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn success(&self) -> bool {
        self.status.success()
    }

    /// Return the process exit code, or `None` when it ended by signal.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-code.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// assert!(result.exit_code().is_some());
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn exit_code(&self) -> Option<i32> {
        self.status.code()
    }

    /// Return the terminating signal, or `None` for an ordinary exit.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// let server = libtmux::Server::builder().socket_path("/tmp/libtmux-result-signal.sock").build()?;
    /// let result = server.cmd(libtmux::Command::new("list-sessions")).await?;
    /// assert!(result.signal().is_none());
    /// server.shutdown().await?;
    /// # Ok::<(), libtmux::Error>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn signal(&self) -> Option<i32> {
        self.status.signal()
    }
}

impl fmt::Debug for CommandResult {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CommandResult")
            .field("request_id", &self.request_id)
            .field("command", &self.command)
            .field("status", &self.status)
            .field("stdout_len", &self.stdout.len())
            .field("stderr_len", &self.stderr.len())
            .finish()
    }
}

#[cfg(test)]
mod tests {

    use std::borrow::Cow;
    use std::error::Error as StdError;
    use std::ffi::OsString;
    use std::fmt::Display;
    use std::os::unix::ffi::{OsStrExt, OsStringExt};
    use std::os::unix::process::ExitStatusExt;

    use static_assertions::{assert_impl_all, assert_not_impl_any};

    use super::*;

    assert_impl_all!(CommandArg: Send, Sync);
    assert_impl_all!(CommandRequest: Send, Sync);
    assert_impl_all!(CommandResult: Send, Sync);
    assert_impl_all!(RequestId: Send, Sync);
    assert_impl_all!(ProcessStatus: Send, Sync);
    assert_not_impl_any!(CommandResult: Display);
    assert_not_impl_any!(CommandRequest: Clone);

    fn argv_bytes(request: &CommandRequest) -> Vec<Vec<u8>> {
        request
            .argv()
            .iter()
            .map(|argument| argument.as_os_str().as_bytes().to_vec())
            .collect()
    }

    fn exit_status(code: i32) -> ExitStatus {
        ExitStatus::from_raw(code << 8)
    }

    fn command_result(
        command: Command,
        status: ExitStatus,
        stdout: &[u8],
        stderr: &[u8],
    ) -> CommandResult {
        let request = CommandRequest::new(RequestId::new(7), command);
        CommandResult::new(
            request.request_id(),
            request.summary().clone(),
            ProcessStatus::from_exit_status(status),
            stdout.to_vec(),
            stderr.to_vec(),
        )
    }

    #[test]
    fn dispatch_lowering_escapes_only_each_final_semicolon() {
        let cases: &[(&[u8], &[u8])] = &[
            (b";", b"\\;"),
            (b"value;", b"value\\;"),
            (b"a;b", b"a;b"),
            (b"\\;", b"\\\\;"),
            (b"\\\\;", b"\\\\\\;"),
            (b";;", b";\\;"),
            (b"plain", b"plain"),
        ];

        for (logical, physical) in cases {
            let argument = OsString::from_vec(logical.to_vec());
            let request =
                CommandRequest::new(RequestId::new(11), Command::new("cmd").arg(argument));
            assert_eq!(argv_bytes(&request), [b"cmd".to_vec(), physical.to_vec()]);
        }
    }

    #[test]
    fn dispatch_lowering_applies_to_every_argv_position() {
        let request = CommandRequest::new(
            RequestId::new(12),
            Command::new(";")
                .arg("first;")
                .arg("middle;")
                .arg("last;")
                .arg("after"),
        );

        assert_eq!(
            argv_bytes(&request),
            [
                b"\\;".to_vec(),
                b"first\\;".to_vec(),
                b"middle\\;".to_vec(),
                b"last\\;".to_vec(),
                b"after".to_vec(),
            ],
        );
    }

    #[test]
    fn dispatch_lowering_preserves_non_utf8_prefixes() {
        let logical = OsString::from_vec(b"\xffvalue;".to_vec());
        let request = CommandRequest::new(RequestId::new(13), Command::new(logical));

        assert_eq!(argv_bytes(&request), [b"\xffvalue\\;".to_vec()]);
    }

    #[test]
    fn command_summary_remains_logical_after_dispatch_lowering() {
        let request = CommandRequest::new(
            RequestId::new(14),
            Command::new("display-message").arg("value;"),
        );

        assert_eq!(
            request.summary().to_string(),
            r#""display-message" "value;""#
        );
        assert_eq!(
            argv_bytes(&request),
            [b"display-message".to_vec(), b"value\\;".to_vec()]
        );
    }

    #[test]
    fn request_preserves_the_dispatch_id_supplied_by_the_executor_owner() {
        let command = Command::new("display-message").arg("same");
        let cloned = command.clone();
        assert_eq!(command.summary(), cloned.summary());

        let first = CommandRequest::new(RequestId::new(101), command);
        let second = CommandRequest::new(RequestId::new(102), cloned);

        assert_eq!(first.request_id(), RequestId::new(101));
        assert_eq!(second.request_id(), RequestId::new(102));
    }

    #[test]
    fn sensitive_argument_lowering_preserves_bytes_while_diagnostics_redact() {
        let sensitive = OsString::from_vec(b"\xffsentinel-secret;".to_vec());
        let request = CommandRequest::new(
            RequestId::new(103),
            Command::new("set-environment")
                .arg("TOKEN")
                .sensitive_arg(sensitive),
        );

        assert_eq!(
            argv_bytes(&request),
            [
                b"set-environment".to_vec(),
                b"TOKEN".to_vec(),
                b"\xffsentinel-secret\\;".to_vec(),
            ],
        );
        for diagnostic in [
            format!("{request:?}"),
            format!("{:?}", request.summary()),
            request.summary().to_string(),
        ] {
            assert!(!diagnostic.contains("sentinel-secret"));
            assert!(!diagnostic.contains("\\xff"));
        }
    }

    #[test]
    fn process_status_preserves_exit_and_signal_outcomes() {
        let success = ProcessStatus::from_exit_status(exit_status(0));
        let failure = ProcessStatus::from_exit_status(exit_status(7));
        let signal = ProcessStatus::from_exit_status(ExitStatus::from_raw(15));

        assert!(success.success());
        assert_eq!(success.code(), Some(0));
        assert_eq!(success.signal(), None);
        assert!(!failure.success());
        assert_eq!(failure.code(), Some(7));
        assert_eq!(failure.signal(), None);
        assert!(!signal.success());
        assert_eq!(signal.code(), None);
        assert_eq!(signal.signal(), Some(15));
    }

    #[test]
    fn command_results_preserve_exact_output_bytes_and_trailing_blank_lines() {
        let result = command_result(
            Command::new("display-message"),
            exit_status(0),
            b"first\n\n",
            b"warning\n\n",
        );

        assert_eq!(result.request_id(), 7);
        assert_eq!(result.command().to_string(), r#""display-message""#);
        assert_eq!(result.stdout(), b"first\n\n");
        assert_eq!(result.stderr(), b"warning\n\n");
        let (stdout, stderr) = result.into_streams();
        assert_eq!(stdout, b"first\n\n");
        assert_eq!(stderr, b"warning\n\n");
    }

    #[test]
    fn command_results_offer_borrowed_strict_and_named_lossy_views() {
        let valid = command_result(Command::new("show-messages"), exit_status(0), b"ok\n", b"");
        assert_eq!(valid.stdout_utf8().expect("fixture is UTF-8"), "ok\n");
        assert!(matches!(valid.stdout_lossy(), Cow::Borrowed("ok\n")));

        let invalid = command_result(
            Command::new("show-messages"),
            exit_status(0),
            b"before\xffafter",
            b"error\xfe",
        );
        assert_eq!(
            invalid
                .stdout_utf8()
                .expect_err("fixture is not UTF-8")
                .valid_up_to(),
            6,
        );
        assert_eq!(
            invalid
                .stderr_utf8()
                .expect_err("fixture is not UTF-8")
                .valid_up_to(),
            5,
        );
        assert!(matches!(invalid.stdout_lossy(), Cow::Owned(_)));
        assert!(matches!(invalid.stderr_lossy(), Cow::Owned(_)));
    }

    #[test]
    fn borrowed_utf8_errors_never_own_or_debug_rejected_output() {
        let result = command_result(
            Command::new("show-messages"),
            exit_status(0),
            b"sentinel-secret\xff",
            b"",
        );
        let error = result
            .stdout_utf8()
            .expect_err("fixture contains an invalid UTF-8 byte");

        assert!(!format!("{error:?}").contains("sentinel-secret"));
        assert!(!error.to_string().contains("sentinel-secret"));
        assert!(StdError::source(&error).is_none());
    }

    #[test]
    fn nonzero_has_session_output_is_not_mirrored_or_promoted_to_an_error() {
        let result = command_result(
            Command::new("has-session").arg("-t").arg("missing"),
            exit_status(1),
            b"",
            b"can't find session: missing\n",
        );

        assert!(!result.success());
        assert_eq!(result.exit_code(), Some(1));
        assert_eq!(result.stdout(), b"");
        assert_eq!(result.stderr(), b"can't find session: missing\n");
    }

    #[test]
    fn sensitive_arguments_and_output_are_absent_from_private_debug_surfaces() {
        let sensitive = CommandArg::sensitive(OsString::from("sentinel-secret"));
        let command = Command::new("set-environment")
            .arg("TOKEN")
            .sensitive_arg("sentinel-secret");
        let summary = command.summary();
        let result = command_result(
            command.clone(),
            exit_status(7),
            b"sentinel-secret stdout",
            b"sentinel-secret stderr",
        );

        for diagnostic in [
            format!("{sensitive:?}"),
            format!("{command:?}"),
            format!("{summary:?}"),
            summary.to_string(),
            format!("{result:?}"),
        ] {
            assert!(!diagnostic.contains("sentinel-secret"));
        }
        assert!(
            result
                .stdout()
                .windows(15)
                .any(|bytes| bytes == b"sentinel-secret")
        );
        assert!(
            result
                .stderr()
                .windows(15)
                .any(|bytes| bytes == b"sentinel-secret")
        );
        let debug = format!("{result:?}");
        assert!(debug.contains("stdout_len"));
        assert!(debug.contains("stderr_len"));
        assert!(debug.contains("<redacted>"));
    }

    #[test]
    fn command_arg_public_debug_is_ascii_escaped_and_bounded() {
        let escaped = CommandArg::public(OsString::from_vec(b"line\n\xff".to_vec()));
        let bounded = CommandArg::public(OsString::from_vec(vec![b'a'; 128]));
        let escaped_debug = format!("{escaped:?}");
        let bounded_debug = format!("{bounded:?}");

        assert!(escaped_debug.is_ascii());
        assert!(escaped_debug.contains("\\n"));
        assert!(escaped_debug.contains("\\xff"));
        assert!(bounded_debug.contains("<truncated>"));
        assert!(bounded_debug.len() < 256);
    }
}