supercode-harness 0.5.45

The optional native Volter Harness agent and tool harness
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
//! One route for every message: which door reaches a receiver, and delivery
//! through it.
//!
//! Every caller that delivers mail — `supercode message send`,
//! `harness.v1.sessions.message`, and idle notices — goes through
//! [`door_for`] and [`deliver`], so the choice of door is made in one place.
//! The doors, best first:
//!
//! 1. **runtime** — a session supercode controls (a hosted runtime of any
//!    harness): its own `steer`/`send_input` ([`crate::runtime_mail`]). This
//!    is the default tier.
//! 2. **native** — a Claude Code session supercode does not control: a Claude
//!    relay sends with Claude's own `SendMessage` ([`crate::claude_relay`]).
//! 3. **hook** — a Codex session supercode does not control, with
//!    supercode's hooks in its hooks file: filed in its mailbox, and the hook
//!    points the session at it.
//! 4. **stored** — no door: filed in its mailbox, seen only when the session
//!    reads it.
//!
//! Tiers 2–4 are the degradation tier, for sessions supercode does not
//! control. An operator (a board, a script) is not a session: its mail is
//! filed in its mailbox and read with `sessions.inbox`.

use std::path::Path;

use crate::claude_peer::{read_registry, registry_dir, ClaudePeerSession, ClaudePeerStatus};
use crate::claude_relay::{send_through_relay, supercode_program, RelayReceipt, RELAY_NAME_PREFIX};
use crate::live_runtime::LiveRuntimeRecord;
use crate::mailbox::{
    local_machine_name, mail_root, Envelope, IdleSubscription, MailAddress, Mailbox, ReplyVia,
};
use crate::runtime_mail::{deliver_to_runtime, RuntimeDelivery};
use crate::HarnessHomes;

/// Arguments a Codex hook entry carries, which is how its presence is found.
pub const CODEX_HOOK_ARGUMENTS: &str = "message hook codex";

/// The door that reaches one receiver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Door {
    /// A session supercode controls.
    Runtime(Box<LiveRuntimeRecord>),
    /// A Claude Code session supercode does not control.
    Native(Box<ClaudePeerSession>),
    /// A Codex session supercode does not control, with supercode's hooks.
    Hook,
    /// A running session with no door.
    Stored,
    /// An operator's mailbox.
    Operator,
}

impl Door {
    /// Stable name of the door, as `message list` and receipts show it.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Runtime(_) => "runtime",
            Self::Native(_) => "native",
            Self::Hook => "hook",
            Self::Stored => "stored",
            Self::Operator => "operator",
        }
    }
}

/// Why no door reaches an address on this machine.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoDoor {
    /// The address names another machine.
    OtherMachine(String),
    /// No running session has that address.
    NotRunning,
}

/// The door that reaches `to` on this machine.
pub fn door_for(homes: &HarnessHomes, to: &MailAddress) -> Result<Door, NoDoor> {
    if to.machine != local_machine_name() {
        return Err(NoDoor::OtherMachine(to.machine.clone()));
    }
    if to.harness == "operator" {
        return Ok(Door::Operator);
    }
    LiveSessions::read(homes)
        .sessions
        .into_iter()
        .find(|session| &session.address == to)
        .map(|session| session.door)
        .ok_or(NoDoor::NotRunning)
}

/// One running session on this machine, as the router reaches it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiveSession {
    /// Its address.
    pub address: MailAddress,
    /// The name an agent knows it by (`volter-2c@machine`).
    pub name: String,
    /// Its status as its harness reports it (`busy`, `idle`, `hosted`, …).
    pub status: String,
    /// The door that reaches it.
    pub door: Door,
    /// The process running it, when the harness names one (a hosted
    /// runtime's host, a Claude session's own process).
    pub pid: Option<u32>,
    /// Its working directory.
    pub cwd: Option<std::path::PathBuf>,
    /// The tmux session and pane it runs in, when Claude records one.
    pub tmux: Option<String>,
}

/// Every running session on this machine with its door, read once: what
/// `message list` shows, what names resolve against, and what discovery
/// projects onto each discovered session as `delivery`.
#[derive(Debug, Default)]
pub struct LiveSessions {
    sessions: Vec<LiveSession>,
}

