agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
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
mod capture;
mod observations;
mod passive;
mod progress;
mod remote_codex;
mod save;
mod sessions;
mod terminal;
mod tmux;

use agent_ssh::{config, grid, layout, resolver, workspace};

use std::{env, path::PathBuf, process::Command};

use anyhow::{Context, Result, bail};
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, parser::ValueSource};

use config::{Host, parse_ssh_config};
use grid::{Step, grid_steps};
use terminal::{SSH_EXE, fragment_path, generate_fragment, pane_args};

#[derive(Debug, Parser)]
#[command(version, about, subcommand_precedence_over_arg = true)]
struct Cli {
    #[command(subcommand)]
    operation: Option<Operation>,

    /// Save selected SSH hosts as a workspace without opening terminals.
    #[arg(long, conflicts_with_all = ["save_layout", "regroup", "command", "list", "sync", "tabs"])]
    save_workspace: Option<PathBuf>,

    /// Save selected SSH destinations as a version 2 terminal layout.
    #[arg(long, conflicts_with_all = ["save_workspace", "regroup", "command", "list", "sync", "tabs"])]
    save_layout: Option<PathBuf>,

    /// Regroup this many existing single-pane tabs into groups of four.
    #[arg(long, requires = "window", conflicts_with_all = ["group", "hosts", "command", "list", "sync", "tabs", "new_window", "panes_per_tab"])]
    regroup: Option<usize>,

    /// First existing tab to regroup (zero-based).
    #[arg(long, default_value_t = 0, requires = "regroup")]
    first_tab: usize,

    /// Maximum panes in each tab (workspace default: 4).
    #[arg(long, conflicts_with = "tabs")]
    panes_per_tab: Option<usize>,

    /// Target Windows Terminal window name or ID.
    #[arg(long, conflicts_with = "new_window")]
    window: Option<String>,

    /// SSH host aliases to open.
    hosts: Vec<String>,

    /// Open all hosts in a named @group (repeatable).
    #[arg(short, long)]
    group: Vec<String>,

    /// Open each host as a separate tab instead of a pane grid.
    #[arg(long)]
    tabs: bool,

    /// Open in a new Windows Terminal window.
    #[arg(long)]
    new_window: bool,

    /// Run a command on all selected hosts instead of opening Terminal.
    #[arg(short, long)]
    command: Option<String>,

    /// List configured groups and hosts.
    #[arg(short, long)]
    list: bool,

    /// Regenerate the Windows Terminal fragment.
    #[arg(short, long)]
    sync: bool,

