pty-mcp 0.2.0

An MCP server for PTY management with SSH connections, remote sessions, file access, and mounts
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
use std::{
    collections::BTreeMap,
    path::PathBuf,
    process::{Output, Stdio},
    time::Duration,
};

use anyhow::{Result, anyhow, bail};
use tokio::{
    io::{AsyncRead, AsyncReadExt},
    process::Command,
    task::JoinHandle,
};

use super::model::{SshAuthKind, SshConnectionSummary, SshMountSummary, SshTarget};

const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(8);
const DEFAULT_MOUNT_TIMEOUT: Duration = Duration::from_secs(15);
const DEFAULT_UNMOUNT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_CAPTURE_TIMEOUT: Duration = Duration::from_secs(20);

#[derive(Debug, Clone)]
pub struct SshConnectVerificationRequest {
    pub ssh_bin_path: Option<PathBuf>,
    pub target: SshTarget,
    pub auth_kind: SshAuthKind,
    pub identity_path: Option<PathBuf>,
    pub verify_host_key: bool,
    pub connect_timeout: Option<Duration>,
}

#[derive(Debug, Clone)]
pub struct SshSessionSpawnPlanRequest {
    pub ssh_bin_path: Option<PathBuf>,
    pub target: SshTarget,
    pub auth_kind: SshAuthKind,
    pub identity_path: Option<PathBuf>,
    pub verify_host_key: bool,
    pub command: Option<String>,
    pub args: Vec<String>,
    pub cwd: Option<String>,
    pub env: BTreeMap<String, String>,
    pub shell: Option<String>,
    pub interactive: bool,
    pub login: bool,
}

#[derive(Debug, Clone)]
pub struct SshExecPlanRequest {
    pub ssh_bin_path: Option<PathBuf>,
    pub target: SshTarget,
    pub auth_kind: SshAuthKind,
    pub identity_path: Option<PathBuf>,
    pub verify_host_key: bool,
    pub script: String,
    pub cwd: Option<String>,
    pub env: BTreeMap<String, String>,
    pub shell: Option<String>,
    pub login: bool,
}

#[derive(Debug, Clone)]
pub struct SshMountPlanRequest {
    pub mount: SshMountSummary,
    pub connection: SshConnectionSummary,
    pub auth_kind: SshAuthKind,
    pub identity_path: Option<PathBuf>,
    pub verify_host_key: bool,
    pub sshfs_bin_path: Option<PathBuf>,
}

#[derive(Debug, Clone)]
pub struct SshUnmountRequest {
    pub mount: SshMountSummary,
    pub force: bool,
    pub umount_bin_path: Option<PathBuf>,
    pub diskutil_bin_path: Option<PathBuf>,
}

#[derive(Debug, Clone)]
pub struct SshSessionSpawnPlan {
    pub command: String,
    pub args: Vec<String>,
    pub public_args: Vec<String>,
    pub remote_command: Option<String>,
}

#[derive(Debug, Default, Clone, Copy)]
pub struct SshRuntime;

impl SshRuntime {
    pub async fn verify_connection(&self, request: SshConnectVerificationRequest) -> Result<()> {
        let SshConnectVerificationRequest {
            ssh_bin_path,
            target,
            auth_kind,
            identity_path,
            verify_host_key,
            connect_timeout,
        } = request;

        let ssh_bin_path = ssh_bin_path
            .ok_or_else(|| capability_unavailable("ssh binary path is not configured"))?;
        if !ssh_bin_path.is_file() {
            return Err(capability_unavailable(format!(
                "ssh binary does not exist at {}",
                ssh_bin_path.display()
            )));
        }

        let connect_timeout = connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT);
        let args = build_verify_args(
            &target,
            &auth_kind,
            identity_path.as_ref(),
            verify_host_key,
            connect_timeout,
        );
        let output = run_verify_command(ssh_bin_path.clone(), args, connect_timeout).await?;

        if output.status.success() {
            return Ok(());
        }