/// Why a receiver named by an agent was not found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unresolved {
    /// The address names a session that is not running.
    Stale(String),
    /// No running session has that name (the text suggests near names).
    Unknown(String),
}

impl LiveSessions {
    /// Read every running session now. Sessions supercode controls come
    /// first, and a degraded-tier row for the same session is dropped: the
    /// runtime is the default tier.
    pub fn read(homes: &HarnessHomes) -> Self {
        let machine = local_machine_name();
        let registry = read_registry(&registry_dir(homes));
        // A hosted Claude session is also in Claude's registry, which knows
        // its name; a relay is not a session and is not listed.
        let registered = |record: &crate::live_runtime::LiveRuntimeRecord| {
            registry.iter().find(|session| {
                session.session_id == record.source.session_id
                    || session.session_id == record.runtime_session_id
            })
        };
        let mut sessions: Vec<LiveSession> = crate::runtime_mail::controlled_runtimes()
            .into_iter()
            .filter_map(|record| {
                let registered = registered(&record);
                if registered.is_some_and(|session| session.name.starts_with(RELAY_NAME_PREFIX)) {
                    return None;
                }
                let address =
                    MailAddress::new(&machine, &record.source.harness, &record.source.session_id)
                        .ok()?;
                let short: String = record.source.session_id.chars().take(8).collect();
                let name = match registered {
                    Some(session) if !session.name.is_empty() => session.name.clone(),
                    _ => format!("{}-{short}", record.source.harness),
                };
                Some(LiveSession {
                    name: format!("{name}@{machine}"),
                    address,
                    status: "hosted".into(),
                    pid: Some(record.pid),
                    cwd: Some(record.source.workspace.clone()),
                    tmux: None,
                    door: Door::Runtime(Box::new(record)),
                })
            })
            .collect();
        let controlled = |address: &MailAddress, sessions: &[LiveSession]| {
            sessions.iter().any(|session| &session.address == address)
        };
        for session in registry {
            if session.name.starts_with(RELAY_NAME_PREFIX) {
                continue;
            }
            let Ok(address) = MailAddress::new(&machine, "claude-code", &session.session_id) else {
                continue;
            };
            if controlled(&address, &sessions) {
                continue;
            }
            sessions.push(LiveSession {
                address,
                name: format!("{}@{machine}", session.name),
                status: session
                    .status
                    .as_ref()
                    .map(|status| status.as_str().to_string())
                    .unwrap_or_else(|| "unknown".into()),
                pid: Some(session.pid),
                cwd: session.cwd.clone(),
                tmux: session.tmux.clone(),
                door: Door::Native(Box::new(session)),
            });
        }
        let user_hook = codex_user_hook_installed();
        for (path, status) in crate::codex_peer::live_rollouts(&homes.codex) {
            let Some((session_id, None)) = crate::codex_peer::rollout_session(&path) else {
                continue;
            };
            let Ok(address) = MailAddress::new(&machine, "codex", &session_id) else {
                continue;
            };
            if controlled(&address, &sessions) {
                continue;
            }
            let cwd = crate::codex_peer::rollout_cwd(&path);
            let hooked = user_hook || cwd.as_deref().is_some_and(codex_project_hook_installed);
            sessions.push(LiveSession {
                name: format!("{}@{machine}", codex_name(&session_id)),
                address,
                status: status.as_str().to_string(),
                pid: None,
                cwd,
                tmux: None,
                door: if hooked { Door::Hook } else { Door::Stored },
            });
        }
        Self { sessions }
    }

    /// Every running session.
    pub fn all(&self) -> &[LiveSession] {
        &self.sessions
    }

