supercode-cli 0.5.80

Volter Harness — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! `supercode open`: open a session where you are — its pane, or the
//! runtime supercode hosts — and attach this terminal.
//!
//! The session is named the way every other supercode verb names one: its
//! name, its id (or a unique prefix), or its `sc:` address. It opens in a
//! terminal pane of this machine's daemon, running the harness's own TUI, so
//! any authenticated device can attach to it and `supercode teams input`
//! (voice among them) types into it as its user.
//!
//! - Already in a pane: this terminal attaches to that pane (a direct tmux
//!   client: a daemon restart does not end the view; ctrl-] detaches).
//! - Running on another of the team's machines (named by its address or
//!   `name@machine`): this terminal attaches to its pane there through the
//!   machine's Teams server, as `--on` does; outside a pane there, `--move`
//!   runs `open --move` on that machine first.
//! - Running outside supercode: `--move` ends it there and opens it here;
//!   without it nothing happens, because a session has one writer.
//! - Not running: it is resumed in a new pane with the harness's own resume,
//!   in its own directory.
//!
//! Every session supercode starts or resumes runs without approval prompts
//! (Claude Code `--dangerously-skip-permissions`, Codex
//! `--dangerously-bypass-approvals-and-sandbox`), unless the arguments given
//! to the harness choose a permission mode themselves.
//!
//! The pane's launch key is the session (`open:<harness>:<id>`), so opening
//! the same session twice never makes two panes.

use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use anyhow::{anyhow, bail, Context, Result};
use serde_json::Value;
use supercode_harness::mail_route::{Door, LiveSessions};
use supercode_harness::mailbox::MailAddress;
use supercode_harness::{DiscoveryQuery, HarnessHomes, HarnessId, StorageLocator};

#[derive(clap::Args)]
pub(crate) struct OpenArgs {
    /// The session: its name, id (or a unique prefix of it), or address; or
    /// a pane (`p_…`).
    #[arg(required_unless_present = "new")]
    pub(crate) session: Option<String>,
    /// Open a new pane running this program (`claude`, `codex`, any
    /// command) instead of an existing session.
    #[arg(long, value_name = "PROGRAM", conflicts_with_all = ["session", "relocate"])]
    pub(crate) new: Option<String>,
    /// With --new: what the pane runs, for the machine's records (a harness
    /// id). Defaults to the harness the program is.
    #[arg(long, value_name = "KIND", requires = "new")]
    pub(crate) kind: Option<String>,
    /// With --new: a launch key; the same key never opens a second pane.
    #[arg(long, value_name = "KEY", requires = "new")]
    pub(crate) key: Option<String>,
    /// With --new: the first message, typed once the program is ready for it.
    #[arg(long, value_name = "TEXT", requires = "new")]
    pub(crate) input: Option<String>,
    /// With --new: tell this session, by mail, when the pane ends and how
    /// (as `message send --notify-when-idle` tells a sender a turn ended).
    #[arg(long, requires = "new")]
    pub(crate) notify_when_ended: bool,
    /// An enrolled machine of the selected Teams context, instead of this
    /// one. There, a pane is named by its id (`p_…`).
    #[arg(long, value_name = "MACHINE", conflicts_with = "relocate")]
    pub(crate) on: Option<String>,
    /// Watch without taking the keyboard: a pane's, or a runtime's
    /// (observers cannot claim the controller lease or submit).
    #[arg(long, conflicts_with = "take_control")]
    pub(crate) observe: bool,
    /// A runtime supercode hosts: the terminal frontend to show it in.
    #[arg(long, value_enum, default_value_t)]
    pub(crate) ui: crate::frontend_client::FrontendClientId,
    /// A runtime supercode hosts: displace its current controller.
    #[arg(long)]
    pub(crate) take_control: bool,
    /// A runtime supercode hosts: print an operator-made SSH tunnel recipe
    /// instead of attaching. No tunnel is opened and no credential printed.
    #[arg(long)]
    pub(crate) remote_instructions: bool,
    /// A runtime URL (`http://…`, printed by `serve`): its bearer token (or
    /// SUPERCODE_SERVER_TOKEN).
    #[arg(long, value_name = "TOKEN", conflicts_with = "credential_fd")]
    pub(crate) token: Option<String>,
    /// A runtime URL: read its credential from an inherited descriptor,
    /// keeping it out of argv, environment, shell history and stdin.
    #[arg(long, value_name = "FD", conflicts_with = "token")]
    pub(crate) credential_fd: Option<i32>,
    /// A runtime URL: the stable client identity bound into a scoped credential.
    #[arg(long, value_name = "ID")]
    pub(crate) client_id: Option<String>,
    /// A runtime URL: join through the ACP frontend adapter instead of HTTP.
    #[arg(long)]
    pub(crate) acp: bool,
    /// With --acp: the session id to resume; omitted, the single runtime the
    /// endpoint represents.
    #[arg(long, value_name = "ID", requires = "acp")]
    pub(crate) acp_session: Option<String>,
    /// With --acp: resume event delivery after this acknowledged cursor.
    #[arg(long, value_name = "SEQUENCE", requires = "acp")]
    pub(crate) after_sequence: Option<u64>,
    /// A `supercode-live://` receipt: the harness it must be.
    #[arg(long, value_name = "HARNESS", requires = "receipt_session")]
    pub(crate) harness: Option<String>,
    /// A `supercode-live://` receipt: the harness-native session it must be.
    #[arg(long = "session", value_name = "SESSION", requires = "harness")]
    pub(crate) receipt_session: Option<String>,
    /// Continue the session in Volter Harness's own agent (`supercode
    /// resume`), in a pane of its own, instead of in its harness. Arguments
    /// after `--` go to that agent (`-- --model opus`).
    #[arg(long, conflicts_with_all = ["new", "relocate"])]
    pub(crate) native: bool,
    /// End the session where it runs now (outside supercode) and open it here.
    #[arg(long = "move")]
    pub(crate) relocate: bool,
    /// Open the pane without attaching this terminal; print the pane.
    #[arg(long)]
    pub(crate) detach: bool,
    /// Arguments for the harness, after supercode's own (`-- --model opus`).
    #[arg(last = true)]
    pub(crate) args: Vec<String>,
}