        Err(map_ssh_failure(&target, output))
    }

    pub async fn mount(&self, request: SshMountPlanRequest) -> Result<()> {
        let sshfs_bin_path = request
            .sshfs_bin_path
            .clone()
            .ok_or_else(|| capability_unavailable("sshfs binary path is not configured"))?;
        if !sshfs_bin_path.is_file() {
            return Err(capability_unavailable(format!(
                "sshfs binary does not exist at {}",
                sshfs_bin_path.display()
            )));
        }

        let args = build_mount_args(&request);
        let output = run_command(
            sshfs_bin_path.clone(),
            args,
            DEFAULT_MOUNT_TIMEOUT,
            "ssh mount command timed out",
            "ssh mount task failed",
            "failed to execute ssh mount command",
        )
        .await?;

        if output.status.success() {
            return Ok(());
        }

        Err(map_mount_failure(&request, output))
    }

    pub fn build_session_spawn_plan(
        &self,
        request: SshSessionSpawnPlanRequest,
    ) -> Result<SshSessionSpawnPlan> {
        let ssh_bin_path = ensure_ssh_binary(request.ssh_bin_path)?;

        let remote_command = build_remote_command(
            request.command.as_deref(),
            &request.args,
            request.cwd.as_deref(),
            &request.env,
            request.shell.as_deref(),
            request.login,
        )?;

        Ok(build_ssh_session_plan(
            ssh_bin_path,
            request.target,
            request.auth_kind,
            request.identity_path,
            request.verify_host_key,
            request.interactive,
            remote_command,
        ))
    }

    pub fn build_exec_plan(&self, request: SshExecPlanRequest) -> Result<SshSessionSpawnPlan> {
        let ssh_bin_path = ensure_ssh_binary(request.ssh_bin_path)?;
        let remote_command = build_remote_exec_command(
            &request.script,
            request.cwd.as_deref(),
            &request.env,
            request.shell.as_deref(),
            request.login,
        )?;

        Ok(build_ssh_session_plan(
            ssh_bin_path,
            request.target,
            request.auth_kind,
            request.identity_path,
            request.verify_host_key,
            true,
            Some(remote_command),
        ))
    }

    pub async fn exec_capture(
        &self,
        request: SshExecPlanRequest,
        timeout: Option<Duration>,
    ) -> Result<Output> {
        let ssh_bin_path = ensure_ssh_binary(request.ssh_bin_path)?;
        let remote_command = build_remote_exec_command(
            &request.script,
            request.cwd.as_deref(),
            &request.env,
            request.shell.as_deref(),
            request.login,
        )?;
        let plan = build_ssh_session_plan(
            ssh_bin_path.clone(),
            request.target.clone(),
            request.auth_kind.clone(),
            request.identity_path.clone(),
            request.verify_host_key,
            false,
            Some(remote_command),
        );

        run_command(
            ssh_bin_path,
            plan.args,
            timeout.unwrap_or(DEFAULT_CAPTURE_TIMEOUT),
            "ssh command timed out",
            "ssh command task failed",
            "failed to execute ssh command",
        )
        .await
    }

    pub async fn unmount(&self, request: SshUnmountRequest) -> Result<()> {
        let mountpoint = PathBuf::from(&request.mount.local_path);

        if let Some(umount_bin_path) = request.umount_bin_path.as_ref() {
            if !umount_bin_path.is_file() {
                return Err(capability_unavailable(format!(
                    "umount binary does not exist at {}",
                    umount_bin_path.display()
                )));
            }

            let mut args = Vec::new();
            if request.force {
                args.push("-f".to_string());
            }
            args.push(mountpoint.display().to_string());

            let output = run_command(
                umount_bin_path.clone(),
                args,
                DEFAULT_UNMOUNT_TIMEOUT,
                "ssh unmount command timed out",
                "ssh unmount task failed",
                "failed to execute ssh unmount command",
            )
            .await?;

            if output.status.success() {
                return Ok(());
            }

            if should_try_diskutil_fallback(&request, &output) {
                return self.run_diskutil_unmount(&request).await;
            }

            return Err(map_unmount_failure(&request.mount, output));
        }

        if request.force && cfg!(target_os = "macos") && request.diskutil_bin_path.is_some() {
            return self.run_diskutil_unmount(&request).await;
        }

        Err(capability_unavailable(
            "no unmount binary is available for ssh_unmount",
        ))
    }

    pub async fn disconnect(&self, _connection: &SshConnectionSummary, _force: bool) -> Result<()> {
        Ok(())
    }

    pub async fn cleanup_on_shutdown(&self, _mounts: &[SshMountSummary]) -> Result<()> {
        Ok(())
    }

    async fn run_diskutil_unmount(&self, request: &SshUnmountRequest) -> Result<()> {
        let diskutil_bin_path = request
            .diskutil_bin_path
            .as_ref()
            .ok_or_else(|| capability_unavailable("diskutil binary path is not configured"))?;
        if !diskutil_bin_path.is_file() {
            return Err(capability_unavailable(format!(
                "diskutil binary does not exist at {}",
                diskutil_bin_path.display()
            )));
        }

        let mut args = vec!["unmount".to_string()];
        if request.force {
            args.push("force".to_string());
        }
        args.push(request.mount.local_path.clone());

        let output = run_command(
            diskutil_bin_path.clone(),
            args,
            DEFAULT_UNMOUNT_TIMEOUT,
            "diskutil unmount command timed out",
            "diskutil unmount task failed",
            "failed to execute diskutil unmount command",
        )
        .await?;

        if output.status.success() {
            return Ok(());
        }

        Err(map_unmount_failure(&request.mount, output))
    }
}

