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    /// they show it its mailbox at its next tool call or when its turn ends.
47    /// An idle one in a daemon pane is woken through its pane.
48    Hook {
49        /// The daemon pane it runs in.
50        pane: Option<String>,
51        /// Whether its last turn has ended.
52        idle: bool,
53    },
54    /// A running session with no door.
55    Stored,
56    /// An operator's mailbox.
57    Operator,
58}
59
60impl Door {
61    /// Stable name of the door, as `message list` and receipts show it.
62    pub fn name(&self) -> &'static str {
63        match self {
64            Self::Runtime(_) => "runtime",
65            Self::Native(_) => "native",
66            Self::Hook { .. } => "hook",
67            Self::Stored => "stored",
68            Self::Operator => "operator",
69        }
70    }
71}
72
73/// Why no door reaches an address on this machine.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum NoDoor {
76    /// The address names another machine.
77    OtherMachine(String),
78    /// No running session has that address.
79    NotRunning,
80}
81
82/// The door that reaches `to` on this machine.
83pub fn door_for(homes: &HarnessHomes, to: &MailAddress) -> Result<Door, NoDoor> {
84    if to.machine != local_machine_name() {
85        return Err(NoDoor::OtherMachine(to.machine.clone()));
86    }
87    if to.harness == "operator" || to.harness == "board" {
88        return Ok(Door::Operator);
89    }
90    LiveSessions::read(homes)
91        .sessions
92        .into_iter()
93        .find(|session| &session.address == to)
94        .map(|session| session.door)
95        .ok_or(NoDoor::NotRunning)
96}
97
98/// One running session on this machine, as the router reaches it.
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct LiveSession {
101    /// Its address.
102    pub address: MailAddress,
103    /// The name an agent knows it by (`volter-2c@machine`).
104    pub name: String,
105    /// Its status as its harness reports it (`busy`, `idle`, `hosted`, …).
106    pub status: String,
107    /// The door that reaches it.
108    pub door: Door,
109    /// The process running it, when the harness names one (a hosted
110    /// runtime's host, a Claude session's own process).
111    pub pid: Option<u32>,
112    /// Its working directory.
113    pub cwd: Option<std::path::PathBuf>,
114    /// The tmux session and pane it runs in, when Claude records one.
115    pub tmux: Option<String>,
116    /// Its transcript, when the harness names the file (a Codex rollout).
117    pub transcript: Option<std::path::PathBuf>,
118}
119
120impl LiveSession {
121    /// When its transcript last recorded a message (a prompt, a reply, a tool
122    /// call or result), in epoch milliseconds: what the session last did,
123    /// read from the harness's own records. A queued or injected notice is
124    /// not a message, so this is not the transcript's mtime.
125    pub fn last_message_at_ms(&self, homes: &HarnessHomes) -> Option<u64> {
126        let harness = self.address.harness.as_str();
127        let path = match &self.transcript {
128            Some(path) => path.clone(),
129            None if harness == "claude-code" => {
130                let file = format!("{}.jsonl", self.address.session_id);
131                std::fs::read_dir(&homes.claude_code)
132                    .ok()?
133                    .flatten()
134                    .map(|project| project.path().join(&file))
135                    .find(|path| path.is_file())?
136            }
137            None => return None,
138        };
139        last_message_at_ms(&path, harness)
140    }
141}
142
143impl LiveSession {
144    /// What a session waiting on its user is asking, read from its transcript: the newest tool call with no result
145    /// yet. An `AskUserQuestion` gives its questions, headers and option labels; any other tool its name and a
146    /// shortened input. `None` when the session is not waiting or its transcript shows nothing pending.
147    pub fn pending_request(&self, homes: &HarnessHomes) -> Option<serde_json::Value> {
148        if self.status != "waiting" {
149            return None;
150        }
151        // A Codex prompt writes nothing to its rollout: what it asks is read off its pane.
152        if self.address.harness == "codex" {
153            let prompt = daemon_pane(self).and_then(|pane| pane_prompt(&pane))?;
154            return Some(serde_json::json!({"prompt": prompt, "source": "screen"}));
155        }
156        if self.address.harness != "claude-code" {
157            return None;
158        }
159        let file = format!("{}.jsonl", self.address.session_id);
160        let from_transcript = std::fs::read_dir(&homes.claude_code)
161            .ok()
162            .and_then(|projects| {
163                projects
164                    .flatten()
165                    .map(|project| project.path().join(&file))
166                    .find(|path| path.is_file())
167            })
168            .and_then(|path| pending_request(&path));
169        // Claude Code writes a question's tool call to its transcript only once it is answered
170        // (2.1.280): until then, what it asks is on its pane.
171        from_transcript.or_else(|| {
172            let prompt = daemon_pane(self).and_then(|pane| pane_prompt(&pane))?;
173            Some(serde_json::json!({"prompt": prompt, "source": "screen"}))
174        })
175    }
176}
177
178/// The newest tool call in a Claude transcript that has no result yet, as [`LiveSession::pending_request`] shows it.
179pub fn pending_request(path: &Path) -> Option<serde_json::Value> {
180    use std::io::{Read, Seek, SeekFrom};
181    let mut file = std::fs::File::open(path).ok()?;
182    let length = file.metadata().ok()?.len();
183    let start = length.saturating_sub(512 * 1024);
184    file.seek(SeekFrom::Start(start)).ok()?;
185    let mut bytes = Vec::new();
186    file.read_to_end(&mut bytes).ok()?;
187    let text = String::from_utf8_lossy(&bytes);
188    let mut answered = std::collections::HashSet::new();
189    for line in text.lines().rev() {
190        let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {
191            continue;
192        };
193        if record["isSidechain"] == true {
194            continue;
195        }
196        let Some(content) = record
197            .pointer("/message/content")
198            .and_then(serde_json::Value::as_array)
199        else {
200            continue;
201        };
202        match record["type"].as_str() {
203            Some("user") => {
204                for item in content.iter().filter(|item| item["type"] == "tool_result") {
205                    if let Some(id) = item["tool_use_id"].as_str() {
206                        answered.insert(id.to_string());
207                    }
208                }
209            }
210            Some("assistant") => {
211                let Some(call) = content.iter().rev().find(|item| item["type"] == "tool_use")
212                else {
213                    continue;
214                };
215                if call["id"].as_str().is_some_and(|id| answered.contains(id)) {
216                    return None;
217                }
218                let tool = call["name"].as_str().unwrap_or_default();
219                if tool == "AskUserQuestion" {
220                    let questions = call["input"]["questions"]
221                        .as_array()
222                        .map(|questions| {
223                            questions
224                                .iter()
225                                .map(|question| {
226                                    serde_json::json!({
227                                        "question": question["question"],
228                                        "header": question["header"],
229                                        "options": question["options"].as_array().map(|options| options.iter().map(|option| option["label"].clone()).collect::<Vec<_>>()).unwrap_or_default(),
230                                    })
231                                })
232                                .collect::<Vec<_>>()
233                        })
234                        .unwrap_or_default();
235                    return Some(serde_json::json!({"tool": tool, "questions": questions}));
236                }
237                let input = call["input"].to_string();
238                let input: String = input.chars().take(500).collect();
239                return Some(serde_json::json!({"tool": tool, "input": input}));
240            }
241            _ => {}
242        }
243    }
244    None
245}
246
247/// The newest message record's timestamp in a Claude or Codex transcript.
248fn last_message_at_ms(path: &Path, harness: &str) -> Option<u64> {
249    use std::io::{Read, Seek, SeekFrom};
250    // A tool result can be large; widen the window once before giving up.
251    for window in [256 * 1024_u64, 8 * 1024 * 1024] {
252        let mut file = std::fs::File::open(path).ok()?;
253        let length = file.metadata().ok()?.len();
254        let start = length.saturating_sub(window);
255        file.seek(SeekFrom::Start(start)).ok()?;
256        let mut bytes = Vec::new();
257        file.read_to_end(&mut bytes).ok()?;
258        let text = String::from_utf8_lossy(&bytes);
259        let mut lines = text.lines().rev().collect::<Vec<_>>();
260        if start > 0 {
261            lines.pop(); // the first line may begin mid-record
262        }
263        for line in lines {
264            let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {
265                continue;
266            };
267            let message = match harness {
268                "codex" => record["type"] == "response_item",
269                _ => {
270                    matches!(record["type"].as_str(), Some("user" | "assistant"))
271                        && record["isSidechain"] != true
272                }
273            };
274            if !message {
275                continue;
276            }
277            if let Some(at) = record["timestamp"]
278                .as_str()
279                .and_then(supercode_interchange::sidecar::rfc3339_to_ms)
280                .and_then(|at| u64::try_from(at).ok())
281            {
282                return Some(at);
283            }
284        }
285        if start == 0 {
286            return None;
287        }
288    }
289    None
290}
291
292/// Every running session on this machine with its door, read once: what
293/// `message list` shows, what names resolve against, and what discovery
294/// projects onto each discovered session as `delivery`.
295#[derive(Debug, Default)]
296pub struct LiveSessions {
297    sessions: Vec<LiveSession>,
298}
299
300/// Why a receiver named by an agent was not found.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub enum Unresolved {
303    /// The address names a session that is not running.
304    Stale(String),
305    /// No running session has that name (the text suggests near names).
306    Unknown(String),
307}
308
309impl LiveSessions {
310    /// Read every running session now. Sessions supercode controls come
311    /// first, and a degraded-tier row for the same session is dropped: the
312    /// runtime is the default tier.
313    pub fn read(homes: &HarnessHomes) -> Self {
314        crate::slow_log::timed("read live sessions", || Self::read_now(homes))
315    }
316
317    fn read_now(homes: &HarnessHomes) -> Self {
318        let machine = local_machine_name();
319        let registry = read_registry(&registry_dir(homes));
320        // A hosted Claude session is also in Claude's registry, which knows
321        // its name; a relay is not a session and is not listed.
322        let registered = |record: &crate::live_runtime::LiveRuntimeRecord| {
323            registry.iter().find(|session| {
324                session.session_id == record.source.session_id
325                    || session.session_id == record.runtime_session_id
326            })
327        };
328        let records = crate::runtime_mail::controlled_runtimes();
329        // A runtime supercode hosts says whether a turn runs: its label is that, not only its door.
330        let turns = crate::runtime_mail::runtime_turn_states(&records);
331        let mut sessions: Vec<LiveSession> = records
332            .into_iter()
333            .zip(turns)
334            .filter_map(|(record, turn)| {
335                let registered = registered(&record);
336                if registered.is_some_and(|session| session.name.starts_with(RELAY_NAME_PREFIX)) {
337                    return None;
338                }
339                let address =
340                    MailAddress::new(&machine, &record.source.harness, &record.source.session_id)
341                        .ok()?;
342                let short: String = record.source.session_id.chars().take(8).collect();
343                let name = match registered {
344                    Some(session) if !session.name.is_empty() => session.name.clone(),
345                    _ => format!("{}-{short}", record.source.harness),
346                };
347                Some(LiveSession {
348                    name: format!("{name}@{machine}"),
349                    address,
350                    // `hosted` only when its runtime did not answer: no label rather than a false one.
351                    status: match turn {
352                        Some(crate::frontend::FrontendTurnState::Busy) => "busy".into(),
353                        Some(crate::frontend::FrontendTurnState::Idle) => "idle".into(),
354                        None => "hosted".into(),
355                    },
356                    pid: Some(record.pid),
357                    cwd: Some(record.source.workspace.clone()),
358                    tmux: None,
359                    transcript: None,
360                    door: Door::Runtime(Box::new(record)),
361                })
362            })
363            .collect();
364        let controlled = |address: &MailAddress, sessions: &[LiveSession]| {
365            sessions.iter().any(|session| &session.address == address)
366        };
367        for session in registry {
368            if session.name.starts_with(RELAY_NAME_PREFIX) {
369                continue;
370            }
371            let Ok(address) = MailAddress::new(&machine, "claude-code", &session.session_id) else {
372                continue;
373            };
374            if controlled(&address, &sessions) {
375                continue;
376            }
377            sessions.push(LiveSession {
378                address,
379                name: format!("{}@{machine}", session.name),
380                status: session
381                    .status
382                    .as_ref()
383                    .map(|status| status.as_str().to_string())
384                    .unwrap_or_else(|| "unknown".into()),
385                pid: Some(session.pid),
386                cwd: session.cwd.clone(),
387                tmux: session.tmux.clone(),
388                transcript: None,
389                door: Door::Native(Box::new(session)),
390            });
391        }
392        let user_hook = codex_user_hook_installed();
393        let rollouts = crate::codex_peer::live_rollouts(&homes.codex);
394        let panes = crate::codex_peer::session_panes();
395        // A shared native app-server can retain a rollout after its terminal has gone.
396        // Pane absence rules out the pane, not the native writer holding the thread.
397        let live_panes = (!panes.is_empty())
398            .then(|| live_daemon_panes(panes.values()))
399            .flatten();
400        for (path, status) in rollouts {
401            let Some((session_id, None)) = crate::codex_peer::rollout_session(&path) else {
402                continue;
403            };
404            let Ok(address) = MailAddress::new(&machine, "codex", &session_id) else {
405                continue;
406            };
407            if controlled(&address, &sessions) {
408                continue;
409            }
410            let cwd = crate::codex_peer::rollout_cwd(&path);
411            let hooked = user_hook || cwd.as_deref().is_some_and(codex_project_hook_installed);
412            let pane = panes
413                .get(&session_id)
414                .filter(|pane| {
415                    live_panes
416                        .as_ref()
417                        .is_none_or(|live| live.contains_key(*pane))
418                })
419                .cloned();
420            // A Codex turn waiting on an approval or a choice writes nothing to its rollout, which
421            // reads that turn as working; in a daemon pane its screen shows the prompt.
422            let status = match status {
423                crate::codex_peer::CodexPeerStatus::Busy
424                | crate::codex_peer::CodexPeerStatus::Running
425                    if pane.as_ref().is_some_and(|p| {
426                        live_panes.as_ref().and_then(|live| live.get(p)) == Some(&true)
427                    }) =>
428                {
429                    "idle".to_string()
430                }
431
432                crate::codex_peer::CodexPeerStatus::Busy
433                | crate::codex_peer::CodexPeerStatus::Running
434                    if pane.as_deref().and_then(pane_prompt).is_some() =>
435                {
436                    "waiting".to_string()
437                }
438                status => status.as_str().to_string(),
439            };
440            let door = if hooked {
441                Door::Hook {
442                    pane: pane.clone(),
443                    idle: status == "idle",
444                }
445            } else {
446                Door::Stored
447            };
448            sessions.push(LiveSession {
449                name: format!("{}@{machine}", codex_name(&session_id)),
450                address,
451                status,
452                pid: None,
453                cwd,
454                // The daemon pane it runs in, as a Claude session's tmux names its own.
455                tmux: pane,
456                transcript: Some(path),
457                door,
458            });
459        }
460        // A conversation resumed in a daemon pane and idle since holds no rollout open; its pane and the
461        // process's own `resume <id>` still name it, so it is reachable as an idle session there.
462        for (session_id, pane) in &panes {
463            let Ok(address) = MailAddress::new(&machine, "codex", session_id) else {
464                continue;
465            };
466            if controlled(&address, &sessions)
467                || !live_panes
468                    .as_ref()
469                    .is_some_and(|live| live.contains_key(pane))
470            {
471                continue;
472            }
473            let Some(path) = crate::codex_peer::rollout_of_session(&homes.codex, session_id) else {
474                continue;
475            };
476            let cwd = crate::codex_peer::rollout_cwd(&path);
477            let hooked = user_hook || cwd.as_deref().is_some_and(codex_project_hook_installed);
478            sessions.push(LiveSession {
479                name: format!("{}@{machine}", codex_name(session_id)),
480                address,
481                status: "idle".to_string(),
482                pid: None,
483                cwd,
484                tmux: Some(pane.clone()),
485                transcript: Some(path),
486                door: if hooked {
487                    Door::Hook {
488                        pane: Some(pane.clone()),
489                        idle: true,
490                    }
491                } else {
492                    Door::Stored
493                },
494            });
495        }
496        Self { sessions }
497    }
498
499    /// Every running session.
500    pub fn all(&self) -> &[LiveSession] {
501        &self.sessions
502    }
503
504    /// The door that reaches `harness`'s session `session_id`, when it is
505    /// running.
506    pub fn door(&self, harness: &str, session_id: &str) -> Option<&'static str> {
507        self.sessions
508            .iter()
509            .find(|session| {
510                session.address.harness == harness && session.address.session_id == session_id
511            })
512            .map(|session| session.door.name())
513    }
514
515    /// The running session an agent means by `to`: an address, `name@machine`
516    /// on this machine, or a name unique here.
517    pub fn resolve(&self, to: &str) -> Result<&LiveSession, Unresolved> {
518        let machine = local_machine_name();
519        if let Ok(address) = MailAddress::parse(to) {
520            return self
521                .sessions
522                .iter()
523                .find(|session| session.address == address)
524                .ok_or_else(|| {
525                    Unresolved::Stale(format!(
526                        "{to} is no longer running. Nothing was sent. Run supercode message list \
527                         for the live sessions."
528                    ))
529                });
530        }
531        let wanted = match to.split_once('@') {
532            Some((name, at)) if at == machine => name.to_string(),
533            Some((_, at)) => {
534                return Err(Unresolved::Unknown(format!(
535                    "Not sent: {to} is on machine {at}, not this one. Nothing was sent."
536                )))
537            }
538            None => to.to_string(),
539        };
540        let short = |session: &LiveSession| {
541            session
542                .name
543                .split('@')
544                .next()
545                .unwrap_or_default()
546                .to_string()
547        };
548        let matching: Vec<&LiveSession> = self
549            .sessions
550            .iter()
551            .filter(|session| short(session) == wanted)
552            .collect();
553        if let [only] = matching.as_slice() {
554            return Ok(only);
555        }
556        let hint = if matching.len() > 1 {
557            format!(
558                " {} sessions are named {wanted}; use its address.",
559                matching.len()
560            )
561        } else {
562            let near: Vec<String> = self
563                .sessions
564                .iter()
565                .filter(|session| {
566                    let name = short(session);
567                    name.contains(&wanted)
568                        || wanted.contains(&name)
569                        || name
570                            .chars()
571                            .zip(wanted.chars())
572                            .take_while(|(a, b)| a == b)
573                            .count()
574                            >= 4
575                })
576                .take(3)
577                .map(|session| {
578                    format!(
579                        "{} ({}, {})",
580                        session.name, session.address.harness, session.status
581                    )
582                })
583                .collect();
584            if near.is_empty() {
585                String::new()
586            } else {
587                format!(" Did you mean: {}?", near.join(", "))
588            }
589        };
590        Err(Unresolved::Unknown(format!(
591            "No session named \"{wanted}\" is reachable.{hint} Run supercode message list. Nothing \
592             was sent."
593        )))
594    }
595}
596
597/// Whether the session process `pid` has supercode's messaging tools: a
598/// harness starts each MCP server as a child of the session, so the tools are
599/// loaded exactly when a live `supercode message mcp` is one of its children.
600pub fn has_message_tools(pid: u32) -> bool {
601    let Ok(output) = std::process::Command::new("ps")
602        .args(["-A", "-o", "ppid=,command="])
603        .output()
604    else {
605        return false;
606    };
607    String::from_utf8_lossy(&output.stdout).lines().any(|line| {
608        let line = line.trim_start();
609        let Some((ppid, command)) = line.split_once(' ') else {
610            return false;
611        };
612        ppid.parse::<u32>() == Ok(pid) && command.trim_end().ends_with(" message mcp")
613    })
614}
615
616/// Display name of a Codex conversation: `codex-` and the start of its id.
617pub fn codex_name(session_id: &str) -> String {
618    format!("codex-{}", session_id.chars().take(8).collect::<String>())
619}
620
621/// The session a process belongs to: the sender a message is from.
622#[derive(Debug, Clone, PartialEq, Eq)]
623pub struct Caller {
624    /// Its address, where replies go.
625    pub address: MailAddress,
626    /// The name it is known by.
627    pub name: String,
628}
629
630/// Why no session could be found behind a process.
631pub const CALLER_UNRESOLVED: &str = "Can't tell which session is running this command, so \
632    replies would have nowhere to go. Nothing was sent. Run it from your agent session's own \
633    shell tool.";
634
635/// The session behind a process, from its ancestry `pids` (nearest first):
636/// the first that owns a hosted runtime, a Claude session or a Codex
637/// conversation. Never declared by the caller; an environment id only
638/// corroborates, and a mismatch refuses.
639pub fn resolve_caller(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
640    crate::slow_log::timed("resolve the caller", || resolve_caller_now(homes, pids))
641}
642
643fn resolve_caller_now(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
644    let machine = local_machine_name();
645    let registry = read_registry(&registry_dir(homes));
646    let hosted = crate::runtime_mail::controlled_runtimes();
647    for &pid in pids {
648        if let Some(record) = hosted.iter().find(|record| record.pid == pid) {
649            let short: String = record.source.session_id.chars().take(8).collect();
650            return Ok(Caller {
651                address: MailAddress::new(
652                    &machine,
653                    &record.source.harness,
654                    &record.source.session_id,
655                )
656                .map_err(|error| error.to_string())?,
657                name: format!("{}-{short}@{machine}", record.source.harness),
658            });
659        }
660        if let Some(session) = registry.iter().find(|session| session.pid == pid) {
661            if let Ok(claimed) = std::env::var("CLAUDE_CODE_SESSION_ID") {
662                if !claimed.is_empty() && claimed != session.session_id {
663                    return Err(format!(
664                        "{CALLER_UNRESOLVED} (CLAUDE_CODE_SESSION_ID names {claimed}, but the Claude \
665                         process {pid} above this command is session {})",
666                        session.session_id
667                    ));
668                }
669            }
670            return Ok(Caller {
671                address: MailAddress::new(&machine, "claude-code", &session.session_id)
672                    .map_err(|error| error.to_string())?,
673                name: format!("{}@{machine}", session.name),
674            });
675        }
676        // Codex names the thread a command runs for (`CODEX_THREAD_ID`); the
677        // claim stands when this process holds that thread's rollout, as
678        // Codex's shared app-server daemon does for every thread it runs.
679        if let Some(thread) = std::env::var("CODEX_THREAD_ID")
680            .ok()
681            .filter(|thread| !thread.is_empty())
682            .filter(|thread| crate::codex_peer::holds_session(pid, thread))
683        {
684            return Ok(Caller {
685                address: MailAddress::new(&machine, "codex", &thread)
686                    .map_err(|error| error.to_string())?,
687                name: format!("{}@{machine}", codex_name(&thread)),
688            });
689        }
690        if let Some((session_id, _)) = crate::codex_peer::session_of_process(pid) {
691            return Ok(Caller {
692                address: MailAddress::new(&machine, "codex", &session_id)
693                    .map_err(|error| error.to_string())?,
694                name: format!("{}@{machine}", codex_name(&session_id)),
695            });
696        }
697    }
698    #[cfg(windows)]
699    if let Some(session) = msys_cut_claim(&registry, pids) {
700        return Ok(Caller {
701            address: MailAddress::new(&machine, "claude-code", &session.session_id)
702                .map_err(|error| error.to_string())?,
703            name: format!("{}@{machine}", session.name),
704        });
705    }
706    Err(format!(
707        "{CALLER_UNRESOLVED} (looked for this command's processes {pids:?} among {} Claude \
708         sessions in {} and {} hosted runtimes)",
709        registry.len(),
710        registry_dir(homes).display(),
711        hosted.len()
712    ))
713}
714
715/// Git Bash (MSYS) runs a command in a forked process that hands over to it. When the command is
716/// itself an MSYS program (a `sh` script, as npm's command shims are), the forked process exits once
717/// it has handed over, so the Windows parent chain is cut just above that shell and never reaches
718/// the Claude session running it. When the ancestry ends at exactly such a cut (its last pid is gone,
719/// the one before it is an MSYS shell), the session Claude names in `CLAUDE_CODE_SESSION_ID` stands
720/// if it is a live Claude session on this machine.
721#[cfg(windows)]
722fn msys_cut_claim<'a>(
723    registry: &'a [ClaudePeerSession],
724    pids: &[u32],
725) -> Option<&'a ClaudePeerSession> {
726    let table = process_table();
727    let [.., shell, cut] = pids else {
728        return None;
729    };
730    if table.contains_key(cut) {
731        return None;
732    }
733    let name = table.get(shell)?.1.to_ascii_lowercase();
734    if !matches!(name.as_str(), "sh.exe" | "bash.exe" | "dash.exe") {
735        return None;
736    }
737    let claimed = std::env::var("CLAUDE_CODE_SESSION_ID").ok()?;
738    registry
739        .iter()
740        .find(|session| !claimed.is_empty() && session.session_id == claimed)
741}
742
743/// This process's ancestry, nearest first (itself included).
744pub fn process_ancestry() -> Vec<u32> {
745    crate::slow_log::timed("read the process ancestry", || {
746        ancestry_of(std::process::id())
747    })
748}
749
750/// A process's ancestry, nearest first (itself included).
751pub fn ancestry_of(pid: u32) -> Vec<u32> {
752    let parents = parent_pids();
753    let mut chain = vec![pid];
754    let mut current = pid;
755    while let Some(&parent) = parents.get(&current) {
756        if parent <= 1 || chain.contains(&parent) {
757            break;
758        }
759        chain.push(parent);
760        current = parent;
761    }
762    chain
763}
764
765/// Every process's parent: pid → parent pid, from `ps`.
766#[cfg(not(windows))]
767fn parent_pids() -> std::collections::HashMap<u32, u32> {
768    let Ok(output) = std::process::Command::new("ps")
769        .args(["-axo", "pid=,ppid="])
770        .output()
771    else {
772        return Default::default();
773    };
774    String::from_utf8_lossy(&output.stdout)
775        .lines()
776        .filter_map(|line| {
777            let mut fields = line.split_whitespace();
778            Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?))
779        })
780        .collect()
781}
782
783/// Every process's parent: pid → parent pid, from a process snapshot.
784#[cfg(windows)]
785fn parent_pids() -> std::collections::HashMap<u32, u32> {
786    process_table()
787        .into_iter()
788        .map(|(pid, (parent, _))| (pid, parent))
789        .collect()
790}
791
792/// Every process: pid → (parent pid, executable file name), from a process snapshot.
793#[cfg(windows)]
794fn process_table() -> std::collections::HashMap<u32, (u32, String)> {
795    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
796    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
797        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
798        TH32CS_SNAPPROCESS,
799    };
800
801    let mut parents = std::collections::HashMap::new();
802    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
803    if snapshot == INVALID_HANDLE_VALUE {
804        return parents;
805    }
806    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
807    entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
808    let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
809    while has_entry {
810        let length = entry
811            .szExeFile
812            .iter()
813            .position(|&unit| unit == 0)
814            .unwrap_or(entry.szExeFile.len());
815        let name = String::from_utf16_lossy(&entry.szExeFile[..length]);
816        parents.insert(entry.th32ProcessID, (entry.th32ParentProcessID, name));
817        has_entry = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
818    }
819    unsafe {
820        CloseHandle(snapshot);
821    }
822    parents
823}
824
825/// Codex's user-level hooks file.
826pub fn codex_hooks_path() -> std::path::PathBuf {
827    std::env::var_os("CODEX_HOME")
828        .map(std::path::PathBuf::from)
829        .or_else(|| {
830            supercode_interchange::user_home()
831                .map(std::path::PathBuf::into_os_string)
832                .map(|home| std::path::PathBuf::from(home).join(".codex"))
833        })
834        .unwrap_or_else(|| std::path::PathBuf::from(".codex"))
835        .join("hooks.json")
836}
837
838/// Whether supercode's mail hook is in Codex's user hooks file. (Codex runs
839/// it only once its user has trusted it.)
840pub fn codex_user_hook_installed() -> bool {
841    std::fs::read_to_string(codex_hooks_path())
842        .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
843}
844
845/// Whether supercode's mail hook is in a project's Codex hooks file, in the
846/// session's directory or one above it.
847pub fn codex_project_hook_installed(cwd: &Path) -> bool {
848    cwd.ancestors().any(|directory| {
849        std::fs::read_to_string(directory.join(".codex").join("hooks.json"))
850            .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
851    })
852}
853
854/// How a delivery ended.
855#[derive(Debug, Clone, PartialEq, Eq)]
856pub enum Delivered {
857    /// The receiver has it now: steered into a running turn.
858    Steered,
859    /// The receiver has it now: it started a turn in an idle session.
860    Started,
861    /// Claude reported it in the receiver's inbox; `busy` says whether the
862    /// receiver reads it at its next tool call (true) or it starts a turn.
863    Native {
864        /// True when the receiver was in a turn.
865        busy: bool,
866    },
867    /// Filed in the receiver's mailbox, which a hook points it at.
868    Hooked,
869    /// Filed in an idle receiver's mailbox, and its pane told to read it: a
870    /// turn has started, in which its hook shows it the message.
871    HookWoken,
872    /// Filed in the receiver's mailbox, waiting to be read.
873    Queued,
874    /// Filed with no door to show it.
875    Stored,
876    /// Filed in an operator's mailbox.
877    Operator,
878}
879
880/// A delivery refused before anything was sent.
881#[derive(Debug, Clone, PartialEq, Eq)]
882pub enum Refused {
883    /// `--queue` cannot hold a message for an idle Claude session: Claude
884    /// starts a turn for every message it delivers.
885    CannotQueueNative,
886    /// The relayed text would not fit one relay turn.
887    TooLong(usize),
888}
889
890/// Largest message relayed into a Claude session. The relay copies it into a
891/// model turn byte for byte, so it must fit comfortably in one.
892pub const MAX_RELAYED_BYTES: usize = 100_000;
893
894/// Deliver `envelope` to `to` through `door`. With `wake` false an idle
895/// receiver is not started. With `notify_when_idle` the sender gets one idle
896/// notice after the receiver's next turn ends.
897pub async fn deliver(
898    envelope: &Envelope,
899    to: &MailAddress,
900    door: &Door,
901    wake: bool,
902    notify_when_idle: bool,
903) -> Result<Result<Delivered, Refused>, String> {
904    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
905    // A runtime answers with its turn's final message, which the watcher
906    // sends back: not every runtime can run a command (a hosted agent may
907    // have no shell), and each can end a turn.
908    let mut final_reply = false;
909    let delivered = match door {
910        Door::Runtime(record) => {
911            let mut sent = envelope.clone();
912            let answers = matches!(envelope.reply_via, ReplyVia::Command);
913            if answers {
914                sent.reply_via = ReplyVia::FinalMessage {
915                    destination: envelope.from_name.clone(),
916                };
917            }
918            match deliver_to_runtime(record, sent.render(), wake).await? {
919                RuntimeDelivery::Steered => {
920                    mailbox
921                        .deliver_read(&sent)
922                        .map_err(|error| error.to_string())?;
923                    final_reply = answers;
924                    Delivered::Steered
925                }
926                RuntimeDelivery::Started => {
927                    mailbox
928                        .deliver_read(&sent)
929                        .map_err(|error| error.to_string())?;
930                    final_reply = answers;
931                    Delivered::Started
932                }
933                RuntimeDelivery::NotWoken => {
934                    mailbox
935                        .deliver(envelope)
936                        .map_err(|error| error.to_string())?;
937                    Delivered::Queued
938                }
939            }
940        }
941        Door::Native(session) => {
942            let busy = session.status != Some(ClaudePeerStatus::Idle);
943            if !wake && !busy {
944                return Ok(Err(Refused::CannotQueueNative));
945            }
946            // The same envelope every door delivers; Claude wraps it in its
947            // own, which names the relay. Its reply line names the door this
948            // session really has: its tools when it runs supercode's MCP server.
949            let mut envelope = envelope.clone();
950            if envelope.reply_via == ReplyVia::Command && has_message_tools(session.pid) {
951                envelope.reply_via = ReplyVia::Tool;
952            }
953            let envelope = &envelope;
954            let text = envelope.render();
955            if text.len() > MAX_RELAYED_BYTES {
956                return Ok(Err(Refused::TooLong(text.len())));
957            }
958            // Filed before it is handed over: a session that reads its mailbox on its first tool call (to reply by
959            // the message's id) finds it there. A relay that fails takes back the copy this delivery filed.
960            let filed_here = mailbox
961                .find(&envelope.id)
962                .map_err(|error| error.to_string())?
963                .is_none();
964            let filed = mailbox
965                .deliver_read(envelope)
966                .map_err(|error| error.to_string())?;
967            match send_through_relay(
968                &envelope.from,
969                &envelope.from_name,
970                &session.name,
971                text,
972                &envelope.id,
973            )
974            .await
975            {
976                RelayReceipt::Delivered { .. } => Delivered::Native { busy },
977                RelayReceipt::Failed { detail } => {
978                    if filed_here {
979                        std::fs::remove_file(&filed).ok();
980                    }
981                    return Err(detail);
982                }
983            }
984        }
985        Door::Hook { .. } => {
986            mailbox
987                .deliver(envelope)
988                .map_err(|error| error.to_string())?;
989            if wake {
990                mailbox
991                    .request_wake(&envelope.id)
992                    .map_err(|error| error.to_string())?;
993            }
994            Delivered::Hooked
995        }
996        Door::Stored => {
997            mailbox
998                .deliver(envelope)
999                .map_err(|error| error.to_string())?;
1000            Delivered::Stored
1001        }
1002        Door::Operator => {
1003            mailbox
1004                .deliver(envelope)
1005                .map_err(|error| error.to_string())?;
1006            Delivered::Operator
1007        }
1008    };
1009    let notice = notify_when_idle && !matches!(door, Door::Operator);
1010    if notice || final_reply {
1011        let mut subscription = IdleSubscription::new(envelope.id.clone(), envelope.from.clone());
1012        subscription.notice = notice;
1013        subscription.final_reply = final_reply;
1014        mailbox
1015            .subscribe_idle(&subscription)
1016            .map_err(|error| error.to_string())?;
1017        // The watcher that settles it runs beside the machine daemon.
1018        if let Ok(program) = supercode_program() {
1019            crate::claude_relay::ensure_machine_daemon(&program)
1020                .await
1021                .ok();
1022        }
1023    }
1024    Ok(Ok(delivered))
1025}
1026
1027/// How the user's own turn reached its session.
1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1029pub enum UserTurn {
1030    /// A hosted runtime was in a turn; the words were steered into it.
1031    Steered,
1032    /// A hosted runtime was idle; the words started a turn.
1033    Started,
1034    /// Typed into the session's pane as its own submitted turn.
1035    Typed,
1036    /// The pane's composer holds a draft, or its program is not at its
1037    /// composer: the turn waits in the session's mailbox and is typed once
1038    /// the composer is empty.
1039    Waiting,
1040}
1041
1042impl UserTurn {
1043    /// Stable wire spelling.
1044    pub const fn as_str(self) -> &'static str {
1045        match self {
1046            Self::Steered => "steered",
1047            Self::Started => "started",
1048            Self::Typed => "typed",
1049            Self::Waiting => "waiting",
1050        }
1051    }
1052}
1053
1054/// The choice or permission prompt a daemon pane's screen shows, as its lines (the question above
1055/// it and its options), or `None`. The terminal substrate's own check (`classifyAttentionSignal`):
1056/// a selector (❯ or ›) on a numbered option is a prompt blocked on an answer; the idle input line
1057/// has no number after its selector.
1058pub fn pane_prompt(pane: &str) -> Option<Vec<String>> {
1059    let screen = pane_screen(pane)?;
1060    let lines: Vec<&str> = screen.lines().map(str::trim_end).collect();
1061    let is_option = |line: &str| {
1062        let line = line.trim_start();
1063        // Windows consoles draw Claude's selector as `>`.
1064        let rest = line
1065            .strip_prefix('❯')
1066            .or_else(|| line.strip_prefix('›'))
1067            .or_else(|| line.strip_prefix('>'))
1068            .unwrap_or(line)
1069            .trim_start();
1070        let digits = rest.chars().take_while(char::is_ascii_digit).count();
1071        digits > 0 && matches!(rest[digits..].chars().next(), Some('.' | ')'))
1072    };
1073    let selected = lines.iter().position(|line| {
1074        let line = line.trim_start();
1075        (line.starts_with('❯') || line.starts_with('›') || line.starts_with('>')) && is_option(line)
1076    })?;
1077    // The prompt: the options' block of non-empty lines and the block above it (the question).
1078    let block_start = |end: usize| {
1079        lines[..end]
1080            .iter()
1081            .rposition(|line| line.trim().is_empty())
1082            .map_or(0, |blank| blank + 1)
1083    };
1084    let options = block_start(selected);
1085    let above = lines[..options]
1086        .iter()
1087        .rposition(|line| !line.trim().is_empty())
1088        .map(|last| block_start(last));
1089    let start = above.unwrap_or(options);
1090    let end = lines[selected..]
1091        .iter()
1092        .position(|line| line.trim().is_empty())
1093        .map_or(lines.len(), |blank| selected + blank);
1094    Some(
1095        lines[start..end]
1096            .iter()
1097            .map(|line| line.trim().to_string())
1098            .filter(|line| !line.is_empty())
1099            .take(20)
1100            .collect(),
1101    )
1102}
1103
1104/// Read this machine's actual panes once for the session list. Unavailability is unknown.
1105/// Only `wanted` are read: the daemon captures each pane it is asked about, so asking about every
1106/// pane cost a screen capture of all of them on every live-session read (t_23e47b73).
1107fn live_daemon_panes<'a>(
1108    wanted: impl Iterator<Item = &'a String>,
1109) -> Option<std::collections::HashMap<String, bool>> {
1110    let wanted: Vec<&str> = wanted.map(String::as_str).collect();
1111    crate::slow_log::timed("teams panes ls --presence-only", || {
1112        live_daemon_panes_now(&wanted.join(","))
1113    })
1114}
1115
1116fn live_daemon_panes_now(wanted: &str) -> Option<std::collections::HashMap<String, bool>> {
1117    let entry = crate::teams_entry().ok()?;
1118    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
1119        .ok()
1120        .filter(|value| !value.trim().is_empty())
1121        .unwrap_or_else(|| "node".into());
1122    let output = std::process::Command::new(node)
1123        .arg(entry)
1124        .args(["panes", "ls", "--presence-only", "--panes", wanted])
1125        .stdin(std::process::Stdio::null())
1126        .output()
1127        .ok()?;
1128    if !output.status.success() {
1129        return None;
1130    }
1131    let rows: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).ok()?;
1132    rows.iter()
1133        .map(|row| {
1134            Some((
1135                row["pane"].as_str()?.to_owned(),
1136                row["idleComposer"].as_bool()?,
1137            ))
1138        })
1139        .collect()
1140}
1141
1142/// A daemon pane's screen: tmux's capture where the daemon's host is tmux, else the machine daemon's
1143/// own capture (`teams panes capture`), as on Windows, where panes are ConPTY.
1144fn pane_screen(pane: &str) -> Option<String> {
1145    #[cfg(unix)]
1146    {
1147        let output = std::process::Command::new("tmux")
1148            .args(["capture-pane", "-p", "-t", &format!("{pane}:")])
1149            .output()
1150            .ok()?;
1151        output
1152            .status
1153            .success()
1154            .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
1155    }
1156    #[cfg(not(unix))]
1157    {
1158        let entry = crate::teams_entry().ok()?;
1159        let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
1160            .ok()
1161            .filter(|value| !value.trim().is_empty())
1162            .unwrap_or_else(|| "node".into());
1163        let output = std::process::Command::new(node)
1164            .arg(entry)
1165            .args(["panes", "capture", pane, "--lines", "60"])
1166            .stdin(std::process::Stdio::null())
1167            .output()
1168            .ok()?;
1169        output
1170            .status
1171            .success()
1172            .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
1173    }
1174}
1175
1176/// The daemon pane a session runs in, when it runs in one.
1177pub fn daemon_pane(session: &LiveSession) -> Option<String> {
1178    let name = session.tmux.as_deref()?.split(':').next()?;
1179    let rest = name.strip_prefix("p_")?;
1180    (!rest.is_empty()
1181        && rest
1182            .chars()
1183            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
1184    .then(|| name.to_string())
1185}
1186
1187/// Deliver the user's own turn to `to` through the one door that carries the
1188/// user's authority: a hosted runtime's own input, or the session's pane.
1189/// A session with neither (running outside supercode) is refused, never
1190/// reached as a peer instead. Callers hold the owner's authority already:
1191/// this is reached only through owner doors (the machine's own harness.v1).
1192pub async fn deliver_user_turn(
1193    homes: &HarnessHomes,
1194    envelope: &Envelope,
1195    to: &MailAddress,
1196) -> Result<UserTurn, String> {
1197    let session = LiveSessions::read(homes)
1198        .sessions
1199        .into_iter()
1200        .find(|session| &session.address == to)
1201        .ok_or_else(|| format!("{to} is not running; nothing was sent"))?;
1202    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
1203    if let Door::Runtime(record) = &session.door {
1204        let delivered = deliver_to_runtime(record, envelope.body.clone(), true).await?;
1205        mailbox
1206            .deliver_read(envelope)
1207            .map_err(|error| error.to_string())?;
1208        return Ok(match delivered {
1209            RuntimeDelivery::Steered => UserTurn::Steered,
1210            _ => UserTurn::Started,
1211        });
1212    }
1213    let Some(pane) = daemon_pane(&session) else {
1214        let name = session.name.split('@').next().unwrap_or(&session.name);
1215        return Err(format!(
1216            "{name} runs outside supercode, where nothing can speak as its user. Open it in a \
1217             pane with `supercode open {name}`; nothing was sent."
1218        ));
1219    };
1220    mailbox
1221        .deliver(envelope)
1222        .map_err(|error| error.to_string())?;
1223    let typed = type_user_turns(&mailbox, &pane).await;
1224    Ok(if typed.contains(&envelope.id) {
1225        UserTurn::Typed
1226    } else {
1227        UserTurn::Waiting
1228    })
1229}
1230
1231/// Type the user's waiting turns into `pane`, oldest first, each only when
1232/// the pane's composer is empty. Stops at the first that has to wait.
1233/// Returns the ids typed.
1234pub async fn type_user_turns(mailbox: &Mailbox, pane: &str) -> Vec<String> {
1235    let mut typed = Vec::new();
1236    for waiting in mailbox.user_turns().unwrap_or_default() {
1237        // Claimed before it is typed: the machine's watcher and a direct delivery both type waiting turns, and
1238        // two typers filling one composer sent a turn's text twice in one prompt. A turn another typer holds is
1239        // that typer's, and so is every turn after it.
1240        let Ok(Some(stored)) = mailbox.claim_user_turn(&waiting) else {
1241            break;
1242        };
1243        match submit_mail_batch(pane, &stored.envelope.body, &[stored.envelope.id.clone()]).await {
1244            Ok(true) => {
1245                mailbox.acknowledge(&stored).ok();
1246                typed.push(stored.envelope.id.clone());
1247            }
1248            Ok(false) => {
1249                mailbox.release(&stored).ok();
1250                break;
1251            }
1252            Err(error) => {
1253                mailbox.release(&stored).ok();
1254                eprintln!(
1255                    "supercode: the user's turn {} for {} waits: {error}",
1256                    stored.envelope.id,
1257                    mailbox.address()
1258                );
1259                break;
1260            }
1261        }
1262    }
1263    typed
1264}
1265
1266/// The daemon drains a recipient's waiting envelopes as one paste. The machine
1267/// retains the batch and its ids until the native transcript confirms receipt.
1268pub(crate) async fn wake_hook_mailbox(
1269    mailbox: &Mailbox,
1270    pane: &str,
1271    ids: &[String],
1272) -> Result<bool, String> {
1273    let messages = ids
1274        .iter()
1275        .map(|id| mailbox.find(id))
1276        .collect::<Result<Vec<_>, _>>()
1277        .map_err(|error| error.to_string())?;
1278    let messages: Vec<_> = messages.into_iter().flatten().collect();
1279    if messages.is_empty() {
1280        return Ok(false);
1281    }
1282    let mut delivered = true;
1283    for message in messages {
1284        delivered &= submit_mail_batch(
1285            pane,
1286            &message.envelope.render(),
1287            &[message.envelope.id.clone()],
1288        )
1289        .await?;
1290    }
1291    Ok(delivered)
1292}
1293
1294async fn submit_mail_batch(pane: &str, text: &str, ids: &[String]) -> Result<bool, String> {
1295    let entry = crate::teams_entry().map_err(|error| error.to_string())?;
1296    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
1297        .ok()
1298        .filter(|value| !value.trim().is_empty())
1299        .unwrap_or_else(|| "node".into());
1300    let output = tokio::process::Command::new(node)
1301        .arg(entry)
1302        .args([
1303            "input",
1304            pane,
1305            text,
1306            "--when-composer-empty",
1307            "--message-ids",
1308            &ids.join(","),
1309        ])
1310        // A message is the session's own door, not a session acting on a pane: the pane doors read that from this
1311        // process's place under the daemon's `message watch`, not from anything named here.
1312        .env_remove("SUPERCODE_CALLER")
1313        .stdin(std::process::Stdio::null())
1314        .output()
1315        .await
1316        .map_err(|error| error.to_string())?;
1317    if !output.status.success() {
1318        return Err(crate::mailbox::error_line(&String::from_utf8_lossy(
1319            &output.stderr,
1320        )));
1321    }
1322    let answer: serde_json::Value =
1323        serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?;
1324    Ok(answer["delivered"] == true)
1325}