/// What a name resolved to.
enum Resolved {
    /// A harness session, to open in a pane.
    Session(Target),
    /// A runtime supercode hosts, by its runtime id.
    Runtime(String),
}

/// A runtime supercode hosts, in a terminal frontend.
async fn open_runtime(cli: &crate::Cli, open: &OpenArgs, runtime: &str) -> Result<()> {
    if open.on.is_some() {
        bail!("a runtime on another machine is opened by its URL there");
    }
    crate::attach_runtime_client_cmd(
        cli,
        runtime,
        open.ui,
        open.observe,
        open.take_control,
        open.remote_instructions,
    )
    .await
}

/// A session to open.
struct Target {
    harness: String,
    id: String,
    name: Option<String>,
    cwd: Option<PathBuf>,
    transcript: Option<PathBuf>,
    /// The process running it now, if one is.
    pid: Option<u32>,
    /// The daemon pane it runs in, if it runs in one.
    pane: Option<String>,
    /// The tmux session it runs in, if that is not a daemon pane.
    tmux: Option<String>,
}

pub(crate) async fn run(cli: &crate::Cli, open: &OpenArgs) -> Result<()> {
    let view = View {
        detach: open.detach,
        observe: open.observe,
        on: open.on.as_deref(),
        context: cli.context.as_deref(),
    };
    if let Some(program) = &open.new {
        return open_new(program, open, cli.cwd.as_deref(), &view);
    }
    let wanted = open.session.as_deref().unwrap_or_default();
    // A runtime by its URL (`serve`), or by a live receipt.
    if wanted.starts_with("http://") || wanted.starts_with("https://") {
        return crate::attach_cmd(
            cli,
            crate::AttachConnectOptions {
                base_url: wanted,
                token: open.token.as_deref(),
                credential_fd: open.credential_fd,
                client_id: open.client_id.as_deref(),
                through_acp: open.acp,
                session_id: open.acp_session.clone(),
                after_sequence: open.after_sequence,
            },
        )
        .await;
    }
    if wanted.starts_with("supercode-live://") {
        let (Some(harness), Some(session)) = (&open.harness, &open.receipt_session) else {
            bail!("a supercode-live:// receipt is opened with --harness and --session, which it is checked against");
        };
        return crate::harness_attach_cmd(cli, wanted, harness, session).await;
    }
    if is_daemon_pane(wanted) {
        return attach(wanted, &view, wanted);
    }
    // A runtime supercode hosts, by its runtime id or its source session's.
    if let Some(record) = supercode_harness::runtime_mail::controlled_runtimes()
        .into_iter()
        .find(|record| record.runtime_session_id == wanted || record.source.session_id == wanted)
    {
        return open_runtime(cli, open, &record.runtime_session_id).await;
    }
    if let Some(machine) = &open.on {
        bail!(
            "on another machine a pane is named by its id (`p_…`, from `supercode teams panes \
             ls --machine {machine}`); `{wanted}` is not one"
        );
    }
    let homes = HarnessHomes::default();
    // A session named on another of the team's machines is looked up there only.
    if let Some(machine) = crate::message::other_machine(wanted) {
        let row = crate::message::team_session(&homes, wanted)
            .ok_or_else(|| anyhow!("no session named `{wanted}` is running on {machine}"))?;
        return open_there(&homes, &row, open, view);
    }
    let target = match resolve(&homes, wanted) {
        Ok(Resolved::Session(target)) => target,
        Ok(Resolved::Runtime(runtime)) => return open_runtime(cli, open, &runtime).await,
        // A bare name only a session on another of the team's machines has.
        Err(error) => match crate::message::team_session(&homes, wanted) {
            Some(row) => return open_there(&homes, &row, open, view),
            None => return Err(error),
        },
    };
    let label = target.name.clone().unwrap_or_else(|| short(&target.id));
    // Everything but a pane attach starts a writer on the session. An
    // observer never does: a hosted session between turns has no live door
    // for a moment, and resuming it then puts a second writer on its
    // transcript.
    if open.observe && target.pane.is_none() {
        bail!(
            "{label} is not in a pane or hosted here right now, so there is nothing to observe. \
             Nothing was opened; without --observe it would be resumed in a new pane."
        );
    }
    if open.native {
        return open_native(&target, open, &view, &label);
    }
    if let Some(pane) = &target.pane {
        return attach(pane, &view, &label);
    }
    if let Some(pid) = target.pid {
        if !open.relocate {
            bail!(
                "{label} is running outside supercode (pid {pid}{}). Nothing was opened: a \
                 session has one writer. End it there (`/exit`), or run `supercode open {} --move` \
                 to end it and open it here.",
                target
                    .tmux
                    .as_ref()
                    .map(|tmux| format!(", tmux session {tmux}"))
                    .unwrap_or_default(),
                wanted
            );
        }
        refuse_foreign_process(pid, &label)?;
        end_process(pid)?;
    }
    if target.harness == HarnessId::CODEX {
        give_codex_its_delivery_door();
    }
    let (program, arguments) = launch_command(&target, &open.args)?;
    let key = format!("open:{}:{}", target.harness, target.id);
    let mut request = vec![
        "launch".to_string(),
        format!("--launch-key={key}"),
        format!("--pane={}", pane_for(&key)),
        format!("--kind={}", target.harness),
    ];
    if attaches_here(&view) {
        request.push("--popup=false".into());
    }
    if let Some(cwd) = &target.cwd {
        request.push(format!("--cwd={}", cwd.display()));
    }
    request.push(program);
    request.push("--".into());
    request.extend(arguments);
    let launched = fleet_json(&request)?;
    let pane = launched["pane"]
        .as_str()
        .ok_or_else(|| anyhow!("the machine daemon opened no pane: {launched}"))?
        .to_string();
    attach(&pane, &view, &label)
}