    /// Print the Windows Terminal invocation without running it.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Subcommand)]
enum Operation {
    #[command(hide = true)]
    SessionRequest(sessions::RequestCli),
    /// Start a named persistent session from an agent preset.
    Start(sessions::StartCli),
    /// List local and known remote sessions across backends.
    List(sessions::ListCli),
    /// Attach to an existing session; never launch a replacement.
    Attach(sessions::ActionCli),
    /// Detach clients from an agent-ssh-owned session without stopping it.
    Detach(sessions::ActionCli),
    /// Stop an agent-ssh-owned session after checking its runtime identity.
    Stop(sessions::ActionCli),
    /// List built-in and configured agent presets.
    Presets(sessions::PresetsCli),
    /// Save live agent identities and their current Terminal tab and pane geometry.
    Save(save::SaveCli),
    /// Load a saved layout. Without PATH, use the newest managed snapshot.
    Load(LoadCli),
    /// Inspect or attach to existing tmux sessions, locally or over SSH.
    Tmux(tmux::TmuxCli),
    /// Reattach or resume an exact saved remote Codex conversation.
    CodexRecover(remote_codex::RecoverCli),
}

#[derive(Debug, clap::Args)]
struct LoadCli {
    /// Snapshot file. Defaults to the newest managed snapshot.
    path: Option<PathBuf>,
    /// Print the recovery plan without opening terminals.
    #[arg(long, conflicts_with = "dry_run")]
    plan: bool,
    /// Print the Windows Terminal invocation without running it.
    #[arg(long)]
    dry_run: bool,
    /// Target Windows Terminal window. Defaults to a new window.
    #[arg(long)]
    window: Option<String>,
    /// Open only attachable panes in legacy layouts; version 3 preserves gaps as labelled shells.
    #[arg(long)]
    allow_partial: bool,
    /// Override the pane count for legacy version 1 or 2 layouts.
    #[arg(long, value_parser = clap::value_parser!(u8).range(1..=16))]
    panes_per_tab: Option<u8>,
}

fn load(cli: LoadCli) -> Result<()> {
    let progress = progress::Progress::new("Loading snapshot", !cli.plan && !cli.dry_run);
    let path = match &cli.path {
        Some(path) => path.clone(),
        None => {
            agent_ssh::snapshot_store::latest(&agent_ssh::snapshot_store::default_directory()?)?
        }
    };
    let target = cli.window.as_deref().unwrap_or("new");
    use std::io::Read;
    let mut text = String::new();
    let before = if cli.path.is_none() {
        Some(path.symlink_metadata()?)
    } else {
        None
    };
    if before
        .as_ref()
        .is_some_and(|metadata| !metadata.file_type().is_file())
    {
        bail!("selected managed snapshot is no longer a regular file; retry load");
    }
    let file = std::fs::File::open(&path)
        .with_context(|| format!("cannot read snapshot {}", path.display()))?;
    if let Some(before) = before {
        let opened = file.metadata()?;
        let after = path.symlink_metadata()?;
        if !opened.is_file()
            || !after.file_type().is_file()
            || before.len() != opened.len()
            || opened.len() != after.len()
            || before.modified()? != opened.modified()?
            || opened.modified()? != after.modified()?
        {
            bail!("selected managed snapshot changed while opening; retry load");
        }
    }
    file.take(2 * 1024 * 1024 + 1).read_to_string(&mut text)?;
    if text.len() > 2 * 1024 * 1024 {
        bail!("snapshot exceeds size limit");
    }
    let version = serde_json::from_str::<serde_json::Value>(text.trim_start_matches('\u{feff}'))
        .with_context(|| format!("invalid snapshot {}", path.display()))?
        .get("version")
        .and_then(serde_json::Value::as_u64);
    if version == Some(3) {
        if cli.panes_per_tab.is_some() {
            bail!("captured layouts preserve their tab boundaries; regrouping is not supported");
        }
        let saved = agent_ssh::snapshot::SavedState::parse(&text)?;
        progress.message("Checking session availability");
        let report = save::plan(&saved, target, target == "new")?;
        drop(progress);
        if cli.plan {
            println!("{}", serde_json::to_string_pretty(&report)?);
            return Ok(());
        }
        if report.partial {
            eprintln!("Warning: some panes will open as placeholders.");
            for pane in &report.panes {
                if let Some(reason) = &pane.reason {
                    eprintln!("{}: {reason}", pane.title);
                }
            }
        }
        if report.blocked {
            for pane in &report.panes {
                if let Some(reason) = &pane.reason {
                    eprintln!("{}: {}", pane.title, reason);
                }
            }
            bail!(
                "load blocked; no terminals opened; rerun this load with --plan to inspect recovery state"
            );
        }
        return open_terminal(&report.terminal_args, cli.dry_run);
    }
    let saved = layout::TerminalLayout::parse(&text)?;
    progress.message("Checking session availability");
    let report = saved.plan(
        target,
        cli.panes_per_tab.map(usize::from),
        cli.allow_partial,
        |command| resolver::resolve(command, resolver::ResolverLimits::default()),
    )?;
    drop(progress);
    if cli.plan {
        println!("{}", serde_json::to_string_pretty(&report)?);
        return Ok(());
    }
    for pane in &report.panes {
        if let Some(reason) = &pane.reason {
            eprintln!("{}: {} ({})", pane.title, pane.state, reason);
        }
    }
    if report.blocked {
        bail!(
            "load blocked; no terminals opened; rerun this load with --plan to inspect observations"
        );
    }
    if report.terminal_args.is_empty() {
        bail!("no attachable panes; no terminals opened");
    }
    open_terminal(&report.terminal_args, cli.dry_run)
}

fn main() -> Result<()> {
    let args = env::args_os().collect::<Vec<_>>();
    if args.len() == 1 {
        println!(
            "agent-ssh {}\nManage agent sessions and terminal layouts.\n",
            env!("CARGO_PKG_VERSION")
        );
        for (command, description) in [
            ("agent-ssh save", "Save sessions and layout"),
            ("agent-ssh load", "Restore the latest saved layout"),
            ("agent-ssh load --plan", "Preview recovery"),
            ("agent-ssh list", "List sessions across hosts"),
            ("agent-ssh start --help", "Start a named agent session"),
            ("agent-ssh attach <name>", "Attach to an existing session"),
            ("agent-ssh presets", "List agent presets"),
            (
                "agent-ssh <host> [host...]",
                "Open SSH hosts in a pane grid",
            ),
            ("agent-ssh --group <name>", "Open a host group"),
            ("agent-ssh --list", "List configured hosts and groups"),
            ("agent-ssh tmux --help", "Inspect or attach tmux sessions"),
        ] {
            println!("  {command:<30} {description}");
        }
        println!("\nRun agent-ssh --help for all commands and options.");
        return Ok(());
    }
    let cli = parse_arguments(args).unwrap_or_else(|error| error.exit());
    if let Some(operation) = cli.operation {
        return match operation {
            Operation::SessionRequest(command) => sessions::dispatch(command),
            Operation::Start(command) => sessions::start(command),
            Operation::List(command) => sessions::list(command),
            Operation::Attach(command) => sessions::action(command, "attach"),
            Operation::Detach(command) => sessions::action(command, "detach"),
            Operation::Stop(command) => sessions::action(command, "stop"),
            Operation::Presets(command) => sessions::presets(command),
            Operation::Tmux(command) => tmux::run(command),
            Operation::CodexRecover(command) => remote_codex::run(command),
            Operation::Save(command) => save::run(command),
            Operation::Load(command) => load(command),
        };
    }
    if let Some(count) = cli.panes_per_tab
        && !(1..=16).contains(&count)
    {
        bail!("panes per tab must be between 1 and 16");
    }
    let window = cli
        .window
        .as_deref()
        .unwrap_or(if cli.new_window { "new" } else { "last" });
    if let Some(count) = cli.regroup {
        return open_terminal(
            &workspace::regroup_args(window, count, cli.first_tab)?,
            cli.dry_run,
        );
    }
    let config_path = ssh_config_path()?;
    let config_text = std::fs::read_to_string(&config_path)
        .with_context(|| format!("no SSH config at {}", config_path.display()))?;
    let all = parse_ssh_config(&config_text);

    if cli.list {
        println!("{:<28} {:<14} COLOR", "HOST", "GROUP");
        for host in &all {
            println!(
                "{:<28} {:<14} {}",
                host.name,
                host.group,
                host.color.as_deref().unwrap_or("")
            );
        }
        return Ok(());
    }

    if cli.sync {
        let path = fragment_path()?;
        let fragment = generate_fragment(&all);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&path, serde_json::to_vec_pretty(&fragment)?)?;
        let groups = all
            .iter()
            .map(|h| &h.group)
            .collect::<std::collections::BTreeSet<_>>()
            .len();
        println!(
            "Wrote {} profiles and {groups} grid actions to {}",
            all.len() + 1,
            path.display()
        );
        println!("Restart Windows Terminal (or save settings) to load them.");
        return Ok(());
    }

