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
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
mod config;
#[cfg(unix)]
mod unix;

use agent_ssh::{
    attachment::CommandSpec,
    resolver::{self, ResolverLimits},
    snapshot::{RecoveryTarget, RemoteCodexReference, SavedState},
};
use anyhow::{Context, Result, bail};
use base64::{Engine, engine::general_purpose::STANDARD};
use clap::Args;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeSet, fs, io::Read, process::Command, time::Duration};

#[derive(Clone, Debug, Args)]
pub struct Scope {
    /// SSH execution host. Defaults to local on Unix or the configured default host.
    #[arg(long, conflicts_with = "local")]
    pub on: Option<String>,
    /// Restrict discovery/execution to this machine.
    #[arg(long)]
    pub local: bool,
    /// Exact tmux socket path on the execution host.
    #[arg(long)]
    pub socket: Option<String>,
    /// Installed agent-ssh executable on the execution host.
    #[arg(long, default_value = "agent-ssh")]
    pub remote_program: String,
}
impl Default for Scope {
    fn default() -> Self {
        Self {
            on: None,
            local: false,
            socket: None,
            remote_program: "agent-ssh".into(),
        }
    }
}

#[derive(Debug, Args)]
pub struct StartCli {
    /// Configured agent preset; see agent-ssh presets.
    pub agent: String,
    /// Friendly session name, unique on the execution host/socket.
    #[arg(long, short)]
    pub name: Option<String>,
    /// Working directory on the execution host; defaults to its current directory.
    #[arg(long)]
    pub cwd: Option<String>,
    #[command(flatten)]
    pub scope: Scope,
    #[arg(long)]
    pub json: bool,
    /// Literal arguments appended to the configured command, following --.
    #[arg(last = true)]
    pub args: Vec<String>,
}