/// The session continued by Volter Harness's own agent, in a pane of its
/// own: the native harness's `resume`, as `claude --resume` is Claude's.
fn open_native(target: &Target, open: &OpenArgs, view: &View, label: &str) -> Result<()> {
    let transcript = target
        .transcript
        .as_ref()
        .ok_or_else(|| anyhow!("{label} has no transcript file supercode can continue from"))?;
    let program = std::env::current_exe().context("locate this supercode")?;
    let key = format!("open:native:{}:{}", target.harness, target.id);
    let mut request = vec![
        "launch".to_string(),
        format!("--launch-key={key}"),
        format!("--pane={}", pane_for(&key)),
        "--kind=supercode".to_string(),
    ];
    if attaches_here(view) {
        request.push("--popup=false".into());
    }
    if let Some(cwd) = &target.cwd {
        request.push(format!("--cwd={}", cwd.display()));
    }
    request.push(program.display().to_string());
    request.push("--".into());
    request.push("resume".into());
    request.push(transcript.display().to_string());
    request.extend(open.args.iter().cloned());
    let launched = fleet_json(&request)?;
    let pane = launched["pane"]
        .as_str()
        .ok_or_else(|| anyhow!("the machine daemon opened no pane: {launched}"))?
        .to_string();
    attach(&pane, view, label)
}

/// Whether this command will show the pane in its own terminal (a local pane,
/// not `--detach`, run from a terminal): the machine's own window for the pane
/// would be a second view of it, so the launch asks for none.
fn attaches_here(view: &View) -> bool {
    use std::io::IsTerminal;
    view.on.is_none()
        && !view.detach
        && std::io::stdin().is_terminal()
        && std::io::stdout().is_terminal()
}

/// How this terminal shows the pane.
struct View<'a> {
    detach: bool,
    observe: bool,
    on: Option<&'a str>,
    /// The Teams context `on` is a machine of.
    context: Option<&'a str>,
}

/// A new pane running `program`, on this machine or `--on` another.
fn open_new(program: &str, open: &OpenArgs, cwd: Option<&Path>, view: &View) -> Result<()> {
    // A harness named by its id runs its own program; only Claude Code's
    // differ (`claude-code` is `claude`).
    let program = match program {
        "claude-code" => "claude",
        other => other,
    };
    let mut request = vec!["launch".to_string()];
    if attaches_here(view) {
        request.push("--popup=false".into());
    }
    if let Some(machine) = view.on {
        request.extend(["--on".to_string(), machine.to_string()]);
        if let Some(context) = view.context {
            request.push(format!("--context={context}"));
        }
    }
    if let Some(input) = &open.input {
        request.push(format!("--input={input}"));
    }
    if let Some(key) = &open.key {
        request.push(format!("--launch-key={key}"));
    }
    if open.notify_when_ended {
        let caller = supercode_harness::mail_route::resolve_caller(
            &HarnessHomes::default(),
            &supercode_harness::mail_route::process_ancestry(),
        )
        .map_err(|message| anyhow!(message))?;
        request.push(format!("--notify={}", caller.address));
        let machine = match view.on {
            Some(machine) => supercode_harness::mailbox::normal_machine_name(machine),
            None => supercode_harness::mailbox::local_machine_name(),
        };
        request.push(format!("--notify-machine={machine}"));
    }
    let kind = open.kind.clone().unwrap_or_else(|| match program {
        "claude" => HarnessId::CLAUDE_CODE.to_string(),
        other => other.to_string(),
    });
    request.push(format!("--kind={kind}"));
    let cwd = match cwd {
        Some(cwd) => Some(cwd.to_path_buf()),
        // A pane on this machine starts where this command runs; another
        // machine chooses its own directory.
        None if view.on.is_none() => std::env::current_dir().ok(),
        None => None,
    };
    if let Some(cwd) = &cwd {
        request.push(format!("--cwd={}", cwd.display()));
    }
    request.push(program.to_string());
    request.push("--".into());
    if kind == HarnessId::CODEX && view.on.is_none() {
        give_codex_its_delivery_door();
    }
    let no_prompts = no_prompt_arguments(&kind, cwd.as_deref(), &open.args);
    request.extend(no_prompts);
    request.extend(open.args.iter().cloned());
    let launched = fleet_json(&request)?;
    let pane = launched["pane"]
        .as_str()
        .ok_or_else(|| anyhow!("the machine daemon opened no pane: {launched}"))?
        .to_string();
    if launched["status"] == "finished" {
        eprintln!("`{program}` ran and finished (status 0) in pane {pane}, which has closed.");
        println!(
            "{}",
            serde_json::json!({"pane": pane, "session": program, "machine": view.on, "finished": true})
        );
        return Ok(());
    }
    if launched["status"] == "exited" {
        let how = launched["exit"]
            .as_str()
            .unwrap_or("no exit status recorded");
        bail!("`{program}` ended as soon as it started ({how}), so pane {pane} is gone. A command with arguments goes as the program and its arguments (`open --new bash -- script.sh`) or as one quoted command line.");
    }
    attach(&pane, view, program)
}

