Skip to main content

supercode_harness/
mail_route.rs

1//! One route for every message: which door reaches a receiver, and delivery
2//! through it.
3//!
4//! Every caller that delivers mail — `supercode message send`,
5//! `harness.v1.sessions.message`, and idle notices — goes through
6//! [`door_for`] and [`deliver`], so the choice of door is made in one place.
7//! The doors, best first:
8//!
9//! 1. **runtime** — a session supercode controls (a hosted runtime of any
10//!    harness): its own `steer`/`send_input` ([`crate::runtime_mail`]). This
11//!    is the default tier.
12//! 2. **native** — a Claude Code session supercode does not control: a Claude
13//!    relay sends with Claude's own `SendMessage` ([`crate::claude_relay`]).
14//! 3. **hook** — a Codex session supercode does not control, with
15//!    supercode's hooks in its hooks file: filed in its mailbox, and the hook
16//!    points the session at it.
17//! 4. **stored** — no door: filed in its mailbox, seen only when the session
18//!    reads it.
19//!
20//! Tiers 2–4 are the degradation tier, for sessions supercode does not
21//! control. An operator (a board, a script) is not a session: its mail is
22//! filed in its mailbox and read with `sessions.inbox`.
23
24use std::path::Path;
25
26use crate::claude_peer::{read_registry, registry_dir, ClaudePeerSession, ClaudePeerStatus};
27use crate::claude_relay::{send_through_relay, supercode_program, RelayReceipt, RELAY_NAME_PREFIX};
28use crate::live_runtime::LiveRuntimeRecord;
29use crate::mailbox::{
30    local_machine_name, mail_root, Envelope, IdleSubscription, MailAddress, Mailbox, ReplyVia,
31};
32use crate::runtime_mail::{deliver_to_runtime, RuntimeDelivery};
33use crate::HarnessHomes;
34
35/// Arguments a Codex hook entry carries, which is how its presence is found.
36pub const CODEX_HOOK_ARGUMENTS: &str = "message hook codex";
37
38/// The door that reaches one receiver.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Door {
41    /// A session supercode controls.
42    Runtime(Box<LiveRuntimeRecord>),
43    /// A Claude Code session supercode does not control.
44    Native(Box<ClaudePeerSession>),
45    /// A Codex session supercode does not control, with supercode's hooks.
46    Hook,
47    /// A running session with no door.
48    Stored,
49    /// An operator's mailbox.
50    Operator,
51}
52
53impl Door {
54    /// Stable name of the door, as `message list` and receipts show it.
55    pub fn name(&self) -> &'static str {
56        match self {
57            Self::Runtime(_) => "runtime",
58            Self::Native(_) => "native",
59            Self::Hook => "hook",
60            Self::Stored => "stored",
61            Self::Operator => "operator",
62        }
63    }
64}
65
66/// Why no door reaches an address on this machine.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub enum NoDoor {
69    /// The address names another machine.
70    OtherMachine(String),
71    /// No running session has that address.
72    NotRunning,
73}
74
75/// The door that reaches `to` on this machine.
76pub fn door_for(homes: &HarnessHomes, to: &MailAddress) -> Result<Door, NoDoor> {
77    if to.machine != local_machine_name() {
78        return Err(NoDoor::OtherMachine(to.machine.clone()));
79    }
80    if to.harness == "operator" {
81        return Ok(Door::Operator);
82    }
83    LiveSessions::read(homes)
84        .sessions
85        .into_iter()
86        .find(|session| &session.address == to)
87        .map(|session| session.door)
88        .ok_or(NoDoor::NotRunning)
89}
90
91/// One running session on this machine, as the router reaches it.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct LiveSession {
94    /// Its address.
95    pub address: MailAddress,
96    /// The name an agent knows it by (`volter-2c@machine`).
97    pub name: String,
98    /// Its status as its harness reports it (`busy`, `idle`, `hosted`, …).
99    pub status: String,
100    /// The door that reaches it.
101    pub door: Door,
102    /// The process running it, when the harness names one (a hosted
103    /// runtime's host, a Claude session's own process).
104    pub pid: Option<u32>,
105    /// Its working directory.
106    pub cwd: Option<std::path::PathBuf>,
107    /// The tmux session and pane it runs in, when Claude records one.
108    pub tmux: Option<String>,
109}
110
111/// Every running session on this machine with its door, read once: what
112/// `message list` shows, what names resolve against, and what discovery
113/// projects onto each discovered session as `delivery`.
114#[derive(Debug, Default)]
115pub struct LiveSessions {
116    sessions: Vec<LiveSession>,
117}
118
119/// Why a receiver named by an agent was not found.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub enum Unresolved {
122    /// The address names a session that is not running.
123    Stale(String),
124    /// No running session has that name (the text suggests near names).
125    Unknown(String),
126}
127
128impl LiveSessions {
129    /// Read every running session now. Sessions supercode controls come
130    /// first, and a degraded-tier row for the same session is dropped: the
131    /// runtime is the default tier.
132    pub fn read(homes: &HarnessHomes) -> Self {
133        let machine = local_machine_name();
134        let registry = read_registry(&registry_dir(homes));
135        // A hosted Claude session is also in Claude's registry, which knows
136        // its name; a relay is not a session and is not listed.
137        let registered = |record: &crate::live_runtime::LiveRuntimeRecord| {
138            registry.iter().find(|session| {
139                session.session_id == record.source.session_id
140                    || session.session_id == record.runtime_session_id
141            })
142        };
143        let mut sessions: Vec<LiveSession> = crate::runtime_mail::controlled_runtimes()
144            .into_iter()
145            .filter_map(|record| {
146                let registered = registered(&record);
147                if registered.is_some_and(|session| session.name.starts_with(RELAY_NAME_PREFIX)) {
148                    return None;
149                }
150                let address =
151                    MailAddress::new(&machine, &record.source.harness, &record.source.session_id)
152                        .ok()?;
153                let short: String = record.source.session_id.chars().take(8).collect();
154                let name = match registered {
155                    Some(session) if !session.name.is_empty() => session.name.clone(),
156                    _ => format!("{}-{short}", record.source.harness),
157                };
158                Some(LiveSession {
159                    name: format!("{name}@{machine}"),
160                    address,
161                    status: "hosted".into(),
162                    pid: Some(record.pid),
163                    cwd: Some(record.source.workspace.clone()),
164                    tmux: None,
165                    door: Door::Runtime(Box::new(record)),
166                })
167            })
168            .collect();
169        let controlled = |address: &MailAddress, sessions: &[LiveSession]| {
170            sessions.iter().any(|session| &session.address == address)
171        };
172        for session in registry {
173            if session.name.starts_with(RELAY_NAME_PREFIX) {
174                continue;
175            }
176            let Ok(address) = MailAddress::new(&machine, "claude-code", &session.session_id) else {
177                continue;
178            };
179            if controlled(&address, &sessions) {
180                continue;
181            }
182            sessions.push(LiveSession {
183                address,
184                name: format!("{}@{machine}", session.name),
185                status: session
186                    .status
187                    .as_ref()
188                    .map(|status| status.as_str().to_string())
189                    .unwrap_or_else(|| "unknown".into()),
190                pid: Some(session.pid),
191                cwd: session.cwd.clone(),
192                tmux: session.tmux.clone(),
193                door: Door::Native(Box::new(session)),
194            });
195        }
196        let user_hook = codex_user_hook_installed();
197        for (path, status) in crate::codex_peer::live_rollouts(&homes.codex) {
198            let Some((session_id, None)) = crate::codex_peer::rollout_session(&path) else {
199                continue;
200            };
201            let Ok(address) = MailAddress::new(&machine, "codex", &session_id) else {
202                continue;
203            };
204            if controlled(&address, &sessions) {
205                continue;
206            }
207            let cwd = crate::codex_peer::rollout_cwd(&path);
208            let hooked = user_hook || cwd.as_deref().is_some_and(codex_project_hook_installed);
209            sessions.push(LiveSession {
210                name: format!("{}@{machine}", codex_name(&session_id)),
211                address,
212                status: status.as_str().to_string(),
213                pid: None,
214                cwd,
215                tmux: None,
216                door: if hooked { Door::Hook } else { Door::Stored },
217            });
218        }
219        Self { sessions }
220    }
221
222    /// Every running session.
223    pub fn all(&self) -> &[LiveSession] {
224        &self.sessions
225    }
226
227    /// The door that reaches `harness`'s session `session_id`, when it is
228    /// running.
229    pub fn door(&self, harness: &str, session_id: &str) -> Option<&'static str> {
230        self.sessions
231            .iter()
232            .find(|session| {
233                session.address.harness == harness && session.address.session_id == session_id
234            })
235            .map(|session| session.door.name())
236    }
237
238    /// The running session an agent means by `to`: an address, `name@machine`
239    /// on this machine, or a name unique here.
240    pub fn resolve(&self, to: &str) -> Result<&LiveSession, Unresolved> {
241        let machine = local_machine_name();
242        if let Ok(address) = MailAddress::parse(to) {
243            return self
244                .sessions
245                .iter()
246                .find(|session| session.address == address)
247                .ok_or_else(|| {
248                    Unresolved::Stale(format!(
249                        "{to} is no longer running. Nothing was sent. Run supercode message list \
250                         for the live sessions."
251                    ))
252                });
253        }
254        let wanted = match to.split_once('@') {
255            Some((name, at)) if at == machine => name.to_string(),
256            Some((_, at)) => {
257                return Err(Unresolved::Unknown(format!(
258                    "Not sent: {to} is on machine {at}, not this one. Nothing was sent."
259                )))
260            }
261            None => to.to_string(),
262        };
263        let short = |session: &LiveSession| {
264            session
265                .name
266                .split('@')
267                .next()
268                .unwrap_or_default()
269                .to_string()
270        };
271        let matching: Vec<&LiveSession> = self
272            .sessions
273            .iter()
274            .filter(|session| short(session) == wanted)
275            .collect();
276        if let [only] = matching.as_slice() {
277            return Ok(only);
278        }
279        let hint = if matching.len() > 1 {
280            format!(
281                " {} sessions are named {wanted}; use its address.",
282                matching.len()
283            )
284        } else {
285            let near: Vec<String> = self
286                .sessions
287                .iter()
288                .filter(|session| {
289                    let name = short(session);
290                    name.contains(&wanted)
291                        || wanted.contains(&name)
292                        || name
293                            .chars()
294                            .zip(wanted.chars())
295                            .take_while(|(a, b)| a == b)
296                            .count()
297                            >= 4
298                })
299                .take(3)
300                .map(|session| {
301                    format!(
302                        "{} ({}, {})",
303                        session.name, session.address.harness, session.status
304                    )
305                })
306                .collect();
307            if near.is_empty() {
308                String::new()
309            } else {
310                format!(" Did you mean: {}?", near.join(", "))
311            }
312        };
313        Err(Unresolved::Unknown(format!(
314            "No session named \"{wanted}\" is reachable.{hint} Run supercode message list. Nothing \
315             was sent."
316        )))
317    }
318
319    /// An index holding exactly `entries` (harness, session id, door).
320    #[cfg(test)]
321    pub(crate) fn with(entries: &[(&str, &str, &'static str)]) -> Self {
322        Self {
323            sessions: entries
324                .iter()
325                .filter_map(|(harness, id, door)| {
326                    let door = match *door {
327                        "native" => Door::Native(Box::new(ClaudePeerSession {
328                            pid: 0,
329                            session_id: id.to_string(),
330                            cwd: None,
331                            name: id.to_string(),
332                            socket_path: Default::default(),
333                            status: None,
334                            updated_at_ms: None,
335                            version: None,
336                            tmux: None,
337                        })),
338                        "hook" => Door::Hook,
339                        "stored" => Door::Stored,
340                        other => panic!("no test door {other}"),
341                    };
342                    Some(LiveSession {
343                        address: MailAddress::new("test", *harness, *id).ok()?,
344                        name: format!("{id}@test"),
345                        status: "unknown".into(),
346                        pid: None,
347                        cwd: None,
348                        tmux: None,
349                        door,
350                    })
351                })
352                .collect(),
353        }
354    }
355}
356
357/// Whether the session process `pid` has supercode's messaging tools: a
358/// harness starts each MCP server as a child of the session, so the tools are
359/// loaded exactly when a live `supercode message mcp` is one of its children.
360pub fn has_message_tools(pid: u32) -> bool {
361    let Ok(output) = std::process::Command::new("ps")
362        .args(["-A", "-o", "ppid=,command="])
363        .output()
364    else {
365        return false;
366    };
367    String::from_utf8_lossy(&output.stdout).lines().any(|line| {
368        let line = line.trim_start();
369        let Some((ppid, command)) = line.split_once(' ') else {
370            return false;
371        };
372        ppid.parse::<u32>() == Ok(pid) && command.trim_end().ends_with(" message mcp")
373    })
374}
375
376/// Display name of a Codex conversation: `codex-` and the start of its id.
377pub fn codex_name(session_id: &str) -> String {
378    format!("codex-{}", session_id.chars().take(8).collect::<String>())
379}
380
381/// The session a process belongs to: the sender a message is from.
382#[derive(Debug, Clone, PartialEq, Eq)]
383pub struct Caller {
384    /// Its address, where replies go.
385    pub address: MailAddress,
386    /// The name it is known by.
387    pub name: String,
388}
389
390/// Why no session could be found behind a process.
391pub const CALLER_UNRESOLVED: &str = "Can't tell which session is running this command, so \
392    replies would have nowhere to go. Nothing was sent. Run it from your agent session's own \
393    shell tool.";
394
395/// The session behind a process, from its ancestry `pids` (nearest first):
396/// the first that owns a hosted runtime, a Claude session or a Codex
397/// conversation. Never declared by the caller; an environment id only
398/// corroborates, and a mismatch refuses.
399pub fn resolve_caller(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
400    let machine = local_machine_name();
401    let registry = read_registry(&registry_dir(homes));
402    let hosted = crate::runtime_mail::controlled_runtimes();
403    for &pid in pids {
404        if let Some(record) = hosted.iter().find(|record| record.pid == pid) {
405            let short: String = record.source.session_id.chars().take(8).collect();
406            return Ok(Caller {
407                address: MailAddress::new(
408                    &machine,
409                    &record.source.harness,
410                    &record.source.session_id,
411                )
412                .map_err(|error| error.to_string())?,
413                name: format!("{}-{short}@{machine}", record.source.harness),
414            });
415        }
416        if let Some(session) = registry.iter().find(|session| session.pid == pid) {
417            if let Ok(claimed) = std::env::var("CLAUDE_CODE_SESSION_ID") {
418                if !claimed.is_empty() && claimed != session.session_id {
419                    return Err(CALLER_UNRESOLVED.into());
420                }
421            }
422            return Ok(Caller {
423                address: MailAddress::new(&machine, "claude-code", &session.session_id)
424                    .map_err(|error| error.to_string())?,
425                name: format!("{}@{machine}", session.name),
426            });
427        }
428        // Codex names the thread a command runs for (`CODEX_THREAD_ID`); the
429        // claim stands when this process holds that thread's rollout, as
430        // Codex's shared app-server daemon does for every thread it runs.
431        if let Some(thread) = std::env::var("CODEX_THREAD_ID")
432            .ok()
433            .filter(|thread| !thread.is_empty())
434            .filter(|thread| crate::codex_peer::holds_session(pid, thread))
435        {
436            return Ok(Caller {
437                address: MailAddress::new(&machine, "codex", &thread)
438                    .map_err(|error| error.to_string())?,
439                name: format!("{}@{machine}", codex_name(&thread)),
440            });
441        }
442        if let Some((session_id, _)) = crate::codex_peer::session_of_process(pid) {
443            return Ok(Caller {
444                address: MailAddress::new(&machine, "codex", &session_id)
445                    .map_err(|error| error.to_string())?,
446                name: format!("{}@{machine}", codex_name(&session_id)),
447            });
448        }
449    }
450    Err(CALLER_UNRESOLVED.into())
451}
452
453/// This process's ancestry, nearest first (itself included).
454pub fn process_ancestry() -> Vec<u32> {
455    let parents = parent_pids();
456    let mut chain = vec![std::process::id()];
457    let mut current = std::process::id();
458    while let Some(&parent) = parents.get(&current) {
459        if parent <= 1 || chain.contains(&parent) {
460            break;
461        }
462        chain.push(parent);
463        current = parent;
464    }
465    chain
466}
467
468/// Every process's parent: pid → parent pid, from `ps`.
469#[cfg(not(windows))]
470fn parent_pids() -> std::collections::HashMap<u32, u32> {
471    let Ok(output) = std::process::Command::new("ps")
472        .args(["-axo", "pid=,ppid="])
473        .output()
474    else {
475        return Default::default();
476    };
477    String::from_utf8_lossy(&output.stdout)
478        .lines()
479        .filter_map(|line| {
480            let mut fields = line.split_whitespace();
481            Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?))
482        })
483        .collect()
484}
485
486/// Every process's parent: pid → parent pid, from a process snapshot.
487#[cfg(windows)]
488fn parent_pids() -> std::collections::HashMap<u32, u32> {
489    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
490    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
491        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
492        TH32CS_SNAPPROCESS,
493    };
494
495    let mut parents = std::collections::HashMap::new();
496    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
497    if snapshot == INVALID_HANDLE_VALUE {
498        return parents;
499    }
500    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
501    entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
502    let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
503    while has_entry {
504        parents.insert(entry.th32ProcessID, entry.th32ParentProcessID);
505        has_entry = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
506    }
507    unsafe {
508        CloseHandle(snapshot);
509    }
510    parents
511}
512
513/// Codex's user-level hooks file.
514pub fn codex_hooks_path() -> std::path::PathBuf {
515    std::env::var_os("CODEX_HOME")
516        .map(std::path::PathBuf::from)
517        .or_else(|| {
518            supercode_interchange::user_home()
519                .map(std::path::PathBuf::into_os_string)
520                .map(|home| std::path::PathBuf::from(home).join(".codex"))
521        })
522        .unwrap_or_else(|| std::path::PathBuf::from(".codex"))
523        .join("hooks.json")
524}
525
526/// Whether supercode's mail hook is in Codex's user hooks file. (Codex runs
527/// it only once its user has trusted it.)
528pub fn codex_user_hook_installed() -> bool {
529    std::fs::read_to_string(codex_hooks_path())
530        .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
531}
532
533/// Whether supercode's mail hook is in a project's Codex hooks file, in the
534/// session's directory or one above it.
535pub fn codex_project_hook_installed(cwd: &Path) -> bool {
536    cwd.ancestors().any(|directory| {
537        std::fs::read_to_string(directory.join(".codex").join("hooks.json"))
538            .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
539    })
540}
541
542/// How a delivery ended.
543#[derive(Debug, Clone, PartialEq, Eq)]
544pub enum Delivered {
545    /// The receiver has it now: steered into a running turn.
546    Steered,
547    /// The receiver has it now: it started a turn in an idle session.
548    Started,
549    /// Claude reported it in the receiver's inbox; `busy` says whether the
550    /// receiver reads it at its next tool call (true) or it starts a turn.
551    Native {
552        /// True when the receiver was in a turn.
553        busy: bool,
554    },
555    /// Filed in the receiver's mailbox, which a hook points it at.
556    Hooked,
557    /// Filed in the receiver's mailbox, waiting to be read.
558    Queued,
559    /// Filed with no door to show it.
560    Stored,
561    /// Filed in an operator's mailbox.
562    Operator,
563}
564
565/// A delivery refused before anything was sent.
566#[derive(Debug, Clone, PartialEq, Eq)]
567pub enum Refused {
568    /// `--queue` cannot hold a message for an idle Claude session: Claude
569    /// starts a turn for every message it delivers.
570    CannotQueueNative,
571    /// The relayed text would not fit one relay turn.
572    TooLong(usize),
573}
574
575/// Largest message relayed into a Claude session. The relay copies it into a
576/// model turn byte for byte, so it must fit comfortably in one.
577pub const MAX_RELAYED_BYTES: usize = 100_000;
578
579/// Deliver `envelope` to `to` through `door`. With `wake` false an idle
580/// receiver is not started. With `notify_when_idle` the sender gets one idle
581/// notice after the receiver's next turn ends.
582pub async fn deliver(
583    envelope: &Envelope,
584    to: &MailAddress,
585    door: &Door,
586    wake: bool,
587    notify_when_idle: bool,
588) -> Result<Result<Delivered, Refused>, String> {
589    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
590    // A runtime answers with its turn's final message, which the watcher
591    // sends back: not every runtime can run a command (a hosted agent may
592    // have no shell), and each can end a turn.
593    let mut final_reply = false;
594    let delivered = match door {
595        Door::Runtime(record) => {
596            let mut sent = envelope.clone();
597            let answers = matches!(envelope.reply_via, ReplyVia::Command);
598            if answers {
599                sent.reply_via = ReplyVia::FinalMessage {
600                    destination: envelope.from_name.clone(),
601                };
602            }
603            match deliver_to_runtime(record, sent.render(), wake).await? {
604                RuntimeDelivery::Steered => {
605                    mailbox
606                        .deliver_read(&sent)
607                        .map_err(|error| error.to_string())?;
608                    final_reply = answers;
609                    Delivered::Steered
610                }
611                RuntimeDelivery::Started => {
612                    mailbox
613                        .deliver_read(&sent)
614                        .map_err(|error| error.to_string())?;
615                    final_reply = answers;
616                    Delivered::Started
617                }
618                RuntimeDelivery::NotWoken => {
619                    mailbox
620                        .deliver(envelope)
621                        .map_err(|error| error.to_string())?;
622                    Delivered::Queued
623                }
624            }
625        }
626        Door::Native(session) => {
627            let busy = session.status != Some(ClaudePeerStatus::Idle);
628            if !wake && !busy {
629                return Ok(Err(Refused::CannotQueueNative));
630            }
631            // The same envelope every door delivers; Claude wraps it in its
632            // own, which names the relay. Its reply line names the door this
633            // session really has: its tools when it runs supercode's MCP server.
634            let mut envelope = envelope.clone();
635            if envelope.reply_via == ReplyVia::Command && has_message_tools(session.pid) {
636                envelope.reply_via = ReplyVia::Tool;
637            }
638            let envelope = &envelope;
639            let text = envelope.render();
640            if text.len() > MAX_RELAYED_BYTES {
641                return Ok(Err(Refused::TooLong(text.len())));
642            }
643            match send_through_relay(
644                &envelope.from,
645                &envelope.from_name,
646                &session.name,
647                text,
648                &envelope.id,
649            )
650            .await
651            {
652                RelayReceipt::Delivered { .. } => {
653                    mailbox
654                        .deliver_read(envelope)
655                        .map_err(|error| error.to_string())?;
656                    Delivered::Native { busy }
657                }
658                RelayReceipt::Failed { detail } => return Err(detail),
659            }
660        }
661        Door::Hook => {
662            mailbox
663                .deliver(envelope)
664                .map_err(|error| error.to_string())?;
665            Delivered::Hooked
666        }
667        Door::Stored => {
668            mailbox
669                .deliver(envelope)
670                .map_err(|error| error.to_string())?;
671            Delivered::Stored
672        }
673        Door::Operator => {
674            mailbox
675                .deliver(envelope)
676                .map_err(|error| error.to_string())?;
677            Delivered::Operator
678        }
679    };
680    let notice = notify_when_idle && !matches!(door, Door::Operator);
681    if notice || final_reply {
682        let mut subscription = IdleSubscription::new(envelope.id.clone(), envelope.from.clone());
683        subscription.notice = notice;
684        subscription.final_reply = final_reply;
685        mailbox
686            .subscribe_idle(&subscription)
687            .map_err(|error| error.to_string())?;
688        // The watcher that settles it runs beside the machine daemon.
689        if let Ok(program) = supercode_program() {
690            crate::claude_relay::ensure_machine_daemon(&program)
691                .await
692                .ok();
693        }
694    }
695    Ok(Ok(delivered))
696}
697
698/// How the user's own turn reached its session.
699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
700pub enum UserTurn {
701    /// A hosted runtime was in a turn; the words were steered into it.
702    Steered,
703    /// A hosted runtime was idle; the words started a turn.
704    Started,
705    /// Typed into the session's pane as its own submitted turn.
706    Typed,
707    /// The pane's composer holds a draft, or its program is not at its
708    /// composer: the turn waits in the session's mailbox and is typed once
709    /// the composer is empty.
710    Waiting,
711}
712
713impl UserTurn {
714    /// Stable wire spelling.
715    pub const fn as_str(self) -> &'static str {
716        match self {
717            Self::Steered => "steered",
718            Self::Started => "started",
719            Self::Typed => "typed",
720            Self::Waiting => "waiting",
721        }
722    }
723}
724
725/// The daemon pane a session runs in, when it runs in one.
726pub fn daemon_pane(session: &LiveSession) -> Option<String> {
727    let name = session.tmux.as_deref()?.split(':').next()?;
728    let rest = name.strip_prefix("p_")?;
729    (!rest.is_empty()
730        && rest
731            .chars()
732            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
733    .then(|| name.to_string())
734}
735
736/// Deliver the user's own turn to `to` through the one door that carries the
737/// user's authority: a hosted runtime's own input, or the session's pane.
738/// A session with neither (running outside supercode) is refused, never
739/// reached as a peer instead. Callers hold the owner's authority already:
740/// this is reached only through owner doors (the machine's own harness.v1).
741pub async fn deliver_user_turn(
742    homes: &HarnessHomes,
743    envelope: &Envelope,
744    to: &MailAddress,
745) -> Result<UserTurn, String> {
746    let session = LiveSessions::read(homes)
747        .sessions
748        .into_iter()
749        .find(|session| &session.address == to)
750        .ok_or_else(|| format!("{to} is not running; nothing was sent"))?;
751    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
752    if let Door::Runtime(record) = &session.door {
753        let delivered = deliver_to_runtime(record, envelope.body.clone(), true).await?;
754        mailbox
755            .deliver_read(envelope)
756            .map_err(|error| error.to_string())?;
757        return Ok(match delivered {
758            RuntimeDelivery::Steered => UserTurn::Steered,
759            _ => UserTurn::Started,
760        });
761    }
762    let Some(pane) = daemon_pane(&session) else {
763        let name = session.name.split('@').next().unwrap_or(&session.name);
764        return Err(format!(
765            "{name} runs outside supercode, where nothing can speak as its user. Open it in a \
766             pane with `supercode open {name}`; nothing was sent."
767        ));
768    };
769    mailbox
770        .deliver(envelope)
771        .map_err(|error| error.to_string())?;
772    let typed = type_user_turns(&mailbox, &pane).await;
773    Ok(if typed.contains(&envelope.id) {
774        UserTurn::Typed
775    } else {
776        UserTurn::Waiting
777    })
778}
779
780/// Type the user's waiting turns into `pane`, oldest first, each only when
781/// the pane's composer is empty. Stops at the first that has to wait.
782/// Returns the ids typed.
783pub async fn type_user_turns(mailbox: &Mailbox, pane: &str) -> Vec<String> {
784    let mut typed = Vec::new();
785    for stored in mailbox.user_turns().unwrap_or_default() {
786        match submit_when_composer_empty(pane, &stored.envelope.body).await {
787            Ok(true) => {
788                mailbox.mark_read(&stored).ok();
789                typed.push(stored.envelope.id.clone());
790            }
791            Ok(false) => break,
792            Err(error) => {
793                eprintln!(
794                    "supercode: the user's turn {} for {} waits: {error}",
795                    stored.envelope.id,
796                    mailbox.address()
797                );
798                break;
799            }
800        }
801    }
802    typed
803}
804
805/// The daemon's pane door: type `text` as a submitted turn if the composer
806/// is empty now. `Ok(false)` when it holds a draft or is not on screen.
807async fn submit_when_composer_empty(pane: &str, text: &str) -> Result<bool, String> {
808    let entry = crate::teams_entry().map_err(|error| error.to_string())?;
809    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
810        .ok()
811        .filter(|value| !value.trim().is_empty())
812        .unwrap_or_else(|| "node".into());
813    let output = tokio::process::Command::new(node)
814        .arg(entry)
815        .args(["input", pane, text, "--when-composer-empty"])
816        .stdin(std::process::Stdio::null())
817        .output()
818        .await
819        .map_err(|error| error.to_string())?;
820    if !output.status.success() {
821        return Err(crate::mailbox::error_line(&String::from_utf8_lossy(
822            &output.stderr,
823        )));
824    }
825    let answer: serde_json::Value =
826        serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?;
827    Ok(answer["delivered"] == true)
828}