fn build_remote_command(
    command: Option<&str>,
    args: &[String],
    cwd: Option<&str>,
    env: &BTreeMap<String, String>,
    shell: Option<&str>,
    login: bool,
) -> Result<Option<String>> {
    let command = command.map(str::trim).filter(|value| !value.is_empty());
    let cwd = cwd.map(str::trim).filter(|value| !value.is_empty());
    let shell = shell.map(str::trim).filter(|value| !value.is_empty());
    let has_remote_setup = cwd.is_some() || !env.is_empty() || shell.is_some() || login;

    if command.is_none() && !has_remote_setup {
        return Ok(None);
    }

    let mut script_parts = Vec::new();
    for (key, value) in env {
        let key = key.trim();
        if key.is_empty() {
            bail!("remote env key cannot be empty");
        }
        if !is_valid_env_key(key) {
            bail!("remote env key must be a valid shell identifier: env_key={key}");
        }
        script_parts.push(format!("export {key}={}", shell_escape(value)));
    }

    if let Some(cwd) = cwd {
        script_parts.push(build_remote_cwd_command(cwd));
    }

    if let Some(command) = command {
        let mut command_line = vec![shell_escape(command)];
        for arg in args {
            command_line.push(shell_escape(arg));
        }
        script_parts.push(command_line.join(" "));
    } else if let Some(shell) = shell {
        let suffix = if login { " -l" } else { "" };
        script_parts.push(format!("exec {}{}", shell_escape(shell), suffix));
    } else if login {
        script_parts.push("exec ${SHELL:-/bin/sh} -l".to_string());
    } else {
        script_parts.push("exec ${SHELL:-/bin/sh}".to_string());
    }

    if script_parts.is_empty() {
        return Ok(None);
    }

    let script = script_parts.join(" && ");
    Ok(Some(format!("sh -lc {}", shell_escape(&script))))
}

fn build_remote_exec_command(
    script: &str,
    cwd: Option<&str>,
    env: &BTreeMap<String, String>,
    shell: Option<&str>,
    login: bool,
) -> Result<String> {
    let cwd = cwd.map(str::trim).filter(|value| !value.is_empty());
    let shell = shell.map(str::trim).filter(|value| !value.is_empty());
    let script = script.trim();
    if script.is_empty() {
        bail!("remote script cannot be empty");
    }

    let mut script_parts = Vec::new();
    for (key, value) in env {
        let key = key.trim();
        if key.is_empty() {
            bail!("remote env key cannot be empty");
        }
        if !is_valid_env_key(key) {
            bail!("remote env key must be a valid shell identifier: env_key={key}");
        }
        script_parts.push(format!("export {key}={}", shell_escape(value)));
    }

    if let Some(cwd) = cwd {
        script_parts.push(build_remote_cwd_command(cwd));
    }

    let shell_program = shell
        .map(shell_escape)
        .unwrap_or_else(|| "${SHELL:-/bin/sh}".to_string());
    let login_flag = if login { " -l" } else { "" };
    script_parts.push(format!(
        "exec {}{} -c {}",
        shell_program,
        login_flag,
        shell_escape(script),
    ));

    Ok(format!(
        "sh -lc {}",
        shell_escape(&script_parts.join(" && "))
    ))
}