/// Find the session: running ones first (by name, id or address), then
/// persisted ones (by id, id prefix or title).
fn resolve(homes: &HarnessHomes, wanted: &str) -> Result<Resolved> {
    let live = LiveSessions::read(homes);
    let address = MailAddress::parse(wanted).ok();
    let running = live.all().iter().find(|session| {
        address.as_ref() == Some(&session.address)
            || session.name == wanted
            || session.name.split('@').next() == Some(wanted)
            || session.address.session_id == wanted
    });
    if let Some(session) = running {
        let name = session.name.split('@').next().unwrap_or(&session.name);
        if let Door::Runtime(record) = &session.door {
            return Ok(Resolved::Runtime(record.runtime_session_id.clone()));
        }
        let harness = session.address.harness.clone();
        let id = session.address.session_id.clone();
        let tmux = session
            .tmux
            .as_deref()
            .and_then(|tmux| tmux.split(':').next())
            .map(str::to_string);
        let pane = crate::message::session_pane(session.tmux.as_deref(), session.pid, &mut None);
        let pid = match session.pid {
            Some(pid) => Some(pid),
            None if harness == HarnessId::CODEX => codex_pid(&id),
            None => None,
        };
        let mut target = persisted(homes, &harness, &id).unwrap_or(Target {
            harness,
            id,
            name: None,
            cwd: None,
            transcript: None,
            pid: None,
            pane: None,
            tmux: None,
        });
        target.name = Some(name.to_string());
        if target.cwd.is_none() {
            target.cwd = session.cwd.clone();
        }
        target.pid = pid;
        target.tmux = tmux.filter(|_| pane.is_none());
        target.pane = pane;
        return Ok(Resolved::Session(target));
    }
    let query = DiscoveryQuery {
        harnesses: vec![
            HarnessId::new(HarnessId::CLAUDE_CODE),
            HarnessId::new(HarnessId::CODEX),
        ],
        homes: homes.clone(),
        query: Some(wanted.to_string()),
        ..Default::default()
    };
    let mut found: Vec<_> = supercode_harness::discover_sessions(&query)?
        .into_iter()
        .filter(|descriptor| {
            let id = &descriptor.locator.session_id;
            id == wanted
                || (wanted.len() >= 6 && id.starts_with(wanted))
                || descriptor.title.as_deref() == Some(wanted)
        })
        .collect();
    found.sort_by_key(|descriptor| std::cmp::Reverse(descriptor.updated_at_ms));
    let ids: std::collections::BTreeSet<_> = found
        .iter()
        .map(|descriptor| descriptor.locator.session_id.clone())
        .collect();
    if ids.len() > 1 && !found.iter().any(|d| d.locator.session_id == wanted) {
        let listed: Vec<_> = ids.iter().take(5).map(|id| short(id)).collect();
        bail!(
            "`{wanted}` names {} sessions ({}). Name one by its id.",
            ids.len(),
            listed.join(", ")
        );
    }
    let descriptor = found.into_iter().next().ok_or_else(|| {
        anyhow!("no session is named `{wanted}`: not running, and no saved Claude Code or Codex session has that id or name")
    })?;
    let transcript = match &descriptor.locator.storage {
        StorageLocator::File { path } => Some(path.clone()),
        _ => None,
    };
    Ok(Resolved::Session(Target {
        harness: descriptor.locator.harness.0.clone(),
        id: descriptor.locator.session_id.clone(),
        name: descriptor.title.clone(),
        cwd: descriptor.cwd.clone(),
        transcript,
        pid: None,
        pane: None,
        tmux: None,
    }))
}

/// The saved session `id` of `harness`, for its directory and transcript.
fn persisted(homes: &HarnessHomes, harness: &str, id: &str) -> Option<Target> {
    let query = DiscoveryQuery {
        harnesses: vec![HarnessId::new(harness)],
        homes: homes.clone(),
        ..Default::default()
    };
    let descriptor = supercode_harness::discover_sessions(&query)
        .ok()?
        .into_iter()
        .find(|descriptor| descriptor.locator.session_id == id)?;
    let transcript = match &descriptor.locator.storage {
        StorageLocator::File { path } => Some(path.clone()),
        _ => None,
    };
    Some(Target {
        harness: harness.to_string(),
        id: id.to_string(),
        name: descriptor.title,
        cwd: descriptor.cwd,
        transcript,
        pid: None,
        pane: None,
        tmux: None,
    })
}

/// The harness's own resume, without approval prompts unless the caller's
/// arguments choose otherwise, then the caller's arguments.
fn launch_command(target: &Target, extra: &[String]) -> Result<(String, Vec<String>)> {
    let mut arguments = Vec::new();
    let program = match target.harness.as_str() {
        HarnessId::CLAUDE_CODE => {
            arguments.extend(["--resume".to_string(), target.id.clone()]);
            if let Some(name) = &target.name {
                arguments.extend(["--name".to_string(), name.clone()]);
            }
            "claude"
        }
        HarnessId::CODEX => {
            arguments.extend(["resume".to_string(), target.id.clone()]);
            "codex"
        }
        other => {
            bail!("`supercode open` opens Claude Code and Codex sessions; this one is {other}")
        }
    };
    arguments.extend(no_prompt_arguments(
        &target.harness,
        target.cwd.as_deref(),
        extra,
    ));
    arguments.extend(extra.iter().cloned());
    Ok((program.to_string(), arguments))
}