    let targets = resolve_targets(&all, &cli.group, &cli.hosts)?;
    if let Some(path) = cli.save_workspace.as_ref().or(cli.save_layout.as_ref()) {
        let saved = workspace::Workspace {
            version: 1,
            panes_per_tab: cli.panes_per_tab.unwrap_or(4),
            panes: targets
                .iter()
                .map(|host| workspace::Pane {
                    title: host.name.clone(),
                    cwd: None,
                    profile: if host.group == "adhoc" {
                        None
                    } else {
                        Some(host.name.clone())
                    },
                    command: vec![SSH_EXE.into(), host.name.clone()],
                })
                .collect(),
        };
        if cli.save_layout.is_some() {
            let layout = layout::TerminalLayout::from_legacy(saved)?;
            if cli.dry_run {
                println!("{}", serde_json::to_string_pretty(&layout)?);
            } else {
                layout.write(path)?;
                println!("Saved terminal layout to {}", path.display());
            }
        } else if cli.dry_run {
            println!("{}", serde_json::to_string_pretty(&saved)?);
        } else {
            saved.write(path)?;
            println!("Saved workspace to {}", path.display());
        }
        return Ok(());
    }
    if let Some(remote_command) = cli.command {
        return run_remote_command(&targets, &remote_command);
    }