    /// The door that reaches `harness`'s session `session_id`, when it is
    /// running.
    pub fn door(&self, harness: &str, session_id: &str) -> Option<&'static str> {
        self.sessions
            .iter()
            .find(|session| {
                session.address.harness == harness && session.address.session_id == session_id
            })
            .map(|session| session.door.name())
    }

    /// The running session an agent means by `to`: an address, `name@machine`
    /// on this machine, or a name unique here.
    pub fn resolve(&self, to: &str) -> Result<&LiveSession, Unresolved> {
        let machine = local_machine_name();
        if let Ok(address) = MailAddress::parse(to) {
            return self
                .sessions
                .iter()
                .find(|session| session.address == address)
                .ok_or_else(|| {
                    Unresolved::Stale(format!(
                        "{to} is no longer running. Nothing was sent. Run supercode message list \
                         for the live sessions."
                    ))
                });
        }
        let wanted = match to.split_once('@') {
            Some((name, at)) if at == machine => name.to_string(),
            Some((_, at)) => {
                return Err(Unresolved::Unknown(format!(
                    "Not sent: {to} is on machine {at}, not this one. Nothing was sent."
                )))
            }
            None => to.to_string(),
        };
        let short = |session: &LiveSession| {
            session
                .name
                .split('@')
                .next()
                .unwrap_or_default()
                .to_string()
        };
        let matching: Vec<&LiveSession> = self
            .sessions
            .iter()
            .filter(|session| short(session) == wanted)
            .collect();
        if let [only] = matching.as_slice() {
            return Ok(only);
        }
        let hint = if matching.len() > 1 {
            format!(
                " {} sessions are named {wanted}; use its address.",
                matching.len()
            )
        } else {
            let near: Vec<String> = self
                .sessions
                .iter()
                .filter(|session| {
                    let name = short(session);
                    name.contains(&wanted)
                        || wanted.contains(&name)
                        || name
                            .chars()
                            .zip(wanted.chars())
                            .take_while(|(a, b)| a == b)
                            .count()
                            >= 4
                })
                .take(3)
                .map(|session| {
                    format!(
                        "{} ({}, {})",
                        session.name, session.address.harness, session.status
                    )
                })
                .collect();
            if near.is_empty() {
                String::new()
            } else {
                format!(" Did you mean: {}?", near.join(", "))
            }
        };
        Err(Unresolved::Unknown(format!(
            "No session named \"{wanted}\" is reachable.{hint} Run supercode message list. Nothing \
             was sent."
        )))
    }
}

/// Whether the session process `pid` has supercode's messaging tools: a
/// harness starts each MCP server as a child of the session, so the tools are
/// loaded exactly when a live `supercode message mcp` is one of its children.
pub fn has_message_tools(pid: u32) -> bool {
    let Ok(output) = std::process::Command::new("ps")
        .args(["-A", "-o", "ppid=,command="])
        .output()
    else {
        return false;
    };
    String::from_utf8_lossy(&output.stdout).lines().any(|line| {
        let line = line.trim_start();
        let Some((ppid, command)) = line.split_once(' ') else {
            return false;
        };
        ppid.parse::<u32>() == Ok(pid) && command.trim_end().ends_with(" message mcp")
    })
}

/// Display name of a Codex conversation: `codex-` and the start of its id.
pub fn codex_name(session_id: &str) -> String {
    format!("codex-{}", session_id.chars().take(8).collect::<String>())
}

/// The session a process belongs to: the sender a message is from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Caller {
    /// Its address, where replies go.
    pub address: MailAddress,
    /// The name it is known by.
    pub name: String,
}

/// Why no session could be found behind a process.
pub const CALLER_UNRESOLVED: &str = "Can't tell which session is running this command, so \
    replies would have nowhere to go. Nothing was sent. Run it from your agent session's own \
    shell tool.";