fn ensure_ssh_binary(ssh_bin_path: Option<PathBuf>) -> Result<PathBuf> {
    let ssh_bin_path =
        ssh_bin_path.ok_or_else(|| capability_unavailable("ssh binary path is not configured"))?;
    if !ssh_bin_path.is_file() {
        return Err(capability_unavailable(format!(
            "ssh binary does not exist at {}",
            ssh_bin_path.display()
        )));
    }
    Ok(ssh_bin_path)
}

fn build_ssh_session_plan(
    ssh_bin_path: PathBuf,
    target: SshTarget,
    auth_kind: SshAuthKind,
    identity_path: Option<PathBuf>,
    verify_host_key: bool,
    interactive: bool,
    remote_command: Option<String>,
) -> SshSessionSpawnPlan {
    let mut args = Vec::new();
    let mut public_args = Vec::new();

    if interactive {
        push_arg(&mut args, &mut public_args, "-tt", false);
    } else {
        push_arg(&mut args, &mut public_args, "-T", false);
    }

    push_arg_pair(&mut args, &mut public_args, "-o", "BatchMode=yes", false);
    push_arg_pair(
        &mut args,
        &mut public_args,
        "-o",
        "NumberOfPasswordPrompts=0",
        false,
    );
    push_arg_pair(
        &mut args,
        &mut public_args,
        "-o",
        if verify_host_key {
            "StrictHostKeyChecking=yes"
        } else {
            "StrictHostKeyChecking=no"
        },
        false,
    );
    if !verify_host_key {
        push_arg_pair(
            &mut args,
            &mut public_args,
            "-o",
            "UserKnownHostsFile=/dev/null",
            false,
        );
    }

    if let Some(port) = target.port {
        push_arg_pair(&mut args, &mut public_args, "-p", &port.to_string(), false);
    }
    if let Some(identity_path) = identity_path {
        push_arg_pair(
            &mut args,
            &mut public_args,
            "-i",
            &identity_path.display().to_string(),
            true,
        );
    }

    push_arg_pair(
        &mut args,
        &mut public_args,
        "-o",
        if matches!(auth_kind, SshAuthKind::SshAgent) {
            "IdentitiesOnly=no"
        } else {
            "IdentitiesOnly=yes"
        },
        false,
    );

    let destination = destination(&target);
    push_arg(&mut args, &mut public_args, &destination, false);
    if let Some(remote_command) = &remote_command {
        push_arg(&mut args, &mut public_args, remote_command, false);
    }

    SshSessionSpawnPlan {
        command: ssh_bin_path.display().to_string(),
        args,
        public_args,
        remote_command,
    }
}

pub(crate) fn shell_escape(value: &str) -> String {
    if value.is_empty() {
        return "''".to_string();
    }
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

fn build_remote_cwd_command(cwd: &str) -> String {
    if cwd == "~" {
        return "cd -- \"${HOME:-~}\" || exit 1".to_string();
    }

    if let Some(rest) = cwd.strip_prefix("~/") {
        if rest.is_empty() {
            return "cd -- \"${HOME:-~}\" || exit 1".to_string();
        }
        return format!("cd -- \"${{HOME:-~}}\"/{} || exit 1", shell_escape(rest));
    }

    format!("cd -- {} || exit 1", shell_escape(cwd))
}

fn push_arg(args: &mut Vec<String>, public_args: &mut Vec<String>, value: &str, sensitive: bool) {
    args.push(value.to_string());
    public_args.push(if sensitive {
        "<redacted>".to_string()
    } else {
        value.to_string()
    });
}

fn push_arg_pair(
    args: &mut Vec<String>,
    public_args: &mut Vec<String>,
    key: &str,
    value: &str,
    sensitive: bool,
) {
    push_arg(args, public_args, key, false);
    push_arg(args, public_args, value, sensitive);
}

fn is_valid_env_key(key: &str) -> bool {
    let mut chars = key.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first == '_' || first.is_ascii_alphabetic()) {
        return false;
    }

    chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
}