    let mut wt_args = if let Some(count) = cli.panes_per_tab {
        let mut args = Vec::new();
        for chunk in targets.chunks(count) {
            let group = build_wt_args(chunk, false, cli.new_window);
            if args.is_empty() {
                args.extend(group);
            } else {
                args.push(";".into());
                args.extend(group.into_iter().skip(2));
            }
        }
        args
    } else {
        build_wt_args(&targets, cli.tabs, cli.new_window)
    };
    if let Some(window) = cli.window {
        wt_args[1] = window;
    }
    open_terminal(&wt_args, cli.dry_run)?;
    if !cli.dry_run && !cli.tabs && targets.len() > 1 {
        println!(
            "Opened {} panes. Alt+Shift+B = broadcast input to all panes.",
            targets.len()
        );
    }
    Ok(())
}

fn parse_arguments(
    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
) -> std::result::Result<Cli, clap::Error> {
    let mut command = Cli::command();
    let matches = command.try_get_matches_from_mut(args)?;
    if matches.subcommand().is_some()
        && command.get_arguments().any(|argument| {
            matches.value_source(argument.get_id().as_str()) == Some(ValueSource::CommandLine)
        })
    {
        return Err(command.error(
            clap::error::ErrorKind::ArgumentConflict,
            "subcommands cannot be combined with SSH layout options or host arguments",
        ));
    }
    Cli::from_arg_matches(&matches)
}

fn open_terminal(wt_args: &[String], dry_run: bool) -> Result<()> {
    if dry_run {
        println!("wt {}", display_args(wt_args));
        return Ok(());
    }
    let status = Command::new("wt.exe")
        .args(wt_args)
        .status()
        .context("failed to start wt.exe")?;
    if !status.success() {
        bail!("wt.exe exited with {status}");
    }
    Ok(())
}

fn ssh_config_path() -> Result<PathBuf> {
    let home = env::var_os("USERPROFILE")
        .or_else(|| env::var_os("HOME"))
        .context("neither USERPROFILE nor HOME is set")?;
    Ok(PathBuf::from(home).join(".ssh").join("config"))
}

fn resolve_targets(all: &[Host], groups: &[String], names: &[String]) -> Result<Vec<Host>> {
    let mut targets = Vec::new();
    for group in groups {
        let members: Vec<_> = all.iter().filter(|h| h.group == *group).cloned().collect();
        if members.is_empty() {
            bail!("no hosts in group '{group}'");
        }
        targets.extend(members);
    }
    for name in names {
        targets.push(
            all.iter()
                .find(|h| h.name == *name)
                .cloned()
                .unwrap_or_else(|| Host {
                    name: name.clone(),
                    group: "adhoc".into(),
                    color: None,
                }),
        );
    }
    if targets.is_empty() {
        bail!("give host names, or --group <name>; see agent-ssh --list");
    }
    Ok(targets)
}

fn build_wt_args(targets: &[Host], tabs: bool, new_window: bool) -> Vec<String> {
    let window = if new_window {
        "new"
    } else if env::var_os("WT_SESSION").is_some() {
        "0"
    } else {
        "last"
    };
    let mut args = vec!["-w".into(), window.into()];
    if tabs {
        for (index, target) in targets.iter().enumerate() {
            if index > 0 {
                args.push(";".into());
            }
            args.push("nt".into());
            args.extend(pane_args(target));
        }
    } else {
        for (index, step) in grid_steps(targets).iter().enumerate() {
            if index > 0 {
                args.push(";".into());
            }
            match step {
                Step::New(target) => {
                    args.push("nt".into());
                    args.extend(pane_args(target));
                }
                Step::Split {
                    direction,
                    size,
                    target,
                } => {
                    args.extend([
                        "sp".into(),
                        direction.wt_flag().into(),
                        "--size".into(),
                        format!("{size:.4}")
                            .trim_end_matches('0')
                            .trim_end_matches('.')
                            .into(),
                    ]);
                    args.extend(pane_args(target));
                }
                Step::FocusLeft => args.extend(["mf".into(), "left".into()]),
            }
        }
    }
    args
}