/// The session behind a process, from its ancestry `pids` (nearest first):
/// the first that owns a hosted runtime, a Claude session or a Codex
/// conversation. Never declared by the caller; an environment id only
/// corroborates, and a mismatch refuses.
pub fn resolve_caller(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
    let machine = local_machine_name();
    let registry = read_registry(&registry_dir(homes));
    let hosted = crate::runtime_mail::controlled_runtimes();
    for &pid in pids {
        if let Some(record) = hosted.iter().find(|record| record.pid == pid) {
            let short: String = record.source.session_id.chars().take(8).collect();
            return Ok(Caller {
                address: MailAddress::new(
                    &machine,
                    &record.source.harness,
                    &record.source.session_id,
                )
                .map_err(|error| error.to_string())?,
                name: format!("{}-{short}@{machine}", record.source.harness),
            });
        }
        if let Some(session) = registry.iter().find(|session| session.pid == pid) {
            if let Ok(claimed) = std::env::var("CLAUDE_CODE_SESSION_ID") {
                if !claimed.is_empty() && claimed != session.session_id {
                    return Err(format!(
                        "{CALLER_UNRESOLVED} (CLAUDE_CODE_SESSION_ID names {claimed}, but the Claude \
                         process {pid} above this command is session {})",
                        session.session_id
                    ));
                }
            }
            return Ok(Caller {
                address: MailAddress::new(&machine, "claude-code", &session.session_id)
                    .map_err(|error| error.to_string())?,
                name: format!("{}@{machine}", session.name),
            });
        }
        // Codex names the thread a command runs for (`CODEX_THREAD_ID`); the
        // claim stands when this process holds that thread's rollout, as
        // Codex's shared app-server daemon does for every thread it runs.
        if let Some(thread) = std::env::var("CODEX_THREAD_ID")
            .ok()
            .filter(|thread| !thread.is_empty())
            .filter(|thread| crate::codex_peer::holds_session(pid, thread))
        {
            return Ok(Caller {
                address: MailAddress::new(&machine, "codex", &thread)
                    .map_err(|error| error.to_string())?,
                name: format!("{}@{machine}", codex_name(&thread)),
            });
        }
        if let Some((session_id, _)) = crate::codex_peer::session_of_process(pid) {
            return Ok(Caller {
                address: MailAddress::new(&machine, "codex", &session_id)
                    .map_err(|error| error.to_string())?,
                name: format!("{}@{machine}", codex_name(&session_id)),
            });
        }
    }
    #[cfg(windows)]
    if let Some(session) = msys_cut_claim(&registry, pids) {
        return Ok(Caller {
            address: MailAddress::new(&machine, "claude-code", &session.session_id)
                .map_err(|error| error.to_string())?,
            name: format!("{}@{machine}", session.name),
        });
    }
    Err(format!(
        "{CALLER_UNRESOLVED} (looked for this command's processes {pids:?} among {} Claude \
         sessions in {} and {} hosted runtimes)",
        registry.len(),
        registry_dir(homes).display(),
        hosted.len()
    ))
}

/// Git Bash (MSYS) runs a command in a forked process that hands over to it. When the command is
/// itself an MSYS program (a `sh` script, as npm's command shims are), the forked process exits once
/// it has handed over, so the Windows parent chain is cut just above that shell and never reaches
/// the Claude session running it. When the ancestry ends at exactly such a cut (its last pid is gone,
/// the one before it is an MSYS shell), the session Claude names in `CLAUDE_CODE_SESSION_ID` stands
/// if it is a live Claude session on this machine.
#[cfg(windows)]
fn msys_cut_claim<'a>(
    registry: &'a [ClaudePeerSession],
    pids: &[u32],
) -> Option<&'a ClaudePeerSession> {
    let table = process_table();
    let [.., shell, cut] = pids else {
        return None;
    };
    if table.contains_key(cut) {
        return None;
    }
    let name = table.get(shell)?.1.to_ascii_lowercase();
    if !matches!(name.as_str(), "sh.exe" | "bash.exe" | "dash.exe") {
        return None;
    }
    let claimed = std::env::var("CLAUDE_CODE_SESSION_ID").ok()?;
    registry
        .iter()
        .find(|session| !claimed.is_empty() && session.session_id == claimed)
}

/// This process's ancestry, nearest first (itself included).
pub fn process_ancestry() -> Vec<u32> {
    ancestry_of(std::process::id())
}

/// A process's ancestry, nearest first (itself included).
pub fn ancestry_of(pid: u32) -> Vec<u32> {
    let parents = parent_pids();
    let mut chain = vec![pid];
    let mut current = pid;
    while let Some(&parent) = parents.get(&current) {
        if parent <= 1 || chain.contains(&parent) {
            break;
        }
        chain.push(parent);
        current = parent;
    }
    chain
}