/// A Codex session is messaged through supercode's hooks in Codex's user
/// hooks file; a session supercode opens gets them without a setup step (it
/// runs with `--dangerously-bypass-hook-trust`, so they need no trusting).
fn give_codex_its_delivery_door() {
    match crate::message::install_codex_hooks() {
        Ok((path, added)) if !added.is_empty() => eprintln!(
            "Added supercode's mail hooks to {}, so sessions can message this Codex.",
            path.display()
        ),
        Ok(_) => {}
        Err(error) => eprintln!("supercode's mail hooks were not added to Codex: {error:#}"),
    }
}

/// The arguments that run `harness` in `cwd` without approval prompts (for
/// Codex, its folder-trust prompt too), or none when the caller's `arguments`
/// already choose a permission mode.
fn no_prompt_arguments(harness: &str, cwd: Option<&Path>, arguments: &[String]) -> Vec<String> {
    // a launched pane runs unattended: past its startup prompts and its approval prompts, unless the caller chose
    supercode_harness::startup_prompts::startup_arguments(harness, cwd, arguments, true)
}

/// The pane a session opens in: named by the session, so reopening it after
/// its pane ended gives the same pane id, and anything that names the pane
/// (a shared Surface, a grant) keeps working.
fn pane_for(launch_key: &str) -> String {
    format!("p_{}", &blake3::hash(launch_key.as_bytes()).to_hex()[..16])
}

/// Whether a tmux session name is a pane this machine's daemon launched.
pub(crate) fn is_daemon_pane(name: &str) -> bool {
    name.strip_prefix("p_").is_some_and(|rest| {
        !rest.is_empty()
            && rest
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    })
}

/// The `codex` process running session `id`. Codex's shared app-server
/// daemon (`codex app-server`) holds the rollouts of every thread it has
/// loaded, with or without a terminal attached, so it is never a session's
/// process: a session it holds opens with `codex resume`, which attaches to
/// the same daemon.
fn codex_pid(id: &str) -> Option<u32> {
    let output = std::process::Command::new("ps")
        .args(["-axo", "pid=,args="])
        .output()
        .ok()?;
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            let pid: u32 = fields.next()?.parse().ok()?;
            let program = fields.next()?;
            let is_codex = Path::new(program)
                .file_name()
                .is_some_and(|name| name == "codex");
            (is_codex && fields.next() != Some("app-server")).then_some(pid)
        })
        .find(|pid| {
            supercode_harness::codex_peer::session_of_process(*pid)
                .is_some_and(|(session, _)| session == id)
        })
}

/// End the process running a session and wait until it is gone.
#[derive(clap::Args)]
pub(crate) struct CloseArgs {
    /// The session: its name, id (or a unique prefix of it), or address; or a
    /// pane (`p_…`). A session on another of the team's machines is named by
    /// its address or `name@machine` (a bare name when no session here has it).
    pub(crate) session: String,
}

/// End a session wherever it runs here: its pane closed through the machine
/// daemon, or, running in a terminal of its own, its process ended.
pub(crate) fn close(args: &CloseArgs) -> Result<()> {
    let wanted = args.session.as_str();
    if is_daemon_pane(wanted) {
        return close_pane(wanted, wanted);
    }
    let homes = HarnessHomes::default();
    // A session named on another of the team's machines is looked up there only.
    if let Some(machine) = crate::message::other_machine(wanted) {
        let row = crate::message::team_session(&homes, wanted)
            .ok_or_else(|| anyhow!("no session named `{wanted}` is running on {machine}"))?;
        return close_there(&homes, &row);
    }
    let target = match resolve(&homes, wanted) {
        Ok(Resolved::Session(target)) => target,
        Ok(Resolved::Runtime(runtime)) => {
            bail!("{wanted} is runtime {runtime}, which supercode hosts; it ends with its host")
        }
        // A bare name only a session on another of the team's machines has.
        Err(error) => match crate::message::team_session(&homes, wanted) {
            Some(row) => return close_there(&homes, &row),
            None => return Err(error),
        },
    };
    let label = target.name.clone().unwrap_or_else(|| short(&target.id));
    if let Some(pane) = &target.pane {
        return close_pane(pane, &label);
    }
    let Some(pid) = target.pid else {
        println!("{label} is not running; there is nothing to close.");
        return Ok(());
    };
    refuse_foreign_process(pid, &label)?;
    end_process(pid)?;
    println!("closed {label} (pid {pid}); its transcript stays, and `supercode open {wanted}` resumes it");
    Ok(())
}

/// Interrupt a session's turn and end the processes that turn started, leaving the session running.
#[derive(clap::Args)]
pub(crate) struct StopArgs {
    /// The session, named as `close` names it.
    pub(crate) session: String,
}

