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/// Display name of a Codex conversation: `codex-` and the start of its id.
358pub fn codex_name(session_id: &str) -> String {
359    format!("codex-{}", session_id.chars().take(8).collect::<String>())
360}
361
362/// The session a process belongs to: the sender a message is from.
363#[derive(Debug, Clone, PartialEq, Eq)]
364pub struct Caller {
365    /// Its address, where replies go.
366    pub address: MailAddress,
367    /// The name it is known by.
368    pub name: String,
369}
370
371/// Why no session could be found behind a process.
372pub const CALLER_UNRESOLVED: &str = "Can't tell which session is running this command, so \
373    replies would have nowhere to go. Nothing was sent. Run it from your agent session's own \
374    shell tool.";
375
376/// The session behind a process, from its ancestry `pids` (nearest first):
377/// the first that owns a hosted runtime, a Claude session or a Codex
378/// conversation. Never declared by the caller; an environment id only
379/// corroborates, and a mismatch refuses.
380pub fn resolve_caller(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
381    let machine = local_machine_name();
382    let registry = read_registry(&registry_dir(homes));
383    let hosted = crate::runtime_mail::controlled_runtimes();
384    for &pid in pids {
385        if let Some(record) = hosted.iter().find(|record| record.pid == pid) {
386            let short: String = record.source.session_id.chars().take(8).collect();
387            return Ok(Caller {
388                address: MailAddress::new(
389                    &machine,
390                    &record.source.harness,
391                    &record.source.session_id,
392                )
393                .map_err(|error| error.to_string())?,
394                name: format!("{}-{short}@{machine}", record.source.harness),
395            });
396        }
397        if let Some(session) = registry.iter().find(|session| session.pid == pid) {
398            if let Ok(claimed) = std::env::var("CLAUDE_CODE_SESSION_ID") {
399                if !claimed.is_empty() && claimed != session.session_id {
400                    return Err(CALLER_UNRESOLVED.into());
401                }
402            }
403            return Ok(Caller {
404                address: MailAddress::new(&machine, "claude-code", &session.session_id)
405                    .map_err(|error| error.to_string())?,
406                name: format!("{}@{machine}", session.name),
407            });
408        }
409        if let Some((session_id, _)) = crate::codex_peer::session_of_process(pid) {
410            return Ok(Caller {
411                address: MailAddress::new(&machine, "codex", &session_id)
412                    .map_err(|error| error.to_string())?,
413                name: format!("{}@{machine}", codex_name(&session_id)),
414            });
415        }
416    }
417    Err(CALLER_UNRESOLVED.into())
418}
419
420/// This process's ancestry, nearest first (itself included), from `ps`.
421pub fn process_ancestry() -> Vec<u32> {
422    let Ok(output) = std::process::Command::new("ps")
423        .args(["-axo", "pid=,ppid="])
424        .output()
425    else {
426        return vec![std::process::id()];
427    };
428    let parents: std::collections::HashMap<u32, u32> = String::from_utf8_lossy(&output.stdout)
429        .lines()
430        .filter_map(|line| {
431            let mut fields = line.split_whitespace();
432            Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?))
433        })
434        .collect();
435    let mut chain = vec![std::process::id()];
436    let mut current = std::process::id();
437    while let Some(&parent) = parents.get(&current) {
438        if parent <= 1 || chain.contains(&parent) {
439            break;
440        }
441        chain.push(parent);
442        current = parent;
443    }
444    chain
445}
446
447/// Codex's user-level hooks file.
448pub fn codex_hooks_path() -> std::path::PathBuf {
449    std::env::var_os("CODEX_HOME")
450        .map(std::path::PathBuf::from)
451        .or_else(|| {
452            std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".codex"))
453        })
454        .unwrap_or_else(|| std::path::PathBuf::from(".codex"))
455        .join("hooks.json")
456}
457
458/// Whether supercode's mail hook is in Codex's user hooks file. (Codex runs
459/// it only once its user has trusted it.)
460pub fn codex_user_hook_installed() -> bool {
461    std::fs::read_to_string(codex_hooks_path())
462        .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
463}
464
465/// Whether supercode's mail hook is in a project's Codex hooks file, in the
466/// session's directory or one above it.
467pub fn codex_project_hook_installed(cwd: &Path) -> bool {
468    cwd.ancestors().any(|directory| {
469        std::fs::read_to_string(directory.join(".codex").join("hooks.json"))
470            .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
471    })
472}
473
474/// How a delivery ended.
475#[derive(Debug, Clone, PartialEq, Eq)]
476pub enum Delivered {
477    /// The receiver has it now: steered into a running turn.
478    Steered,
479    /// The receiver has it now: it started a turn in an idle session.
480    Started,
481    /// Claude reported it in the receiver's inbox; `busy` says whether the
482    /// receiver reads it at its next tool call (true) or it starts a turn.
483    Native {
484        /// True when the receiver was in a turn.
485        busy: bool,
486    },
487    /// Filed in the receiver's mailbox, which a hook points it at.
488    Hooked,
489    /// Filed in the receiver's mailbox, waiting to be read.
490    Queued,
491    /// Filed with no door to show it.
492    Stored,
493    /// Filed in an operator's mailbox.
494    Operator,
495}
496
497/// A delivery refused before anything was sent.
498#[derive(Debug, Clone, PartialEq, Eq)]
499pub enum Refused {
500    /// `--queue` cannot hold a message for an idle Claude session: Claude
501    /// starts a turn for every message it delivers.
502    CannotQueueNative,
503    /// The relayed text would not fit one relay turn.
504    TooLong(usize),
505}
506
507/// Largest message relayed into a Claude session. The relay copies it into a
508/// model turn byte for byte, so it must fit comfortably in one.
509pub const MAX_RELAYED_BYTES: usize = 100_000;
510
511/// Deliver `envelope` to `to` through `door`. With `wake` false an idle
512/// receiver is not started. With `notify_when_idle` the sender gets one idle
513/// notice after the receiver's next turn ends.
514pub async fn deliver(
515    envelope: &Envelope,
516    to: &MailAddress,
517    door: &Door,
518    wake: bool,
519    notify_when_idle: bool,
520) -> Result<Result<Delivered, Refused>, String> {
521    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
522    // A runtime answers with its turn's final message, which the watcher
523    // sends back: not every runtime can run a command (a hosted agent may
524    // have no shell), and each can end a turn.
525    let mut final_reply = false;
526    let delivered = match door {
527        Door::Runtime(record) => {
528            let mut sent = envelope.clone();
529            let answers = matches!(envelope.reply_via, ReplyVia::Command);
530            if answers {
531                sent.reply_via = ReplyVia::FinalMessage {
532                    destination: envelope.from_name.clone(),
533                };
534            }
535            match deliver_to_runtime(record, sent.render(), wake).await? {
536                RuntimeDelivery::Steered => {
537                    mailbox
538                        .deliver_read(&sent)
539                        .map_err(|error| error.to_string())?;
540                    final_reply = answers;
541                    Delivered::Steered
542                }
543                RuntimeDelivery::Started => {
544                    mailbox
545                        .deliver_read(&sent)
546                        .map_err(|error| error.to_string())?;
547                    final_reply = answers;
548                    Delivered::Started
549                }
550                RuntimeDelivery::NotWoken => {
551                    mailbox
552                        .deliver(envelope)
553                        .map_err(|error| error.to_string())?;
554                    Delivered::Queued
555                }
556            }
557        }
558        Door::Native(session) => {
559            let busy = session.status != Some(ClaudePeerStatus::Idle);
560            if !wake && !busy {
561                return Ok(Err(Refused::CannotQueueNative));
562            }
563            // The same envelope every door delivers; Claude wraps it in its
564            // own, which names the relay.
565            let text = envelope.render();
566            if text.len() > MAX_RELAYED_BYTES {
567                return Ok(Err(Refused::TooLong(text.len())));
568            }
569            match send_through_relay(
570                &envelope.from,
571                &envelope.from_name,
572                &session.name,
573                text,
574                &envelope.id,
575            )
576            .await
577            {
578                RelayReceipt::Delivered { .. } => {
579                    mailbox
580                        .deliver_read(envelope)
581                        .map_err(|error| error.to_string())?;
582                    Delivered::Native { busy }
583                }
584                RelayReceipt::Failed { detail } => return Err(detail),
585            }
586        }
587        Door::Hook => {
588            mailbox
589                .deliver(envelope)
590                .map_err(|error| error.to_string())?;
591            Delivered::Hooked
592        }
593        Door::Stored => {
594            mailbox
595                .deliver(envelope)
596                .map_err(|error| error.to_string())?;
597            Delivered::Stored
598        }
599        Door::Operator => {
600            mailbox
601                .deliver(envelope)
602                .map_err(|error| error.to_string())?;
603            Delivered::Operator
604        }
605    };
606    let notice = notify_when_idle && !matches!(door, Door::Operator);
607    if notice || final_reply {
608        let mut subscription = IdleSubscription::new(envelope.id.clone(), envelope.from.clone());
609        subscription.notice = notice;
610        subscription.final_reply = final_reply;
611        mailbox
612            .subscribe_idle(&subscription)
613            .map_err(|error| error.to_string())?;
614        // The watcher that settles it runs beside the machine daemon.
615        if let Ok(program) = supercode_program() {
616            crate::claude_relay::ensure_machine_daemon(&program)
617                .await
618                .ok();
619        }
620    }
621    Ok(Ok(delivered))
622}
623
624/// How the user's own turn reached its session.
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626pub enum UserTurn {
627    /// A hosted runtime was in a turn; the words were steered into it.
628    Steered,
629    /// A hosted runtime was idle; the words started a turn.
630    Started,
631    /// Typed into the session's pane as its own submitted turn.
632    Typed,
633    /// The pane's composer holds a draft, or its program is not at its
634    /// composer: the turn waits in the session's mailbox and is typed once
635    /// the composer is empty.
636    Waiting,
637}
638
639impl UserTurn {
640    /// Stable wire spelling.
641    pub const fn as_str(self) -> &'static str {
642        match self {
643            Self::Steered => "steered",
644            Self::Started => "started",
645            Self::Typed => "typed",
646            Self::Waiting => "waiting",
647        }
648    }
649}
650
651/// The daemon pane a session runs in, when it runs in one.
652pub fn daemon_pane(session: &LiveSession) -> Option<String> {
653    let name = session.tmux.as_deref()?.split(':').next()?;
654    let rest = name.strip_prefix("p_")?;
655    (!rest.is_empty()
656        && rest
657            .chars()
658            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
659    .then(|| name.to_string())
660}
661
662/// Deliver the user's own turn to `to` through the one door that carries the
663/// user's authority: a hosted runtime's own input, or the session's pane.
664/// A session with neither (running outside supercode) is refused, never
665/// reached as a peer instead. Callers hold the owner's authority already:
666/// this is reached only through owner doors (the machine's own harness.v1).
667pub async fn deliver_user_turn(
668    homes: &HarnessHomes,
669    envelope: &Envelope,
670    to: &MailAddress,
671) -> Result<UserTurn, String> {
672    let session = LiveSessions::read(homes)
673        .sessions
674        .into_iter()
675        .find(|session| &session.address == to)
676        .ok_or_else(|| format!("{to} is not running; nothing was sent"))?;
677    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
678    if let Door::Runtime(record) = &session.door {
679        let delivered = deliver_to_runtime(record, envelope.body.clone(), true).await?;
680        mailbox
681            .deliver_read(envelope)
682            .map_err(|error| error.to_string())?;
683        return Ok(match delivered {
684            RuntimeDelivery::Steered => UserTurn::Steered,
685            _ => UserTurn::Started,
686        });
687    }
688    let Some(pane) = daemon_pane(&session) else {
689        let name = session.name.split('@').next().unwrap_or(&session.name);
690        return Err(format!(
691            "{name} runs outside supercode, where nothing can speak as its user. Open it in a \
692             pane with `supercode open {name}`; nothing was sent."
693        ));
694    };
695    mailbox
696        .deliver(envelope)
697        .map_err(|error| error.to_string())?;
698    let typed = type_user_turns(&mailbox, &pane).await;
699    Ok(if typed.contains(&envelope.id) {
700        UserTurn::Typed
701    } else {
702        UserTurn::Waiting
703    })
704}
705
706/// Type the user's waiting turns into `pane`, oldest first, each only when
707/// the pane's composer is empty. Stops at the first that has to wait.
708/// Returns the ids typed.
709pub async fn type_user_turns(mailbox: &Mailbox, pane: &str) -> Vec<String> {
710    let mut typed = Vec::new();
711    for stored in mailbox.user_turns().unwrap_or_default() {
712        match submit_when_composer_empty(pane, &stored.envelope.body).await {
713            Ok(true) => {
714                mailbox.mark_read(&stored).ok();
715                typed.push(stored.envelope.id.clone());
716            }
717            Ok(false) => break,
718            Err(error) => {
719                eprintln!(
720                    "supercode: the user's turn {} for {} waits: {error}",
721                    stored.envelope.id,
722                    mailbox.address()
723                );
724                break;
725            }
726        }
727    }
728    typed
729}
730
731/// The daemon's pane door: type `text` as a submitted turn if the composer
732/// is empty now. `Ok(false)` when it holds a draft or is not on screen.
733async fn submit_when_composer_empty(pane: &str, text: &str) -> Result<bool, String> {
734    let entry = crate::teams_entry().map_err(|error| error.to_string())?;
735    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
736        .ok()
737        .filter(|value| !value.trim().is_empty())
738        .unwrap_or_else(|| "node".into());
739    let output = tokio::process::Command::new(node)
740        .arg(entry)
741        .args(["input", pane, text, "--when-composer-empty"])
742        .stdin(std::process::Stdio::null())
743        .output()
744        .await
745        .map_err(|error| error.to_string())?;
746    if !output.status.success() {
747        return Err(crate::mailbox::error_line(&String::from_utf8_lossy(
748            &output.stderr,
749        )));
750    }
751    let answer: serde_json::Value =
752        serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?;
753    Ok(answer["delivered"] == true)
754}