/// Every process's parent: pid → parent pid, from `ps`.
#[cfg(not(windows))]
fn parent_pids() -> std::collections::HashMap<u32, u32> {
    let Ok(output) = std::process::Command::new("ps")
        .args(["-axo", "pid=,ppid="])
        .output()
    else {
        return Default::default();
    };
    String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let mut fields = line.split_whitespace();
            Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?))
        })
        .collect()
}

/// Every process's parent: pid → parent pid, from a process snapshot.
#[cfg(windows)]
fn parent_pids() -> std::collections::HashMap<u32, u32> {
    process_table()
        .into_iter()
        .map(|(pid, (parent, _))| (pid, parent))
        .collect()
}

/// Every process: pid → (parent pid, executable file name), from a process snapshot.
#[cfg(windows)]
fn process_table() -> std::collections::HashMap<u32, (u32, String)> {
    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
        TH32CS_SNAPPROCESS,
    };

    let mut parents = std::collections::HashMap::new();
    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
    if snapshot == INVALID_HANDLE_VALUE {
        return parents;
    }
    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
    entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
    let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
    while has_entry {
        let length = entry
            .szExeFile
            .iter()
            .position(|&unit| unit == 0)
            .unwrap_or(entry.szExeFile.len());
        let name = String::from_utf16_lossy(&entry.szExeFile[..length]);
        parents.insert(entry.th32ProcessID, (entry.th32ParentProcessID, name));
        has_entry = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
    }
    unsafe {
        CloseHandle(snapshot);
    }
    parents
}

/// Codex's user-level hooks file.
pub fn codex_hooks_path() -> std::path::PathBuf {
    std::env::var_os("CODEX_HOME")
        .map(std::path::PathBuf::from)
        .or_else(|| {
            supercode_interchange::user_home()
                .map(std::path::PathBuf::into_os_string)
                .map(|home| std::path::PathBuf::from(home).join(".codex"))
        })
        .unwrap_or_else(|| std::path::PathBuf::from(".codex"))
        .join("hooks.json")
}

/// Whether supercode's mail hook is in Codex's user hooks file. (Codex runs
/// it only once its user has trusted it.)
pub fn codex_user_hook_installed() -> bool {
    std::fs::read_to_string(codex_hooks_path())
        .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
}

/// Whether supercode's mail hook is in a project's Codex hooks file, in the
/// session's directory or one above it.
pub fn codex_project_hook_installed(cwd: &Path) -> bool {
    cwd.ancestors().any(|directory| {
        std::fs::read_to_string(directory.join(".codex").join("hooks.json"))
            .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
    })
}

/// How a delivery ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Delivered {
    /// The receiver has it now: steered into a running turn.
    Steered,
    /// The receiver has it now: it started a turn in an idle session.
    Started,
    /// Claude reported it in the receiver's inbox; `busy` says whether the
    /// receiver reads it at its next tool call (true) or it starts a turn.
    Native {
        /// True when the receiver was in a turn.
        busy: bool,
    },
    /// Filed in the receiver's mailbox, which a hook points it at.
    Hooked,
    /// Filed in the receiver's mailbox, waiting to be read.
    Queued,
    /// Filed with no door to show it.
    Stored,
    /// Filed in an operator's mailbox.
    Operator,
}

/// A delivery refused before anything was sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refused {
    /// `--queue` cannot hold a message for an idle Claude session: Claude
    /// starts a turn for every message it delivers.
    CannotQueueNative,
    /// The relayed text would not fit one relay turn.
    TooLong(usize),
}

/// Largest message relayed into a Claude session. The relay copies it into a
/// model turn byte for byte, so it must fit comfortably in one.
pub const MAX_RELAYED_BYTES: usize = 100_000;