/// Stop what a session is doing without ending it. A message queues behind a running tool and so
/// cannot stop it; this interrupts the turn through the session's own input door (Escape into its
/// pane, as a person at it would press) and then ends the process trees the turn started: the
/// harness process's children created after the turn's last user message. What the session
/// started with (its MCP servers, its helpers) is older than that and is left alone.
pub(crate) fn stop(args: &StopArgs) -> Result<()> {
    let wanted = args.session.as_str();
    let homes = HarnessHomes::default();
    if let Some(machine) = crate::message::other_machine(wanted) {
        let row = crate::message::team_session(&homes, wanted)
            .ok_or_else(|| anyhow!("no session named `{wanted}` is running on {machine}"))?;
        let (machine, address) = row_machine(&row)?;
        run_there(&machine, &address, &["stop", &address])?;
        println!(
            "asked {machine} to stop {} (`supercode stop` runs there)",
            row["name"].as_str().unwrap_or(wanted)
        );
        return Ok(());
    }
    let target = match resolve(&homes, wanted) {
        Ok(Resolved::Session(target)) => target,
        Ok(Resolved::Runtime(runtime)) => {
            bail!("{wanted} is runtime {runtime}, which supercode hosts; interrupt it through `supercode harness drive`")
        }
        Err(error) => return Err(error),
    };
    let label = target.name.clone().unwrap_or_else(|| short(&target.id));
    let Some(pane) = &target.pane else {
        bail!(
            "{label} runs in a terminal of its own, which supercode has no input door to: interrupt it at that terminal (or through its harness's own remote control)"
        )
    };
    let program = std::env::current_exe().context("locate this supercode")?;
    // The turn's start is read before the interrupt: the interrupt writes a user record of its own.
    let since = turn_started_at(target.transcript.as_deref());
    let status = std::process::Command::new(program)
        .args(["teams", "input", pane, "--key", "Escape"])
        .stdout(std::process::Stdio::null())
        .status()
        .context("run supercode teams input")?;
    if !status.success() {
        bail!("the machine daemon did not deliver Escape to pane {pane}");
    }
    // The harness ends a foreground tool on its own interrupt; what outlives it is ended here.
    std::thread::sleep(Duration::from_secs(2));
    let ended = match (target.pid, since) {
        (Some(pid), Some(since)) => end_turn_children(pid, since),
        _ => Vec::new(),
    };
    if ended.is_empty() {
        println!("stopped {label} (pane {pane}): its turn was interrupted; no process its turn started was left running");
    } else {
        let list = ended
            .iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        println!("stopped {label} (pane {pane}): its turn was interrupted, and the processes it started were ended (pids {list})");
    }
    Ok(())
}

/// When a Claude Code session's current turn began: its transcript's last user message that a
/// person or a sender typed (not a tool result, not the harness's own `[Request interrupted …]`
/// or meta record), in seconds since the epoch.
fn turn_started_at(transcript: Option<&Path>) -> Option<i64> {
    let text = std::fs::read_to_string(transcript?).ok()?;
    text.lines().rev().find_map(|line| {
        let record: Value = serde_json::from_str(line).ok()?;
        if record["type"] != "user" || record["isSidechain"] == true || record["isMeta"] == true {
            return None;
        }
        let content = &record["message"]["content"];
        let texts: Vec<&str> = match content {
            Value::String(text) => vec![text.as_str()],
            Value::Array(items) => items
                .iter()
                .filter(|item| item["type"] == "text")
                .filter_map(|item| item["text"].as_str())
                .collect(),
            _ => Vec::new(),
        };
        let typed = !texts.is_empty()
            && !texts
                .iter()
                .all(|text| text.starts_with("[Request interrupted by user"));
        if !typed {
            return None;
        }
        supercode_interchange::sidecar::rfc3339_to_ms(record["timestamp"].as_str()?)
            .map(|ms| ms / 1000)
    })
}

/// End every process tree under `pid` whose root child started at or after `since` (epoch
/// seconds). Returns the pids of the children whose trees were ended.
#[cfg(unix)]
fn end_turn_children(pid: u32, since: i64) -> Vec<u32> {
    let Ok(output) = std::process::Command::new("ps")
        .args(["-axo", "pid=,ppid=,etime="])
        .output()
    else {
        return Vec::new();
    };
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_secs() as i64);
    // `etime` is [[dd-]hh:]mm:ss.
    let seconds = |etime: &str| -> Option<i64> {
        let (days, rest) = match etime.split_once('-') {
            Some((days, rest)) => (days.parse::<i64>().ok()?, rest),
            None => (0, etime),
        };
        let parts: Vec<i64> = rest
            .split(':')
            .map(|part| part.parse().ok())
            .collect::<Option<_>>()?;
        let (h, m, s) = match parts.as_slice() {
            [m, s] => (0, *m, *s),
            [h, m, s] => (*h, *m, *s),
            _ => return None,
        };
        Some(days * 86_400 + h * 3_600 + m * 60 + s)
    };
    let table: Vec<(u32, u32, i64)> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            let child: u32 = fields.next()?.parse().ok()?;
            let parent: u32 = fields.next()?.parse().ok()?;
            let started = now - seconds(fields.next()?)?;
            Some((child, parent, started))
        })
        .collect();
    let roots: Vec<u32> = table
        .iter()
        .filter(|(_, parent, started)| *parent == pid && *started >= since)
        .map(|(child, _, _)| *child)
        .collect();
    for root in &roots {
        let mut tree = vec![*root];
        let mut index = 0;
        while index < tree.len() {
            let parent = tree[index];
            tree.extend(
                table
                    .iter()
                    .filter(|(_, p, _)| *p == parent)
                    .map(|(c, _, _)| *c),
            );
            index += 1;
        }
        // Children first, so none is reparented and missed.
        for member in tree.iter().rev() {
            // SAFETY: `kill` only sends a signal to the named process.
            unsafe { libc::kill(*member as libc::pid_t, libc::SIGTERM) };
        }
    }
    roots
}

#[cfg(not(unix))]
fn end_turn_children(_pid: u32, _since: i64) -> Vec<u32> {
    Vec::new()
}

/// Close a daemon pane on this machine.
fn close_pane(pane: &str, label: &str) -> Result<()> {
    close_pane_on(pane, label, None)
}