fn build_verify_args(
    target: &SshTarget,
    auth_kind: &SshAuthKind,
    identity_path: Option<&PathBuf>,
    verify_host_key: bool,
    connect_timeout: Duration,
) -> Vec<String> {
    let mut args = vec![
        "-T".to_string(),
        "-o".to_string(),
        "BatchMode=yes".to_string(),
        "-o".to_string(),
        "NumberOfPasswordPrompts=0".to_string(),
        "-o".to_string(),
        format!("ConnectTimeout={}", connect_timeout.as_secs().max(1)),
    ];

    if verify_host_key {
        args.push("-o".to_string());
        args.push("StrictHostKeyChecking=yes".to_string());
    } else {
        args.push("-o".to_string());
        args.push("StrictHostKeyChecking=no".to_string());
        args.push("-o".to_string());
        args.push("UserKnownHostsFile=/dev/null".to_string());
    }

    if let Some(port) = target.port {
        args.push("-p".to_string());
        args.push(port.to_string());
    }

    if let Some(identity_path) = identity_path {
        args.push("-i".to_string());
        args.push(identity_path.display().to_string());
    }

    if matches!(auth_kind, SshAuthKind::SshAgent) {
        args.push("-o".to_string());
        args.push("IdentitiesOnly=no".to_string());
    } else {
        args.push("-o".to_string());
        args.push("IdentitiesOnly=yes".to_string());
    }

    args.push(destination(target));
    args.push("exit".to_string());
    args.push("0".to_string());
    args
}

fn build_mount_args(request: &SshMountPlanRequest) -> Vec<String> {
    let mut args = Vec::new();

    if request.mount.read_only {
        args.push("-o".to_string());
        args.push("ro".to_string());
    }

    args.push("-o".to_string());
    args.push(if request.verify_host_key {
        "StrictHostKeyChecking=yes".to_string()
    } else {
        "StrictHostKeyChecking=no".to_string()
    });
    if !request.verify_host_key {
        args.push("-o".to_string());
        args.push("UserKnownHostsFile=/dev/null".to_string());
    }

    if let Some(port) = request.connection.target.port {
        args.push("-p".to_string());
        args.push(port.to_string());
    }

    if let Some(identity_path) = request.identity_path.as_ref() {
        args.push("-o".to_string());
        args.push(format!("IdentityFile={}", identity_path.display()));
    }

    args.push("-o".to_string());
    args.push(if matches!(request.auth_kind, SshAuthKind::SshAgent) {
        "IdentitiesOnly=no".to_string()
    } else {
        "IdentitiesOnly=yes".to_string()
    });

    args.push(format!(
        "{}:{}",
        destination(&request.connection.target),
        request.mount.remote_path
    ));
    args.push(request.mount.local_path.clone());

    args
}

fn destination(target: &SshTarget) -> String {
    let host = target.host_alias.as_deref().unwrap_or(&target.host);
    match target.user.as_deref() {
        Some(user) if !user.trim().is_empty() => format!("{user}@{host}"),
        _ => host.to_string(),
    }
}

async fn run_verify_command(
    ssh_bin_path: PathBuf,
    args: Vec<String>,
    connect_timeout: Duration,
) -> Result<Output> {
    run_command(
        ssh_bin_path,
        args,
        connect_timeout + Duration::from_secs(2),
        "ssh verification timed out",
        "ssh verification task failed",
        "failed to execute ssh verification command",
    )
    .await
}

fn map_ssh_failure(target: &SshTarget, output: Output) -> anyhow::Error {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}\n{stderr}");
    anyhow!(
        "ssh connection verification failed: target={} exit_code={:?} stderr_preview={}",
        target.summary(),
        output.status.code(),
        stderr_preview(&combined)
    )
}