/// Deliver `envelope` to `to` through `door`. With `wake` false an idle
/// receiver is not started. With `notify_when_idle` the sender gets one idle
/// notice after the receiver's next turn ends.
pub async fn deliver(
    envelope: &Envelope,
    to: &MailAddress,
    door: &Door,
    wake: bool,
    notify_when_idle: bool,
) -> Result<Result<Delivered, Refused>, String> {
    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
    // A runtime answers with its turn's final message, which the watcher
    // sends back: not every runtime can run a command (a hosted agent may
    // have no shell), and each can end a turn.
    let mut final_reply = false;
    let delivered = match door {
        Door::Runtime(record) => {
            let mut sent = envelope.clone();
            let answers = matches!(envelope.reply_via, ReplyVia::Command);
            if answers {
                sent.reply_via = ReplyVia::FinalMessage {
                    destination: envelope.from_name.clone(),
                };
            }
            match deliver_to_runtime(record, sent.render(), wake).await? {
                RuntimeDelivery::Steered => {
                    mailbox
                        .deliver_read(&sent)
                        .map_err(|error| error.to_string())?;
                    final_reply = answers;
                    Delivered::Steered
                }
                RuntimeDelivery::Started => {
                    mailbox
                        .deliver_read(&sent)
                        .map_err(|error| error.to_string())?;
                    final_reply = answers;
                    Delivered::Started
                }
                RuntimeDelivery::NotWoken => {
                    mailbox
                        .deliver(envelope)
                        .map_err(|error| error.to_string())?;
                    Delivered::Queued
                }
            }
        }
        Door::Native(session) => {
            let busy = session.status != Some(ClaudePeerStatus::Idle);
            if !wake && !busy {
                return Ok(Err(Refused::CannotQueueNative));
            }
            // The same envelope every door delivers; Claude wraps it in its
            // own, which names the relay. Its reply line names the door this
            // session really has: its tools when it runs supercode's MCP server.
            let mut envelope = envelope.clone();
            if envelope.reply_via == ReplyVia::Command && has_message_tools(session.pid) {
                envelope.reply_via = ReplyVia::Tool;
            }
            let envelope = &envelope;
            let text = envelope.render();
            if text.len() > MAX_RELAYED_BYTES {
                return Ok(Err(Refused::TooLong(text.len())));
            }
            match send_through_relay(
                &envelope.from,
                &envelope.from_name,
                &session.name,
                text,
                &envelope.id,
            )
            .await
            {
                RelayReceipt::Delivered { .. } => {
                    mailbox
                        .deliver_read(envelope)
                        .map_err(|error| error.to_string())?;
                    Delivered::Native { busy }
                }
                RelayReceipt::Failed { detail } => return Err(detail),
            }
        }
        Door::Hook => {
            mailbox
                .deliver(envelope)
                .map_err(|error| error.to_string())?;
            Delivered::Hooked
        }
        Door::Stored => {
            mailbox
                .deliver(envelope)
                .map_err(|error| error.to_string())?;
            Delivered::Stored
        }
        Door::Operator => {
            mailbox
                .deliver(envelope)
                .map_err(|error| error.to_string())?;
            Delivered::Operator
        }
    };
    let notice = notify_when_idle && !matches!(door, Door::Operator);
    if notice || final_reply {
        let mut subscription = IdleSubscription::new(envelope.id.clone(), envelope.from.clone());
        subscription.notice = notice;
        subscription.final_reply = final_reply;
        mailbox
            .subscribe_idle(&subscription)
            .map_err(|error| error.to_string())?;
        // The watcher that settles it runs beside the machine daemon.
        if let Ok(program) = supercode_program() {
            crate::claude_relay::ensure_machine_daemon(&program)
                .await
                .ok();
        }
    }
    Ok(Ok(delivered))
}

/// How the user's own turn reached its session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UserTurn {
    /// A hosted runtime was in a turn; the words were steered into it.
    Steered,
    /// A hosted runtime was idle; the words started a turn.
    Started,
    /// Typed into the session's pane as its own submitted turn.
    Typed,
    /// The pane's composer holds a draft, or its program is not at its
    /// composer: the turn waits in the session's mailbox and is typed once
    /// the composer is empty.
    Waiting,
}

impl UserTurn {
    /// Stable wire spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Steered => "steered",
            Self::Started => "started",
            Self::Typed => "typed",
            Self::Waiting => "waiting",
        }
    }
}

