supercode-cli 0.5.12

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
//! `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 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>,
    /// 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();
    let target = match resolve(&homes, wanted)? {
        Resolved::Session(target) => target,
        Resolved::Runtime(runtime) => return open_runtime(cli, open, &runtime).await,
    };
    let label = target.name.clone().unwrap_or_else(|| short(&target.id));
    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
            );
        }
        end_process(pid)?;
    }
    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 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 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)
}

/// 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<()> {
    let mut request = vec!["launch".to_string()];
    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}"));
    }
    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());
    request.extend(no_prompt_arguments(&kind, cwd.as_deref(), &open.args));
    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, 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 = tmux.clone().filter(|session| is_daemon_pane(session));
        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))
}

/// 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> {
    let chooses = |flags: &[&str]| {
        arguments.iter().any(|argument| {
            flags
                .iter()
                .any(|flag| argument == flag || argument.starts_with(&format!("{flag}=")))
        })
    };
    match harness {
        HarnessId::CLAUDE_CODE
            if !chooses(&[
                "--permission-mode",
                "--permission-prompts",
                "--dangerously-skip-permissions",
                "--allow-dangerously-skip-permissions",
            ]) =>
        {
            vec!["--dangerously-skip-permissions".into()]
        }
        HarnessId::CODEX
            if !chooses(&[
                "-a",
                "--ask-for-approval",
                "-s",
                "--sandbox",
                "--approve-for-me",
                "--dangerously-bypass-approvals-and-sandbox",
            ]) =>
        {
            let mut flags: Vec<String> = Vec::new();
            if let Some(cwd) = cwd {
                let key = serde_json::to_string(cwd.to_string_lossy().as_ref())
                    .expect("a path serializes as JSON text");
                flags.extend([
                    "-c".into(),
                    format!("projects={{{key}={{trust_level=\"trusted\"}}}}"),
                ]);
            }
            flags.extend([
                "--dangerously-bypass-approvals-and-sandbox".into(),
                "--dangerously-bypass-hook-trust".into(),
            ]);
            flags
        }
        _ => Vec::new(),
    }
}

/// 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.
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.
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(not(unix))]
    bail!("`--move` ends a process by signal, which this platform does not have (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<()> {
    if view.detach {
        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 output = std::process::Command::new(crate::teams_node_bin())
        .arg(&entry)
        .args(args)
        .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()
}