/// Close a daemon pane on this machine, or on `machine` through its Teams server.
fn close_pane_on(pane: &str, label: &str, machine: Option<&str>) -> Result<()> {
    let program = std::env::current_exe().context("locate this supercode")?;
    let mut command = std::process::Command::new(program);
    command.args(["teams", "panes", "close", pane]);
    if let Some(machine) = machine {
        command.args(["--machine", machine]);
    }
    let status = command
        .stdout(std::process::Stdio::null())
        .status()
        .context("run supercode teams panes close")?;
    let there = machine
        .map(|machine| format!(" on {machine}"))
        .unwrap_or_default();
    if !status.success() {
        bail!("the machine daemon{there} did not close pane {pane}");
    }
    println!("closed {label} (pane {pane}{there})");
    Ok(())
}

/// Open a session another machine listed: attach to its pane there. Outside a pane, `--move`
/// runs `open --move` on that machine, which ends it and opens it in a pane of its daemon.
fn open_there(homes: &HarnessHomes, row: &Value, open: &OpenArgs, view: View) -> Result<()> {
    let label = row["name"].as_str().unwrap_or_default().to_string();
    let (machine, pane) = match remote_pane(row, "opened") {
        Ok(found) => found,
        Err(_) if open.relocate && row["pane"].is_null() && !is_hosted_row(row) => {
            let (machine, address) = row_machine(row)?;
            run_there(
                &machine,
                &address,
                &["open", &address, "--move", "--detach"],
            )?;
            let pane = await_pane(homes, &address).ok_or_else(|| {
                anyhow!("{label} was not seen in a pane on {machine} within 30 seconds")
            })?;
            (machine, pane)
        }
        Err(error) => return Err(error),
    };
    let view = View {
        on: Some(&machine),
        ..view
    };
    attach(&pane, &view, &label)
}

/// Close a session another machine listed: its pane there, or, outside a pane, `close` runs
/// on that machine, which ends its process.
fn close_there(homes: &HarnessHomes, row: &Value) -> Result<()> {
    let label = row["name"].as_str().unwrap_or_default();
    if row["pane"].is_null() && !is_hosted_row(row) {
        let (machine, address) = row_machine(row)?;
        run_there(&machine, &address, &["close", &address])?;
        if !await_gone(homes, &address) {
            bail!("{label} still runs on {machine} 30 seconds after `supercode close` ran there");
        }
        println!("closed {label} on {machine} (its process ended there; its transcript stays)");
        return Ok(());
    }
    let (machine, pane) = remote_pane(row, "closed")?;
    close_pane_on(&pane, label, Some(&machine))
}

/// Whether a session another machine listed is a runtime supercode hosts there: its door is the
/// runtime (a machine before the runtime's turn became its status said `hosted` instead).
fn is_hosted_row(row: &Value) -> bool {
    row["delivery"] == "runtime" || row["status"] == "hosted"
}

/// The machine and address of a session another machine listed.
fn row_machine(row: &Value) -> Result<(String, String)> {
    let address = MailAddress::parse(row["address"].as_str().unwrap_or_default())?;
    Ok((address.machine.clone(), address.to_string()))
}

/// Run `supercode ARGS` on `machine`, in a pane its daemon launches (the door `open --new
/// --on` uses): a verb on a session there is that machine's own verb.
fn run_there(machine: &str, address: &str, args: &[&str]) -> Result<()> {
    let mut request = vec![
        "launch".to_string(),
        "--on".into(),
        machine.to_string(),
        format!("--launch-key=there:{}:{address}", args[0]),
        // The verb runs there as this caller, so there too a session acts only on what it started.
        "--act-for-caller".into(),
        "supercode".into(),
        "--".into(),
    ];
    request.extend(args.iter().map(|arg| arg.to_string()));
    fleet_json(&request).map(|_| ())
}

/// The pane `address` runs in on its machine, once its machine lists one (30 seconds at most).
fn await_pane(homes: &HarnessHomes, address: &str) -> Option<String> {
    let deadline = Instant::now() + Duration::from_secs(30);
    while Instant::now() < deadline {
        let pane = crate::message::team_session(homes, address)
            .and_then(|row| row["pane"].as_str().map(str::to_string));
        if pane.is_some() {
            return pane;
        }
        std::thread::sleep(Duration::from_secs(2));
    }
    None
}

/// Whether `address` is gone from its machine's list within 30 seconds.
fn await_gone(homes: &HarnessHomes, address: &str) -> bool {
    let deadline = Instant::now() + Duration::from_secs(30);
    while Instant::now() < deadline {
        if crate::message::team_session(homes, address).is_none() {
            return true;
        }
        std::thread::sleep(Duration::from_secs(2));
    }
    false
}

/// The machine and daemon pane of a session another machine listed (`message list`'s row):
/// a session there is reached through its pane, so one outside a pane is refused, naming why.
fn remote_pane(row: &Value, verb: &str) -> Result<(String, String)> {
    let name = row["name"].as_str().unwrap_or_default();
    let address = MailAddress::parse(row["address"].as_str().unwrap_or_default())?;
    if is_hosted_row(row) {
        bail!(
            "{name} is a runtime supercode hosts on {}; it is {verb} there",
            address.machine
        );
    }
    match row["pane"].as_str() {
        Some(pane) => Ok((address.machine, pane.to_string())),
        None => bail!(
            "{name} runs on {} outside any pane its machine daemon holds. Nothing was {verb}: \
             `supercode open {name} --move` ends it there and opens it in a pane there.",
            address.machine
        ),
    }
}