/// The daemon pane a session runs in, when it runs in one.
pub fn daemon_pane(session: &LiveSession) -> Option<String> {
    let name = session.tmux.as_deref()?.split(':').next()?;
    let rest = name.strip_prefix("p_")?;
    (!rest.is_empty()
        && rest
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
    .then(|| name.to_string())
}

/// Deliver the user's own turn to `to` through the one door that carries the
/// user's authority: a hosted runtime's own input, or the session's pane.
/// A session with neither (running outside supercode) is refused, never
/// reached as a peer instead. Callers hold the owner's authority already:
/// this is reached only through owner doors (the machine's own harness.v1).
pub async fn deliver_user_turn(
    homes: &HarnessHomes,
    envelope: &Envelope,
    to: &MailAddress,
) -> Result<UserTurn, String> {
    let session = LiveSessions::read(homes)
        .sessions
        .into_iter()
        .find(|session| &session.address == to)
        .ok_or_else(|| format!("{to} is not running; nothing was sent"))?;
    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
    if let Door::Runtime(record) = &session.door {
        let delivered = deliver_to_runtime(record, envelope.body.clone(), true).await?;
        mailbox
            .deliver_read(envelope)
            .map_err(|error| error.to_string())?;
        return Ok(match delivered {
            RuntimeDelivery::Steered => UserTurn::Steered,
            _ => UserTurn::Started,
        });
    }
    let Some(pane) = daemon_pane(&session) else {
        let name = session.name.split('@').next().unwrap_or(&session.name);
        return Err(format!(
            "{name} runs outside supercode, where nothing can speak as its user. Open it in a \
             pane with `supercode open {name}`; nothing was sent."
        ));
    };
    mailbox
        .deliver(envelope)
        .map_err(|error| error.to_string())?;
    let typed = type_user_turns(&mailbox, &pane).await;
    Ok(if typed.contains(&envelope.id) {
        UserTurn::Typed
    } else {
        UserTurn::Waiting
    })
}

/// Type the user's waiting turns into `pane`, oldest first, each only when
/// the pane's composer is empty. Stops at the first that has to wait.
/// Returns the ids typed.
pub async fn type_user_turns(mailbox: &Mailbox, pane: &str) -> Vec<String> {
    let mut typed = Vec::new();
    for waiting in mailbox.user_turns().unwrap_or_default() {
        // Claimed before it is typed: the machine's watcher and a direct delivery both type waiting turns, and
        // two typers filling one composer sent a turn's text twice in one prompt. A turn another typer holds is
        // that typer's, and so is every turn after it.
        let Ok(Some(stored)) = mailbox.claim_user_turn(&waiting) else {
            break;
        };
        match submit_when_composer_empty(pane, &stored.envelope.body).await {
            Ok(true) => {
                mailbox.acknowledge(&stored).ok();
                typed.push(stored.envelope.id.clone());
            }
            Ok(false) => {
                mailbox.release(&stored).ok();
                break;
            }
            Err(error) => {
                mailbox.release(&stored).ok();
                eprintln!(
                    "supercode: the user's turn {} for {} waits: {error}",
                    stored.envelope.id,
                    mailbox.address()
                );
                break;
            }
        }
    }
    typed
}

/// The daemon's pane door: type `text` as a submitted turn if the composer
/// is empty now. `Ok(false)` when it holds a draft or is not on screen.
async fn submit_when_composer_empty(pane: &str, text: &str) -> Result<bool, String> {
    let entry = crate::teams_entry().map_err(|error| error.to_string())?;
    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
        .ok()
        .filter(|value| !value.trim().is_empty())
        .unwrap_or_else(|| "node".into());
    let output = tokio::process::Command::new(node)
        .arg(entry)
        .args(["input", pane, text, "--when-composer-empty"])
        .stdin(std::process::Stdio::null())
        .output()
        .await
        .map_err(|error| error.to_string())?;
    if !output.status.success() {
        return Err(crate::mailbox::error_line(&String::from_utf8_lossy(
            &output.stderr,
        )));
    }
    let answer: serde_json::Value =
        serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?;
    Ok(answer["delivered"] == true)
}