fn map_mount_failure(request: &SshMountPlanRequest, output: Output) -> anyhow::Error {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}\n{stderr}");
    anyhow!(
        "ssh mount failed: mount_id={} target={} remote_path={} local_path={} exit_code={:?} stderr_preview={}",
        request.mount.mount_id.as_str(),
        request.connection.target_summary,
        request.mount.remote_path,
        request.mount.local_path,
        output.status.code(),
        stderr_preview(&combined)
    )
}

fn map_unmount_failure(mount: &SshMountSummary, output: Output) -> anyhow::Error {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}\n{stderr}");

    anyhow!(
        "ssh unmount failed: mount_id={} local_path={} exit_code={:?} stderr_preview={}",
        mount.mount_id.as_str(),
        mount.local_path,
        output.status.code(),
        stderr_preview(&combined)
    )
}

fn should_try_diskutil_fallback(request: &SshUnmountRequest, output: &Output) -> bool {
    cfg!(target_os = "macos")
        && request.force
        && request.diskutil_bin_path.is_some()
        && !output.status.success()
}

async fn run_command(
    program: PathBuf,
    args: Vec<String>,
    timeout: Duration,
    timeout_message: &str,
    join_message: &str,
    execution_message: &str,
) -> Result<Output> {
    let mut child = Command::new(&program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|source| {
            let message = source.to_string();
            if message.contains("No such file or directory") {
                capability_unavailable(message)
            } else {
                anyhow!("{execution_message}: {message}")
            }
        })?;

    let stdout_task = spawn_capture_task(child.stdout.take());
    let stderr_task = spawn_capture_task(child.stderr.take());

    let status = match tokio::time::timeout(timeout, child.wait()).await {
        Ok(result) => result.map_err(|source| anyhow!("{execution_message}: {source}"))?,
        Err(_) => {
            let _ = child.start_kill();
            let status = child
                .wait()
                .await
                .map_err(|source| anyhow!("{join_message}: {source}"))?;
            let output = collect_output(status, stdout_task, stderr_task, join_message).await?;
            return Err(timeout_error(timeout_message, &output));
        }
    };

    collect_output(status, stdout_task, stderr_task, join_message).await
}

fn stderr_preview(output: &str) -> String {
    let trimmed = output.trim();
    if trimmed.is_empty() {
        return String::new();
    }
    trimmed.chars().take(512).collect()
}

fn capability_unavailable(message: impl Into<String>) -> anyhow::Error {
    anyhow!("required ssh capability is unavailable: {}", message.into())
}

fn spawn_capture_task<R>(reader: Option<R>) -> JoinHandle<Result<Vec<u8>, std::io::Error>>
where
    R: AsyncRead + Unpin + Send + 'static,
{
    tokio::spawn(async move {
        let Some(mut reader) = reader else {
            return Ok(Vec::new());
        };

        let mut buffer = Vec::new();
        reader.read_to_end(&mut buffer).await?;
        Ok(buffer)
    })
}

async fn collect_output(
    status: std::process::ExitStatus,
    stdout_task: JoinHandle<Result<Vec<u8>, std::io::Error>>,
    stderr_task: JoinHandle<Result<Vec<u8>, std::io::Error>>,
    join_message: &str,
) -> Result<Output> {
    let stdout = join_capture_task(stdout_task, join_message, "stdout").await?;
    let stderr = join_capture_task(stderr_task, join_message, "stderr").await?;
    Ok(Output {
        status,
        stdout,
        stderr,
    })
}

async fn join_capture_task(
    task: JoinHandle<Result<Vec<u8>, std::io::Error>>,
    join_message: &str,
    stream_name: &str,
) -> Result<Vec<u8>> {
    let captured = task.await.map_err(|join_error| {
        anyhow!("{join_message}: failed to join {stream_name} capture task: {join_error}")
    })?;

    captured.map_err(|source| anyhow!("{join_message}: failed to read {stream_name}: {source}"))
}

fn timeout_error(message: &str, output: &Output) -> anyhow::Error {
    let combined = String::from_utf8_lossy(&output.stdout).to_string()
        + "\n"
        + &String::from_utf8_lossy(&output.stderr);

    anyhow!(
        "{message}: exit_code={:?} stderr_preview={}",
        output.status.code(),
        stderr_preview(&combined)
    )
}