/// A session ends only the processes it started: one run below its own process. A person (no session behind
/// this command) and a board may end any; a session is refused on anything else, naming why.
fn refuse_foreign_process(pid: u32, label: &str) -> Result<()> {
    let Some(caller) = crate::acting_caller() else {
        return Ok(());
    };
    let Ok(address) = MailAddress::parse(&caller) else {
        return Ok(());
    };
    if address.harness == "board" {
        return Ok(());
    }
    let own = LiveSessions::read(&HarnessHomes::default())
        .all()
        .iter()
        .find(|session| session.address == address)
        .and_then(|session| session.pid);
    let ancestry = supercode_harness::mail_route::ancestry_of(pid);
    if own.is_some_and(|own| ancestry[1..].contains(&own)) {
        return Ok(());
    }
    bail!(
        "{label} (pid {pid}) was not started by {caller}: a session ends only the processes it started. \
         Nothing was closed; reach that session through its own doors (supercode message send)"
    )
}

fn end_process(pid: u32) -> Result<()> {
    #[cfg(unix)]
    {
        // SAFETY: `kill` only sends a signal to the named process.
        let alive = |signal| unsafe { libc::kill(pid as libc::pid_t, signal) == 0 };
        alive(libc::SIGTERM);
        let deadline = Instant::now() + Duration::from_secs(10);
        while Instant::now() < deadline {
            if !alive(0) {
                return Ok(());
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        bail!("the session's process (pid {pid}) did not end within 10 seconds; nothing was opened")
    }
    #[cfg(windows)]
    {
        use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
        use windows_sys::Win32::System::Threading::{
            OpenProcess, TerminateProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE,
            PROCESS_TERMINATE,
        };
        // Windows has no signal a console program answers from outside its console: the
        // process is terminated, as closing its window would end it.
        // SAFETY: the handle is opened for this pid only and closed before returning.
        unsafe {
            let handle = OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, 0, pid);
            if handle.is_null() {
                bail!("the session's process (pid {pid}) could not be opened to end it");
            }
            let ended = TerminateProcess(handle, 1) != 0
                && WaitForSingleObject(handle, 10_000) == WAIT_OBJECT_0;
            CloseHandle(handle);
            if !ended {
                bail!("the session's process (pid {pid}) did not end within 10 seconds; nothing was opened");
            }
        }
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    bail!("ending a session outside a pane is not supported on this platform (pid {pid})")
}

/// Attach this terminal to `pane`, or print it.
///
/// A pane on this machine: this terminal becomes a tmux client of it
/// directly, so nothing is relayed through the daemon, a daemon restart does
/// not end the view, and the pane takes this terminal's own size. The client
/// presents itself as the daemon's relay clients do (`screen-256color`), which
/// is what the pane's tmux server gives native scrollback, selection and
/// clipboard to. A pane on another machine: its terminal stream through that
/// machine's Teams server. ctrl-] detaches either way.
fn attach(pane: &str, view: &View, label: &str) -> Result<()> {
    // Without a terminal there is nothing to attach: the pane is printed, as
    // `--detach` prints it, so the caller can still reach it.
    use std::io::IsTerminal;
    if view.detach || !(std::io::stdin().is_terminal() && std::io::stdout().is_terminal()) {
        println!(
            "{}",
            serde_json::json!({"pane": pane, "session": label, "machine": view.on})
        );
        return Ok(());
    }
    let mode = if view.observe { "observe" } else { "control" };
    if let Some(machine) = view.on {
        let mut request = vec![
            "attach".to_string(),
            "--on".into(),
            machine.to_string(),
            pane.to_string(),
            format!("--mode={mode}"),
        ];
        if let Some(context) = view.context {
            request.push(format!("--context={context}"));
        }
        return crate::run_fleet(&request);
    }
    // Daemon panes have no prefix key; ctrl-] detaches from them and passes
    // through to every other tmux session. Both commands go to the panes' own
    // tmux server: inside a person's tmux, $TMUX would name theirs instead (and
    // the attach nests in their window).
    let bound = std::process::Command::new("tmux")
        .env_remove("TMUX")
        .args([
            "bind-key",
            "-n",
            "C-]",
            "if-shell",
            "-F",
            "#{m:p_*,#{session_name}}",
            "detach-client",
            "send-keys C-]",
        ])
        .status()
        .context("run tmux")?;
    if !bound.success() {
        bail!("tmux refused the detach key for {pane}");
    }
    eprintln!("[{label}: ctrl-] detaches; the session keeps running]");
    let mut client = std::process::Command::new("tmux");
    client.args(["-T", "RGB", "attach-session"]);
    if view.observe {
        client.arg("-r");
    }
    client
        .args(["-t", pane])
        .env("TERM", "screen-256color")
        .env_remove("TMUX");
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        let error = client.exec();
        bail!("could not attach to {pane}: {error}")
    }
    #[cfg(not(unix))]
    {
        let status = client.status().context("run tmux")?;
        if !status.success() {
            bail!("tmux could not attach to {pane}");
        }
        Ok(())
    }
}

/// One fleet verb whose answer is JSON on stdout.
fn fleet_json(args: &[String]) -> Result<Value> {
    let entry = crate::fleet_entry()?;
    let mut command = std::process::Command::new(crate::teams_node_bin());
    command.arg(&entry).args(args);
    crate::act_for_caller(&mut command);
    let output = command
        .stdin(std::process::Stdio::null())
        .output()
        .context("run the teams CLI")?;
    if !output.status.success() {
        bail!(
            "the machine daemon refused: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    serde_json::from_slice(&output.stdout).context("read the machine daemon's answer")
}

fn short(id: &str) -> String {
    id.chars().take(8).collect()
}