#[derive(Debug, Args)]
pub struct ListCli {
    #[command(flatten)]
    pub scope: Scope,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct ActionCli {
    /// Exact name, runtime ID or unique ID prefix (at least six characters).
    pub session: String,
    #[command(flatten)]
    pub scope: Scope,
}

#[derive(Debug, Args)]
pub struct PresetsCli {
    #[command(flatten)]
    pub scope: Scope,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct RequestCli {
    pub payload: String,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
    version: u32,
    args: Vec<String>,
}

pub fn dispatch(cli: RequestCli) -> Result<()> {
    if cli.payload.len() > 32768 {
        bail!("session request exceeds bound");
    }
    let request: Request = serde_json::from_slice(&STANDARD.decode(cli.payload)?)?;
    if request.version != 1 || request.args.len() > 256 {
        bail!("unsupported session request");
    }
    let mut args = vec!["agent-ssh".to_owned()];
    args.extend(request.args);
    let cli = crate::parse_arguments(args).map_err(|e| anyhow::anyhow!(e.to_string()))?;
    use crate::Operation;
    match cli.operation {
        Some(Operation::Start(cli)) if cli.scope.local => {
            let json = cli.json;
            match start(cli) {
                Err(error) if json => {
                    println!(
                        "{}",
                        serde_json::json!({"version":1,"error":format!("{error:#}")})
                    );
                    Ok(())
                }
                result => result,
            }
        }
        Some(Operation::List(cli)) if cli.scope.local => list(cli),
        Some(Operation::Attach(cli)) if cli.scope.local => action(cli, "attach"),
        Some(Operation::Detach(cli)) if cli.scope.local => action(cli, "detach"),
        Some(Operation::Stop(cli)) if cli.scope.local => action(cli, "stop"),
        Some(Operation::Presets(cli)) if cli.scope.local => presets(cli),
        _ => bail!("session requests must select one local session operation"),
    }
}

#[derive(Serialize, Deserialize)]
pub struct Inventory {
    #[serde(default = "protocol")]
    pub version: u32,
    pub sessions: Vec<Row>,
    pub warnings: Vec<String>,
}
fn protocol() -> u32 {
    1
}
impl Default for Inventory {
    fn default() -> Self {
        Self {
            version: 1,
            sessions: Vec::new(),
            warnings: Vec::new(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
pub struct Row {
    pub id: String,
    pub name: String,
    pub agent: Option<String>,
    pub host: String,
    pub on: Option<String>,
    pub backend: String,
    pub clients: Option<u32>,
    pub state: String,
    pub recovery: String,
    pub capabilities: Vec<String>,
    pub reference: Reference,
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Reference {
    Tmux {
        socket: String,
        session: String,
    },
    RemoteCodex {
        reference: Box<RemoteCodexReference>,
    },
    LocalCodex {
        thread_id: String,
    },
    LocalProcess {
        pid: u32,
        start_ticks: u64,
    },
}

fn quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn command(
    scope: &Scope,
    host: &str,
    verb: &str,
    args: Vec<String>,
    interactive: bool,
) -> Result<CommandSpec> {
    config::host(host)?;
    if scope.remote_program.is_empty()
        || scope.remote_program.starts_with('-')
        || scope.remote_program.chars().any(char::is_control)
    {
        bail!("invalid remote agent-ssh executable");
    }
    agent_ssh::attachment::validate_text(&scope.remote_program)?;
    let mut words = vec![scope.remote_program.clone(), verb.into(), "--local".into()];
    if let Some(socket) = &scope.socket {
        words.extend(["--socket".into(), socket.clone()]);
    }
    words.extend(args);
    let request = STANDARD.encode(serde_json::to_vec(&Request {
        version: 1,
        args: words.iter().skip(1).cloned().collect(),
    })?);
    if request.len() > 24000 {
        bail!("remote session arguments exceed transport bound");
    }
    let words = [
        scope.remote_program.clone(),
        "session-request".into(),
        request,
    ];
    #[cfg(windows)]
    let executable = crate::terminal::SSH_EXE;
    #[cfg(not(windows))]
    let executable = "ssh";
    Ok(CommandSpec {
        program: executable.into(),
        args: vec![
            "-o".into(),
            "BatchMode=yes".into(),
            "-o".into(),
            "ConnectTimeout=8".into(),
            if interactive { "-t" } else { "-T" }.into(),
            "--".into(),
            host.into(),
            words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" "),
        ],
        cwd: None,
    })
}

fn remote_inventory(scope: &Scope, host: &str) -> Result<Inventory> {
    let spec = command(scope, host, "list", vec!["--json".into()], false)?;
    let bytes = resolver::output(
        &spec,
        ResolverLimits {
            timeout: Duration::from_secs(25),
            output_bytes: 4 * 1024 * 1024,
        },
    );
    let mut inventory: Inventory = match bytes
        .and_then(|b| serde_json::from_slice(&b).context("invalid session inventory"))
    {
        Ok(inv) => inv,
        Err(original) => {
            let mut words = vec![scope.remote_program.clone(), "tmux".into()];
            if let Some(socket) = &scope.socket {
                words.extend(["--socket".into(), socket.clone()]);
            }
            words.extend(["list".into(), "--json".into()]);
            let mut legacy = spec.clone();
            *legacy.args.last_mut().context("missing SSH command")? =
                words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" ");
            #[derive(Deserialize)]
            struct Legacy {
                id: String,
                name: String,
                attached_clients: u32,
            }
            let bytes = resolver::output(
                &legacy,
                ResolverLimits {
                    timeout: Duration::from_secs(20),
                    output_bytes: 4 * 1024 * 1024,
                },
            )
            .with_context(|| format!("session discovery failed: {original:#}"))?;
            let rows: Vec<Legacy> = serde_json::from_slice(&bytes)?;
            let socket = if let Some(path) = &scope.socket {
                path.clone()
            } else {
                words.truncate(2);
                words.extend(["clients".into(), "--json".into()]);
                *legacy.args.last_mut().context("missing SSH command")? =
                    words.iter().map(|s| quote(s)).collect::<Vec<_>>().join(" ");
                let bytes = resolver::output(&legacy, ResolverLimits::default())?;
                let clients: crate::observations::ClientSnapshot = serde_json::from_slice(&bytes)?;
                clients.socket
            };
            Inventory{version:1,warnings:vec!["Named-session metadata unavailable; showing tmux inventory. Check the target version/configuration.".into()],sessions:rows.into_iter().map(|r|Row{id:format!("tmux:{}",r.id),name:r.name.clone(),agent:None,host:host.into(),on:Some(host.into()),backend:"tmux".into(),clients:Some(r.attached_clients),state:if r.attached_clients>0{"attached"}else{"detached"}.into(),recovery:"attach".into(),capabilities:vec!["attach".into()],reference:Reference::Tmux{socket:socket.clone(),session:r.name}}).collect()}
        }
    };
    if inventory.version != 1 || inventory.sessions.len() > 4096 {
        bail!("unsupported session inventory");
    }
    for row in &mut inventory.sessions {
        row.host = host.into();
        row.on = Some(host.into());
        if let Reference::Tmux { socket, session } = &row.reference {
            if !socket.starts_with('/')
                || session.is_empty()
                || session.chars().any(char::is_control)
            {
                bail!("invalid remote tmux reference");
            }
        } else if let Reference::RemoteCodex { reference } = &row.reference {
            reference.validate()?;
            if row.capabilities.iter().any(|s| s != "attach") {
                bail!("invalid direct agent capabilities");
            }
        } else if let Reference::LocalCodex { thread_id } = &row.reference {
            uuid::Uuid::parse_str(thread_id).context("invalid remote local conversation ID")?;
            if !row.capabilities.is_empty() {
                bail!("unsupported remote native Codex actions");
            }
        } else {
            bail!("remote local inventory returned an unsupported reference");
        }
    }
    Ok(inventory)
}

fn saved() -> Result<Option<SavedState>> {
    let directory = agent_ssh::snapshot_store::default_directory()?;
    if !directory.exists() {
        return Ok(None);
    }
    let path = match agent_ssh::snapshot_store::latest(&directory) {
        Ok(path) => path,
        Err(error) => {
            if fs::read_dir(&directory)?.next().is_none() {
                return Ok(None);
            }
            return Err(error);
        }
    };
    let mut text = String::new();
    fs::File::open(&path)?
        .take(2 * 1024 * 1024 + 1)
        .read_to_string(&mut text)?;
    SavedState::parse(&text).map(Some).with_context(|| {
        format!(
            "cannot read saved session references from {}",
            path.display()
        )
    })
}

fn host_directory() -> Result<std::path::PathBuf> {
    Ok(agent_ssh::snapshot_store::default_directory()?
        .parent()
        .context("state directory unavailable")?
        .join("hosts"))
}

fn known_hosts() -> Result<BTreeSet<String>> {
    let directory = host_directory()?;
    let mut hosts = BTreeSet::new();
    if !directory.exists() {
        return Ok(hosts);
    }
    for (index, entry) in fs::read_dir(directory)?.enumerate() {
        if index >= 4096 {
            bail!("known host registry exceeds bound");
        }
        let path = entry?.path();
        if path.extension().is_none_or(|e| e != "json") {
            continue;
        }
        let meta = path.symlink_metadata()?;
        if !meta.is_file() || meta.len() > 4096 {
            bail!("invalid known host record");
        }
        let host: String = serde_json::from_slice(&fs::read(path)?)?;
        config::host(&host)?;
        hosts.insert(host);
    }
    Ok(hosts)
}

fn remember_host(host: &str) -> Result<()> {
    use std::{
        hash::{Hash, Hasher},
        io::Write,
    };
    let directory = host_directory()?;
    fs::create_dir_all(&directory)?;
    let mut hash = std::collections::hash_map::DefaultHasher::new();
    host.hash(&mut hash);
    let path = directory.join(format!("{:016x}.json", hash.finish()));
    if path.exists() {
        return Ok(());
    }
    let pending = directory.join(format!("{}.pending", uuid::Uuid::new_v4()));
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&pending)?;
    file.write_all(&serde_json::to_vec(host)?)?;
    file.sync_all()?;
    drop(file);
    let published = fs::hard_link(&pending, &path);
    fs::remove_file(pending)?;
    match published {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
        Err(e) => Err(e.into()),
    }
}

pub(crate) fn sockets_on(host: &str, remote_program: &str) -> Result<Vec<String>> {
    let scope = Scope {
        remote_program: remote_program.into(),
        ..Scope::default()
    };
    let inventory = remote_inventory(&scope, host)?;
    let mut sockets = BTreeSet::new();
    for row in inventory.sessions {
        if let Reference::Tmux { socket, .. } = row.reference {
            sockets.insert(socket);
        }
    }
    Ok(sockets.into_iter().collect())
}

pub fn inventory(scope: &Scope) -> Result<Inventory> {
    let settings = config::load()?;
    let mut output = Inventory {
        version: 1,
        ..Inventory::default()
    };
    let snapshot = match saved() {
        Ok(s) => s,
        Err(e) => {
            output.warnings.push(format!("Saved sessions: {e:#}"));
            None
        }
    };
    let mut hosts = BTreeSet::new();
    if let Some(host) = &scope.on {
        config::host(host)?;
        hosts.insert(host.clone());
    } else if !scope.local {
        match known_hosts() {
            Ok(known) => hosts.extend(known),
            Err(e) => output.warnings.push(format!("Known hosts: {e:#}")),
        }
        hosts.extend(settings.hosts);
        if let Some(host) = settings.default_host {
            hosts.insert(host);
        }
        if let Some(state) = &snapshot {
            for pane in state.panes() {
                match &pane.target {
                    RecoveryTarget::RemoteTmux { host, .. }
                    | RecoveryTarget::RemoteCodex { host, .. } => {
                        hosts.insert(host.clone());
                    }
                    _ => {}
                }
            }
        }
    }
    if scope.on.is_none() {
        #[cfg(unix)]
        match unix::inventory(scope) {
            Ok(inv) => {
                output.sessions.extend(inv.sessions);
                output.warnings.extend(inv.warnings);
            }
            Err(e) => output.warnings.push(format!("Local tmux: {e:#}")),
        }
    }
    #[cfg(windows)]
    let local = if scope.on.is_none() {
        Some(crate::capture::processes())
    } else {
        None
    };
    #[cfg(not(windows))]
    let local: Option<Result<Vec<crate::capture::NativeProcess>>> = None;
    if let Some(Ok(processes)) = &local {
        for process in processes {
            let (id, name, reference) = match crate::save::local_target(process) {
                Ok(RecoveryTarget::LocalCodex { thread_id, .. }) => (
                    thread_id.clone(),
                    format!("codex-{}", &thread_id[..8]),
                    Reference::LocalCodex { thread_id },
                ),
                _ => (
                    format!("process:{}:{}", process.pid, process.start_ticks),
                    format!("codex-{}", process.pid),
                    Reference::LocalProcess {
                        pid: process.pid,
                        start_ticks: process.start_ticks,
                    },
                ),
            };
            output.sessions.push(Row {
                id,
                name,
                agent: Some("codex".into()),
                host: "local".into(),
                on: None,
                backend: "local-codex".into(),
                clients: Some(1),
                state: "running".into(),
                recovery: "in-use".into(),
                capabilities: vec![],
                reference,
            });
        }
    }
    for host in &hosts {
        match remote_inventory(scope, host) {
            Ok(inv) => {
                output.sessions.extend(inv.sessions);
                output
                    .warnings
                    .extend(inv.warnings.into_iter().map(|w| format!("{host}: {w}")));
            }
            Err(e) => output.warnings.push(format!("{host}: {e:#}")),
        }
    }
    if let Some(snapshot) = snapshot {
        for pane in snapshot.panes() {
            match &pane.target {
                RecoveryTarget::LocalCodex { thread_id, .. } if scope.on.is_none() => {
                    let state = match &local {
                        Some(Ok(processes))
                            if processes.iter().any(|p| {
                                p.argv.iter().any(|a| a.eq_ignore_ascii_case(thread_id))
                            }) =>
                        {
                            "running"
                        }
                        Some(Ok(_)) => "resume_available",
                        _ => "unknown",
                    };
                    output.sessions.push(Row {
                        id: thread_id.clone(),
                        name: format!("codex-{}", &thread_id[..8]),
                        agent: Some("codex".into()),
                        host: "local".into(),
                        on: None,
                        backend: "local-codex".into(),
                        clients: if state == "running" { Some(1) } else { None },
                        state: state.into(),
                        recovery: if state == "resume_available" {
                            "resume"
                        } else {
                            "in-use"
                        }
                        .into(),
                        capabilities: vec![],
                        reference: Reference::LocalCodex {
                            thread_id: thread_id.clone(),
                        },
                    });
                }
                RecoveryTarget::RemoteCodex { host, reference } if hosts.contains(host) => {
                    if output
                        .sessions
                        .iter()
                        .any(|row| row.host == *host && row.id == reference.thread_id)
                    {
                        continue;
                    }
                    let check = crate::remote_codex::check(host, reference);
                    if check
                        .as_ref()
                        .is_ok_and(|c| c.mode.as_deref() == Some("managed"))
                    {
                        continue;
                    }
                    let (state, recovery, capabilities) = match check {
                        Ok(c) if c.state == "already_running" => ("running", "in-use", vec![]),
                        Ok(c)
                            if c.state == "attachable" && c.mode.as_deref() == Some("reattach") =>
                        {
                            ("detached", "attach", vec!["attach".into()])
                        }
                        Ok(c) if c.state == "attachable" => ("resume_available", "resume", vec![]),
                        _ => ("unknown", "unavailable", vec![]),
                    };
                    output.sessions.push(Row {
                        id: reference.thread_id.clone(),
                        name: format!("codex-{}", &reference.thread_id[..8]),
                        agent: Some("codex".into()),
                        host: host.clone(),
                        on: Some(host.clone()),
                        backend: "marshal-codex".into(),
                        clients: if state == "running" { Some(1) } else { Some(0) },
                        state: state.into(),
                        recovery: recovery.into(),
                        capabilities,
                        reference: Reference::RemoteCodex {
                            reference: reference.clone(),
                        },
                    });
                }
                _ => {}
            }
        }
    }
    output
        .sessions
        .sort_by(|a, b| (&a.host, &a.name, &a.id).cmp(&(&b.host, &b.name, &b.id)));
    output
        .sessions
        .dedup_by(|a, b| a.host == b.host && a.id == b.id && a.backend == b.backend);
    Ok(output)
}

pub fn list(cli: ListCli) -> Result<()> {
    let progress = crate::progress::Progress::new("Discovering sessions", !cli.json);
    let result = inventory(&cli.scope)?;
    drop(progress);
    if cli.json {
        println!("{}", serde_json::to_string_pretty(&result)?);
        return Ok(());
    }
    for warning in &result.warnings {
        eprintln!("Warning: {warning}");
    }
    if result.sessions.is_empty() {
        if !result.warnings.is_empty() {
            println!("No sessions could be confirmed. Check the warnings above.");
            return Ok(());
        }
        println!("No sessions found. Start one with agent-ssh start codex --on <host>.");
        return Ok(());
    }
    println!(
        "{:<10} {:<22} {:<8} {:<12} {:<7} STATUS",
        "ID", "NAME", "AGENT", "HOST", "CLIENTS"
    );
    for row in result.sessions {
        let id = if uuid::Uuid::parse_str(&row.id).is_ok() {
            &row.id[..8]
        } else {
            &row.id
        };
        println!(
            "{:<10} {:<22} {:<8} {:<12} {:<7} {}",
            cell(id, 10),
            cell(&row.name, 22),
            cell(row.agent.as_deref().unwrap_or("—"), 8),
            cell(&row.host, 12),
            row.clients
                .map(|n| n.to_string())
                .unwrap_or_else(|| "—".into()),
            match row.state.as_str() {
                "resume_available" => "resumable",
                "running" if row.recovery == "in-use" => "in use",
                other => other,
            }
        );
    }
    Ok(())
}

fn cell(value: &str, width: usize) -> String {
    let text = value
        .chars()
        .map(|c| if c.is_control() { '�' } else { c })
        .collect::<String>();
    if text.chars().count() > width {
        format!("{}…", text.chars().take(width - 1).collect::<String>())
    } else {
        text
    }
}

fn execution_host(scope: &Scope) -> Result<Option<String>> {
    if scope.local {
        return Ok(None);
    }
    let host = scope.on.clone().or(config::load()?.default_host);
    if let Some(h) = &host {
        config::host(h)?;
    }
    Ok(host)
}

fn handoff(spec: CommandSpec, interactive: bool) -> Result<()> {
    let mut command = Command::new(spec.program);
    command.args(spec.args);
    if interactive {
        command.env(
            "TERM",
            std::env::var("TERM")
                .ok()
                .filter(|s| !s.is_empty() && s != "dumb")
                .unwrap_or_else(|| "xterm-256color".into()),
        );
    }
    let status = command.status().context("cannot execute session command")?;
    if !status.success() {
        bail!("session command exited with {status}");
    }
    Ok(())
}

pub fn start(cli: StartCli) -> Result<()> {
    config::name(&cli.agent)?;
    if let Some(name) = &cli.name {
        config::name(name)?;
    }
    if let Some(host) = execution_host(&cli.scope)? {
        let mut args = vec![cli.agent.clone()];
        if let Some(name) = &cli.name {
            args.extend(["--name".into(), name.clone()]);
        }
        if let Some(cwd) = &cli.cwd {
            args.extend(["--cwd".into(), cwd.clone()]);
        }
        args.push("--json".into());
        if !cli.args.is_empty() {
            args.push("--".into());
            args.extend(cli.args.clone());
        }
        let progress = crate::progress::Progress::new("Starting session", !cli.json);
        let bytes=resolver::output(&command(&cli.scope,&host,"start",args,false)?,ResolverLimits{timeout:Duration::from_secs(35),output_bytes:1024*1024}).with_context(||format!("launch on {host} was not confirmed; inspect agent-ssh list --on {host} before retrying"))?;
        let response: serde_json::Value = serde_json::from_slice(&bytes).with_context(|| {
            format!(
                "launch response on {host} was invalid; inspect existing sessions before retrying"
            )
        })?;
        if let Some(error) = response.get("error").and_then(serde_json::Value::as_str) {
            bail!("{host}: {error}");
        }
        let mut result: Inventory = serde_json::from_value(response).with_context(|| {
            format!(
                "launch response on {host} was invalid; inspect existing sessions before retrying"
            )
        })?;
        if result.version != 1 || result.sessions.len() != 1 {
            bail!(
                "launch response did not identify exactly one runtime; inspect existing sessions before retrying"
            );
        }
        uuid::Uuid::parse_str(&result.sessions[0].id).context(
            "launch returned an invalid runtime ID; inspect existing sessions before retrying",
        )?;
        config::name(&result.sessions[0].name)?;
        if cli
            .name
            .as_ref()
            .is_some_and(|name| name != &result.sessions[0].name)
        {
            bail!(
                "launch returned an unexpected session name; inspect existing sessions before retrying"
            );
        }
        let row = &mut result.sessions[0];
        row.on = Some(host.clone());
        row.host = host.clone();
        drop(progress);
        if let Err(e) = remember_host(&host) {
            eprintln!("Warning: session started, but the host could not be remembered: {e:#}");
        }
        if cli.json {
            println!("{}", serde_json::to_string_pretty(&result)?);
        } else {
            println!(
                "Started {} on {} ({})\n  Attach: agent-ssh attach {} --on {}",
                row.name,
                host,
                &row.id[..8],
                row.name,
                host
            );
        }
        return Ok(());
    }
    #[cfg(unix)]
    {
        unix::start(cli)
    }
    #[cfg(not(unix))]
    {
        let _ = cli;
        bail!(
            "local persistent launches require Unix; specify --on HOST or configure default_host"
        );
    }
}

pub fn select<'a>(rows: &'a [Row], selector: &str) -> Result<&'a Row> {
    let exact = rows
        .iter()
        .filter(|r| r.id == selector || r.name == selector)
        .collect::<Vec<_>>();
    let found = if exact.is_empty() && selector.len() >= 6 {
        rows.iter()
            .filter(|r| r.id.starts_with(selector))
            .collect::<Vec<_>>()
    } else {
        exact
    };
    match found.as_slice() {
        [row] => Ok(row),
        [] => bail!("session {selector:?} not found; run agent-ssh list"),
        _ => bail!(
            "session {selector:?} is ambiguous; specify --on HOST and an exact name or longer runtime ID"
        ),
    }
}

pub fn action(cli: ActionCli, verb: &str) -> Result<()> {
    let mut scope = cli.scope;
    if scope.on.is_none() && !scope.local {
        scope.on = config::load()?.default_host;
    }
    let inventory = inventory(&scope)?;
    let row = select(&inventory.sessions, &cli.session)?;
    if !row.capabilities.iter().any(|c| c == verb) {
        bail!(
            "{} supports [{}] through agent-ssh; state: {}. Use the owning backend for other operations.",
            row.name,
            row.capabilities.join(", "),
            row.state
        );
    }
    if let Reference::RemoteCodex { reference } = &row.reference {
        #[cfg(unix)]
        if row.on.is_none() {
            return crate::remote_codex::attach_local(reference);
        }
        let mut args = vec![
            "codex-recover".into(),
            "--on".into(),
            row.on.clone().context("remote host unavailable")?,
            "--existing-only".into(),
            "--reference".into(),
            serde_json::to_string(reference)?,
        ];
        let status = Command::new(std::env::current_exe()?)
            .args(std::mem::take(&mut args))
            .status()?;
        if !status.success() {
            bail!("reattachment failed");
        }
        return Ok(());
    }
    if let Some(host) = &row.on {
        let Reference::Tmux { socket, session } = &row.reference else {
            bail!("unsupported remote session backend");
        };
        if verb == "attach" && !row.capabilities.iter().any(|c| c == "stop") {
            return crate::tmux::attach_known(
                Some(host.clone()),
                socket.clone(),
                session.clone(),
                scope.remote_program.clone(),
            );
        }
        let mut scoped = scope.clone();
        scoped.socket = Some(socket.clone());
        return handoff(
            command(
                &scoped,
                host,
                verb,
                vec!["--".into(), row.id.clone()],
                verb == "attach",
            )?,
            verb == "attach",
        );
    }
    #[cfg(unix)]
    {
        unix::action(&scope, row, verb)
    }
    #[cfg(not(unix))]
    {
        bail!("this local session cannot be attached through agent-ssh");
    }
}

pub fn presets(cli: PresetsCli) -> Result<()> {
    if let Some(host) = execution_host(&cli.scope)? {
        return handoff(
            command(
                &cli.scope,
                &host,
                "presets",
                if cli.json {
                    vec!["--json".into()]
                } else {
                    vec![]
                },
                false,
            )?,
            false,
        );
    }
    let settings = config::load()?;
    if cli.json {
        println!("{}", serde_json::to_string_pretty(&settings.presets)?);
    } else {
        println!("{:<18} {:<14} DESCRIPTION", "PRESET", "AGENT");
        for (name, preset) in settings.presets {
            println!(
                "{:<18} {:<14} {}",
                name,
                preset.agent.as_deref().unwrap_or("—"),
                preset.description
            );
        }
        println!(
            "\nConfiguration: {}",
            config::directory()?.join("config.json").display()
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    fn row(id: &str, name: &str, host: &str) -> Row {
        Row {
            id: id.into(),
            name: name.into(),
            agent: Some("codex".into()),
            host: host.into(),
            on: Some(host.into()),
            backend: "tmux".into(),
            clients: Some(0),
            state: "detached".into(),
            recovery: "attach".into(),
            capabilities: vec!["attach".into()],
            reference: Reference::Tmux {
                socket: "/tmp/example.sock".into(),
                session: name.into(),
            },
        }
    }
    #[test]
    fn selection_is_exact_or_uniquely_identified_across_hosts() {
        let rows = vec![
            row("12345678-aaaa", "review", "a"),
            row("87654321-bbbb", "review-long", "b"),
        ];
        assert_eq!(select(&rows, "review").unwrap().host, "a");
        assert_eq!(select(&rows, "876543").unwrap().host, "b");
        assert!(select(&rows, "review-l").is_err());
        let duplicate = vec![
            row("12345678-aaaa", "review", "a"),
            row("12345679-bbbb", "review", "b"),
        ];
        assert!(select(&duplicate, "review").is_err());
        assert!(select(&duplicate, "123456").is_err());
    }
    #[test]
    fn remote_commands_quote_arguments_and_attach_is_the_only_pty_operation() {
        let scope = Scope::default();
        let spec = command(
            &scope,
            "host",
            "start",
            vec!["codex".into(), "--".into(), "a'$(touch bad);value".into()],
            false,
        )
        .unwrap();
        assert!(spec.args.contains(&"-T".into()));
        let encoded = spec.args.last().unwrap().split('\'').nth(5).unwrap();
        let request: Request = serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap();
        assert_eq!(request.args.last().unwrap(), "a'$(touch bad);value");
        assert!(command(&scope, "-oProxyCommand=bad", "list", vec![], false).is_err());
        assert!(
            command(&scope, "host", "attach", vec!["review".into()], true)
                .unwrap()
                .args
                .contains(&"-t".into())
        );
    }
}