fn run_remote_command(targets: &[Host], remote_command: &str) -> Result<()> {
    let mut children = Vec::new();
    for target in targets {
        let child = Command::new(SSH_EXE)
            .args([
                "-o",
                "BatchMode=yes",
                "-o",
                "ConnectTimeout=8",
                &target.name,
                "--",
                remote_command,
            ])
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .with_context(|| format!("failed to run ssh for {}", target.name))?;
        children.push((target.name.clone(), child));
    }
    for (name, child) in children {
        let output = child
            .wait_with_output()
            .with_context(|| format!("failed waiting for ssh to {name}"))?;
        println!("==> {name}");
        print!("{}", String::from_utf8_lossy(&output.stdout));
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }
    Ok(())
}

fn display_args(args: &[String]) -> String {
    args.iter()
        .map(|arg| {
            if arg.contains(' ') {
                format!("\"{arg}\"")
            } else {
                arg.clone()
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

#[cfg(test)]
mod tests {
    use super::{Cli, parse_arguments};
    use clap::Parser;

    #[test]
    fn save_and_load_accept_optional_paths_and_keep_layout_options_scoped() {
        assert!(parse_arguments(["agent-ssh", "save"]).is_ok());
        assert!(parse_arguments(["agent-ssh", "save", "snapshot.json"]).is_ok());
        assert!(parse_arguments(["agent-ssh", "load"]).is_ok());
        assert!(
            parse_arguments([
                "agent-ssh",
                "load",
                "snapshot.json",
                "--dry-run",
                "--window",
                "new"
            ])
            .is_ok()
        );
        assert!(parse_arguments(["agent-ssh", "load", "--plan"]).is_ok());
        for alias in ["load", "save"] {
            assert_eq!(
                parse_arguments(["agent-ssh", "--", alias]).unwrap().hosts,
                [alias]
            );
        }
        for count in ["0", "17"] {
            assert!(
                parse_arguments([
                    "agent-ssh",
                    "load",
                    "snapshot.json",
                    "--panes-per-tab",
                    count
                ])
                .is_err()
            );
        }
        for args in [
            vec!["agent-ssh", "load", "--plan", "--dry-run"],
            vec!["agent-ssh", "--plan"],
            vec!["agent-ssh", "--restore", "snapshot.json"],
            vec!["agent-ssh", "load", "snapshot.json", "--command", "uptime"],
            vec!["agent-ssh", "--regroup", "16"],
            vec!["agent-ssh", "--window", "old", "load"],
            vec![
                "agent-ssh",
                "--regroup",
                "16",
                "--window",
                "agents",
                "load",
                "snapshot.json",
            ],
        ] {
            assert!(parse_arguments(&args).is_err(), "{args:?}");
        }
    }

    #[test]
    fn tmux_modes_do_not_accept_windows_layout_flags() {
        for args in [
            vec!["agent-ssh", "--dry-run", "tmux", "list"],
            vec!["agent-ssh", "load", "saved.json", "tmux", "list"],
            vec!["agent-ssh", "example-host", "tmux", "list"],
        ] {
            assert!(parse_arguments(&args).is_err(), "{args:?}");
        }
        assert!(parse_arguments(["agent-ssh", "tmux", "list", "--on", "host"]).is_ok());
        assert!(
            parse_arguments([
                "agent-ssh",
                "tmux",
                "--socket",
                "/tmp/example",
                "list",
                "--json"
            ])
            .is_ok()
        );
        assert!(Cli::try_parse_from(["agent-ssh", "tmux", "attach", "--", "-literal"]).is_ok());
        assert!(
            Cli::try_parse_from(["agent-ssh", "tmux", "list", "--remote-program", "other"])
                .is_err()
        );
    }
}