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" {
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        let machine = local_machine_name();
315        let registry = read_registry(&registry_dir(homes));
316        // A hosted Claude session is also in Claude's registry, which knows
317        // its name; a relay is not a session and is not listed.
318        let registered = |record: &crate::live_runtime::LiveRuntimeRecord| {
319            registry.iter().find(|session| {
320                session.session_id == record.source.session_id
321                    || session.session_id == record.runtime_session_id
322            })
323        };
324        let mut sessions: Vec<LiveSession> = crate::runtime_mail::controlled_runtimes()
325            .into_iter()
326            .filter_map(|record| {
327                let registered = registered(&record);
328                if registered.is_some_and(|session| session.name.starts_with(RELAY_NAME_PREFIX)) {
329                    return None;
330                }
331                let address =
332                    MailAddress::new(&machine, &record.source.harness, &record.source.session_id)
333                        .ok()?;
334                let short: String = record.source.session_id.chars().take(8).collect();
335                let name = match registered {
336                    Some(session) if !session.name.is_empty() => session.name.clone(),
337                    _ => format!("{}-{short}", record.source.harness),
338                };
339                Some(LiveSession {
340                    name: format!("{name}@{machine}"),
341                    address,
342                    status: "hosted".into(),
343                    pid: Some(record.pid),
344                    cwd: Some(record.source.workspace.clone()),
345                    tmux: None,
346                    transcript: None,
347                    door: Door::Runtime(Box::new(record)),
348                })
349            })
350            .collect();
351        let controlled = |address: &MailAddress, sessions: &[LiveSession]| {
352            sessions.iter().any(|session| &session.address == address)
353        };
354        for session in registry {
355            if session.name.starts_with(RELAY_NAME_PREFIX) {
356                continue;
357            }
358            let Ok(address) = MailAddress::new(&machine, "claude-code", &session.session_id) else {
359                continue;
360            };
361            if controlled(&address, &sessions) {
362                continue;
363            }
364            sessions.push(LiveSession {
365                address,
366                name: format!("{}@{machine}", session.name),
367                status: session
368                    .status
369                    .as_ref()
370                    .map(|status| status.as_str().to_string())
371                    .unwrap_or_else(|| "unknown".into()),
372                pid: Some(session.pid),
373                cwd: session.cwd.clone(),
374                tmux: session.tmux.clone(),
375                transcript: None,
376                door: Door::Native(Box::new(session)),
377            });
378        }
379        let user_hook = codex_user_hook_installed();
380        let rollouts = crate::codex_peer::live_rollouts(&homes.codex);
381        let panes = if rollouts.is_empty() {
382            std::collections::HashMap::new()
383        } else {
384            crate::codex_peer::session_panes()
385        };
386        for (path, status) in rollouts {
387            let Some((session_id, None)) = crate::codex_peer::rollout_session(&path) else {
388                continue;
389            };
390            let Ok(address) = MailAddress::new(&machine, "codex", &session_id) else {
391                continue;
392            };
393            if controlled(&address, &sessions) {
394                continue;
395            }
396            let cwd = crate::codex_peer::rollout_cwd(&path);
397            let hooked = user_hook || cwd.as_deref().is_some_and(codex_project_hook_installed);
398            let pane = panes.get(&session_id).cloned();
399            // A Codex turn waiting on an approval or a choice writes nothing to its rollout, which
400            // reads that turn as working; in a daemon pane its screen shows the prompt.
401            let status = match status {
402                crate::codex_peer::CodexPeerStatus::Busy
403                | crate::codex_peer::CodexPeerStatus::Running
404                    if pane.as_deref().and_then(pane_prompt).is_some() =>
405                {
406                    "waiting".to_string()
407                }
408                status => status.as_str().to_string(),
409            };
410            let door = if hooked {
411                Door::Hook {
412                    pane: pane.clone(),
413                    idle: status == "idle",
414                }
415            } else {
416                Door::Stored
417            };
418            sessions.push(LiveSession {
419                name: format!("{}@{machine}", codex_name(&session_id)),
420                address,
421                status,
422                pid: None,
423                cwd,
424                // The daemon pane it runs in, as a Claude session's tmux names its own.
425                tmux: pane,
426                transcript: Some(path),
427                door,
428            });
429        }
430        Self { sessions }
431    }
432
433    /// Every running session.
434    pub fn all(&self) -> &[LiveSession] {
435        &self.sessions
436    }
437
438    /// The door that reaches `harness`'s session `session_id`, when it is
439    /// running.
440    pub fn door(&self, harness: &str, session_id: &str) -> Option<&'static str> {
441        self.sessions
442            .iter()
443            .find(|session| {
444                session.address.harness == harness && session.address.session_id == session_id
445            })
446            .map(|session| session.door.name())
447    }
448
449    /// The running session an agent means by `to`: an address, `name@machine`
450    /// on this machine, or a name unique here.
451    pub fn resolve(&self, to: &str) -> Result<&LiveSession, Unresolved> {
452        let machine = local_machine_name();
453        if let Ok(address) = MailAddress::parse(to) {
454            return self
455                .sessions
456                .iter()
457                .find(|session| session.address == address)
458                .ok_or_else(|| {
459                    Unresolved::Stale(format!(
460                        "{to} is no longer running. Nothing was sent. Run supercode message list \
461                         for the live sessions."
462                    ))
463                });
464        }
465        let wanted = match to.split_once('@') {
466            Some((name, at)) if at == machine => name.to_string(),
467            Some((_, at)) => {
468                return Err(Unresolved::Unknown(format!(
469                    "Not sent: {to} is on machine {at}, not this one. Nothing was sent."
470                )))
471            }
472            None => to.to_string(),
473        };
474        let short = |session: &LiveSession| {
475            session
476                .name
477                .split('@')
478                .next()
479                .unwrap_or_default()
480                .to_string()
481        };
482        let matching: Vec<&LiveSession> = self
483            .sessions
484            .iter()
485            .filter(|session| short(session) == wanted)
486            .collect();
487        if let [only] = matching.as_slice() {
488            return Ok(only);
489        }
490        let hint = if matching.len() > 1 {
491            format!(
492                " {} sessions are named {wanted}; use its address.",
493                matching.len()
494            )
495        } else {
496            let near: Vec<String> = self
497                .sessions
498                .iter()
499                .filter(|session| {
500                    let name = short(session);
501                    name.contains(&wanted)
502                        || wanted.contains(&name)
503                        || name
504                            .chars()
505                            .zip(wanted.chars())
506                            .take_while(|(a, b)| a == b)
507                            .count()
508                            >= 4
509                })
510                .take(3)
511                .map(|session| {
512                    format!(
513                        "{} ({}, {})",
514                        session.name, session.address.harness, session.status
515                    )
516                })
517                .collect();
518            if near.is_empty() {
519                String::new()
520            } else {
521                format!(" Did you mean: {}?", near.join(", "))
522            }
523        };
524        Err(Unresolved::Unknown(format!(
525            "No session named \"{wanted}\" is reachable.{hint} Run supercode message list. Nothing \
526             was sent."
527        )))
528    }
529}
530
531/// Whether the session process `pid` has supercode's messaging tools: a
532/// harness starts each MCP server as a child of the session, so the tools are
533/// loaded exactly when a live `supercode message mcp` is one of its children.
534pub fn has_message_tools(pid: u32) -> bool {
535    let Ok(output) = std::process::Command::new("ps")
536        .args(["-A", "-o", "ppid=,command="])
537        .output()
538    else {
539        return false;
540    };
541    String::from_utf8_lossy(&output.stdout).lines().any(|line| {
542        let line = line.trim_start();
543        let Some((ppid, command)) = line.split_once(' ') else {
544            return false;
545        };
546        ppid.parse::<u32>() == Ok(pid) && command.trim_end().ends_with(" message mcp")
547    })
548}
549
550/// Display name of a Codex conversation: `codex-` and the start of its id.
551pub fn codex_name(session_id: &str) -> String {
552    format!("codex-{}", session_id.chars().take(8).collect::<String>())
553}
554
555/// The session a process belongs to: the sender a message is from.
556#[derive(Debug, Clone, PartialEq, Eq)]
557pub struct Caller {
558    /// Its address, where replies go.
559    pub address: MailAddress,
560    /// The name it is known by.
561    pub name: String,
562}
563
564/// Why no session could be found behind a process.
565pub const CALLER_UNRESOLVED: &str = "Can't tell which session is running this command, so \
566    replies would have nowhere to go. Nothing was sent. Run it from your agent session's own \
567    shell tool.";
568
569/// The session behind a process, from its ancestry `pids` (nearest first):
570/// the first that owns a hosted runtime, a Claude session or a Codex
571/// conversation. Never declared by the caller; an environment id only
572/// corroborates, and a mismatch refuses.
573pub fn resolve_caller(homes: &HarnessHomes, pids: &[u32]) -> Result<Caller, String> {
574    let machine = local_machine_name();
575    let registry = read_registry(&registry_dir(homes));
576    let hosted = crate::runtime_mail::controlled_runtimes();
577    for &pid in pids {
578        if let Some(record) = hosted.iter().find(|record| record.pid == pid) {
579            let short: String = record.source.session_id.chars().take(8).collect();
580            return Ok(Caller {
581                address: MailAddress::new(
582                    &machine,
583                    &record.source.harness,
584                    &record.source.session_id,
585                )
586                .map_err(|error| error.to_string())?,
587                name: format!("{}-{short}@{machine}", record.source.harness),
588            });
589        }
590        if let Some(session) = registry.iter().find(|session| session.pid == pid) {
591            if let Ok(claimed) = std::env::var("CLAUDE_CODE_SESSION_ID") {
592                if !claimed.is_empty() && claimed != session.session_id {
593                    return Err(format!(
594                        "{CALLER_UNRESOLVED} (CLAUDE_CODE_SESSION_ID names {claimed}, but the Claude \
595                         process {pid} above this command is session {})",
596                        session.session_id
597                    ));
598                }
599            }
600            return Ok(Caller {
601                address: MailAddress::new(&machine, "claude-code", &session.session_id)
602                    .map_err(|error| error.to_string())?,
603                name: format!("{}@{machine}", session.name),
604            });
605        }
606        // Codex names the thread a command runs for (`CODEX_THREAD_ID`); the
607        // claim stands when this process holds that thread's rollout, as
608        // Codex's shared app-server daemon does for every thread it runs.
609        if let Some(thread) = std::env::var("CODEX_THREAD_ID")
610            .ok()
611            .filter(|thread| !thread.is_empty())
612            .filter(|thread| crate::codex_peer::holds_session(pid, thread))
613        {
614            return Ok(Caller {
615                address: MailAddress::new(&machine, "codex", &thread)
616                    .map_err(|error| error.to_string())?,
617                name: format!("{}@{machine}", codex_name(&thread)),
618            });
619        }
620        if let Some((session_id, _)) = crate::codex_peer::session_of_process(pid) {
621            return Ok(Caller {
622                address: MailAddress::new(&machine, "codex", &session_id)
623                    .map_err(|error| error.to_string())?,
624                name: format!("{}@{machine}", codex_name(&session_id)),
625            });
626        }
627    }
628    #[cfg(windows)]
629    if let Some(session) = msys_cut_claim(&registry, pids) {
630        return Ok(Caller {
631            address: MailAddress::new(&machine, "claude-code", &session.session_id)
632                .map_err(|error| error.to_string())?,
633            name: format!("{}@{machine}", session.name),
634        });
635    }
636    Err(format!(
637        "{CALLER_UNRESOLVED} (looked for this command's processes {pids:?} among {} Claude \
638         sessions in {} and {} hosted runtimes)",
639        registry.len(),
640        registry_dir(homes).display(),
641        hosted.len()
642    ))
643}
644
645/// Git Bash (MSYS) runs a command in a forked process that hands over to it. When the command is
646/// itself an MSYS program (a `sh` script, as npm's command shims are), the forked process exits once
647/// it has handed over, so the Windows parent chain is cut just above that shell and never reaches
648/// the Claude session running it. When the ancestry ends at exactly such a cut (its last pid is gone,
649/// the one before it is an MSYS shell), the session Claude names in `CLAUDE_CODE_SESSION_ID` stands
650/// if it is a live Claude session on this machine.
651#[cfg(windows)]
652fn msys_cut_claim<'a>(
653    registry: &'a [ClaudePeerSession],
654    pids: &[u32],
655) -> Option<&'a ClaudePeerSession> {
656    let table = process_table();
657    let [.., shell, cut] = pids else {
658        return None;
659    };
660    if table.contains_key(cut) {
661        return None;
662    }
663    let name = table.get(shell)?.1.to_ascii_lowercase();
664    if !matches!(name.as_str(), "sh.exe" | "bash.exe" | "dash.exe") {
665        return None;
666    }
667    let claimed = std::env::var("CLAUDE_CODE_SESSION_ID").ok()?;
668    registry
669        .iter()
670        .find(|session| !claimed.is_empty() && session.session_id == claimed)
671}
672
673/// This process's ancestry, nearest first (itself included).
674pub fn process_ancestry() -> Vec<u32> {
675    ancestry_of(std::process::id())
676}
677
678/// A process's ancestry, nearest first (itself included).
679pub fn ancestry_of(pid: u32) -> Vec<u32> {
680    let parents = parent_pids();
681    let mut chain = vec![pid];
682    let mut current = pid;
683    while let Some(&parent) = parents.get(&current) {
684        if parent <= 1 || chain.contains(&parent) {
685            break;
686        }
687        chain.push(parent);
688        current = parent;
689    }
690    chain
691}
692
693/// Every process's parent: pid → parent pid, from `ps`.
694#[cfg(not(windows))]
695fn parent_pids() -> std::collections::HashMap<u32, u32> {
696    let Ok(output) = std::process::Command::new("ps")
697        .args(["-axo", "pid=,ppid="])
698        .output()
699    else {
700        return Default::default();
701    };
702    String::from_utf8_lossy(&output.stdout)
703        .lines()
704        .filter_map(|line| {
705            let mut fields = line.split_whitespace();
706            Some((fields.next()?.parse().ok()?, fields.next()?.parse().ok()?))
707        })
708        .collect()
709}
710
711/// Every process's parent: pid → parent pid, from a process snapshot.
712#[cfg(windows)]
713fn parent_pids() -> std::collections::HashMap<u32, u32> {
714    process_table()
715        .into_iter()
716        .map(|(pid, (parent, _))| (pid, parent))
717        .collect()
718}
719
720/// Every process: pid → (parent pid, executable file name), from a process snapshot.
721#[cfg(windows)]
722fn process_table() -> std::collections::HashMap<u32, (u32, String)> {
723    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
724    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
725        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
726        TH32CS_SNAPPROCESS,
727    };
728
729    let mut parents = std::collections::HashMap::new();
730    let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
731    if snapshot == INVALID_HANDLE_VALUE {
732        return parents;
733    }
734    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
735    entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
736    let mut has_entry = unsafe { Process32FirstW(snapshot, &mut entry) } != 0;
737    while has_entry {
738        let length = entry
739            .szExeFile
740            .iter()
741            .position(|&unit| unit == 0)
742            .unwrap_or(entry.szExeFile.len());
743        let name = String::from_utf16_lossy(&entry.szExeFile[..length]);
744        parents.insert(entry.th32ProcessID, (entry.th32ParentProcessID, name));
745        has_entry = unsafe { Process32NextW(snapshot, &mut entry) } != 0;
746    }
747    unsafe {
748        CloseHandle(snapshot);
749    }
750    parents
751}
752
753/// Codex's user-level hooks file.
754pub fn codex_hooks_path() -> std::path::PathBuf {
755    std::env::var_os("CODEX_HOME")
756        .map(std::path::PathBuf::from)
757        .or_else(|| {
758            supercode_interchange::user_home()
759                .map(std::path::PathBuf::into_os_string)
760                .map(|home| std::path::PathBuf::from(home).join(".codex"))
761        })
762        .unwrap_or_else(|| std::path::PathBuf::from(".codex"))
763        .join("hooks.json")
764}
765
766/// Whether supercode's mail hook is in Codex's user hooks file. (Codex runs
767/// it only once its user has trusted it.)
768pub fn codex_user_hook_installed() -> bool {
769    std::fs::read_to_string(codex_hooks_path())
770        .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
771}
772
773/// Whether supercode's mail hook is in a project's Codex hooks file, in the
774/// session's directory or one above it.
775pub fn codex_project_hook_installed(cwd: &Path) -> bool {
776    cwd.ancestors().any(|directory| {
777        std::fs::read_to_string(directory.join(".codex").join("hooks.json"))
778            .is_ok_and(|text| text.contains(CODEX_HOOK_ARGUMENTS))
779    })
780}
781
782/// How a delivery ended.
783#[derive(Debug, Clone, PartialEq, Eq)]
784pub enum Delivered {
785    /// The receiver has it now: steered into a running turn.
786    Steered,
787    /// The receiver has it now: it started a turn in an idle session.
788    Started,
789    /// Claude reported it in the receiver's inbox; `busy` says whether the
790    /// receiver reads it at its next tool call (true) or it starts a turn.
791    Native {
792        /// True when the receiver was in a turn.
793        busy: bool,
794    },
795    /// Filed in the receiver's mailbox, which a hook points it at.
796    Hooked,
797    /// Filed in an idle receiver's mailbox, and its pane told to read it: a
798    /// turn has started, in which its hook shows it the message.
799    HookWoken,
800    /// Filed in the receiver's mailbox, waiting to be read.
801    Queued,
802    /// Filed with no door to show it.
803    Stored,
804    /// Filed in an operator's mailbox.
805    Operator,
806}
807
808/// A delivery refused before anything was sent.
809#[derive(Debug, Clone, PartialEq, Eq)]
810pub enum Refused {
811    /// `--queue` cannot hold a message for an idle Claude session: Claude
812    /// starts a turn for every message it delivers.
813    CannotQueueNative,
814    /// The relayed text would not fit one relay turn.
815    TooLong(usize),
816}
817
818/// Largest message relayed into a Claude session. The relay copies it into a
819/// model turn byte for byte, so it must fit comfortably in one.
820pub const MAX_RELAYED_BYTES: usize = 100_000;
821
822/// Deliver `envelope` to `to` through `door`. With `wake` false an idle
823/// receiver is not started. With `notify_when_idle` the sender gets one idle
824/// notice after the receiver's next turn ends.
825pub async fn deliver(
826    envelope: &Envelope,
827    to: &MailAddress,
828    door: &Door,
829    wake: bool,
830    notify_when_idle: bool,
831) -> Result<Result<Delivered, Refused>, String> {
832    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
833    // A runtime answers with its turn's final message, which the watcher
834    // sends back: not every runtime can run a command (a hosted agent may
835    // have no shell), and each can end a turn.
836    let mut final_reply = false;
837    let delivered = match door {
838        Door::Runtime(record) => {
839            let mut sent = envelope.clone();
840            let answers = matches!(envelope.reply_via, ReplyVia::Command);
841            if answers {
842                sent.reply_via = ReplyVia::FinalMessage {
843                    destination: envelope.from_name.clone(),
844                };
845            }
846            match deliver_to_runtime(record, sent.render(), wake).await? {
847                RuntimeDelivery::Steered => {
848                    mailbox
849                        .deliver_read(&sent)
850                        .map_err(|error| error.to_string())?;
851                    final_reply = answers;
852                    Delivered::Steered
853                }
854                RuntimeDelivery::Started => {
855                    mailbox
856                        .deliver_read(&sent)
857                        .map_err(|error| error.to_string())?;
858                    final_reply = answers;
859                    Delivered::Started
860                }
861                RuntimeDelivery::NotWoken => {
862                    mailbox
863                        .deliver(envelope)
864                        .map_err(|error| error.to_string())?;
865                    Delivered::Queued
866                }
867            }
868        }
869        Door::Native(session) => {
870            let busy = session.status != Some(ClaudePeerStatus::Idle);
871            if !wake && !busy {
872                return Ok(Err(Refused::CannotQueueNative));
873            }
874            // The same envelope every door delivers; Claude wraps it in its
875            // own, which names the relay. Its reply line names the door this
876            // session really has: its tools when it runs supercode's MCP server.
877            let mut envelope = envelope.clone();
878            if envelope.reply_via == ReplyVia::Command && has_message_tools(session.pid) {
879                envelope.reply_via = ReplyVia::Tool;
880            }
881            let envelope = &envelope;
882            let text = envelope.render();
883            if text.len() > MAX_RELAYED_BYTES {
884                return Ok(Err(Refused::TooLong(text.len())));
885            }
886            match send_through_relay(
887                &envelope.from,
888                &envelope.from_name,
889                &session.name,
890                text,
891                &envelope.id,
892            )
893            .await
894            {
895                RelayReceipt::Delivered { .. } => {
896                    mailbox
897                        .deliver_read(envelope)
898                        .map_err(|error| error.to_string())?;
899                    Delivered::Native { busy }
900                }
901                RelayReceipt::Failed { detail } => return Err(detail),
902            }
903        }
904        Door::Hook { pane, idle } => {
905            mailbox
906                .deliver(envelope)
907                .map_err(|error| error.to_string())?;
908            // its hooks run only inside a turn: an idle session is told, in its pane, to read its mailbox; the
909            // message itself reaches it as mail, never as its user's words
910            match pane {
911                Some(pane)
912                    if wake
913                        && *idle
914                        && submit_when_composer_empty(pane, CODEX_WAKE).await == Ok(true) =>
915                {
916                    Delivered::HookWoken
917                }
918                _ => Delivered::Hooked,
919            }
920        }
921        Door::Stored => {
922            mailbox
923                .deliver(envelope)
924                .map_err(|error| error.to_string())?;
925            Delivered::Stored
926        }
927        Door::Operator => {
928            mailbox
929                .deliver(envelope)
930                .map_err(|error| error.to_string())?;
931            Delivered::Operator
932        }
933    };
934    let notice = notify_when_idle && !matches!(door, Door::Operator);
935    if notice || final_reply {
936        let mut subscription = IdleSubscription::new(envelope.id.clone(), envelope.from.clone());
937        subscription.notice = notice;
938        subscription.final_reply = final_reply;
939        mailbox
940            .subscribe_idle(&subscription)
941            .map_err(|error| error.to_string())?;
942        // The watcher that settles it runs beside the machine daemon.
943        if let Ok(program) = supercode_program() {
944            crate::claude_relay::ensure_machine_daemon(&program)
945                .await
946                .ok();
947        }
948    }
949    Ok(Ok(delivered))
950}
951
952/// How the user's own turn reached its session.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub enum UserTurn {
955    /// A hosted runtime was in a turn; the words were steered into it.
956    Steered,
957    /// A hosted runtime was idle; the words started a turn.
958    Started,
959    /// Typed into the session's pane as its own submitted turn.
960    Typed,
961    /// The pane's composer holds a draft, or its program is not at its
962    /// composer: the turn waits in the session's mailbox and is typed once
963    /// the composer is empty.
964    Waiting,
965}
966
967impl UserTurn {
968    /// Stable wire spelling.
969    pub const fn as_str(self) -> &'static str {
970        match self {
971            Self::Steered => "steered",
972            Self::Started => "started",
973            Self::Typed => "typed",
974            Self::Waiting => "waiting",
975        }
976    }
977}
978
979/// The daemon pane a session runs in, when it runs in one.
980/// The choice or permission prompt a daemon pane's screen shows, as its lines (the question above
981/// it and its options), or `None`. The terminal substrate's own check (`classifyAttentionSignal`):
982/// a selector (❯ or ›) on a numbered option is a prompt blocked on an answer; the idle input line
983/// has no number after its selector.
984pub fn pane_prompt(pane: &str) -> Option<Vec<String>> {
985    #[cfg(unix)]
986    {
987        let output = std::process::Command::new("tmux")
988            .args(["capture-pane", "-p", "-t", &format!("{pane}:")])
989            .output()
990            .ok()?;
991        if !output.status.success() {
992            return None;
993        }
994        let screen = String::from_utf8_lossy(&output.stdout);
995        let lines: Vec<&str> = screen.lines().map(str::trim_end).collect();
996        let is_option = |line: &str| {
997            let line = line.trim_start();
998            let rest = line
999                .strip_prefix('❯')
1000                .or_else(|| line.strip_prefix('›'))
1001                .unwrap_or(line)
1002                .trim_start();
1003            let digits = rest.chars().take_while(char::is_ascii_digit).count();
1004            digits > 0 && matches!(rest[digits..].chars().next(), Some('.' | ')'))
1005        };
1006        let selected = lines.iter().position(|line| {
1007            let line = line.trim_start();
1008            (line.starts_with('❯') || line.starts_with('›')) && is_option(line)
1009        })?;
1010        // The prompt: the options' block of non-empty lines and the block above it (the question).
1011        let block_start = |end: usize| {
1012            lines[..end]
1013                .iter()
1014                .rposition(|line| line.trim().is_empty())
1015                .map_or(0, |blank| blank + 1)
1016        };
1017        let options = block_start(selected);
1018        let above = lines[..options]
1019            .iter()
1020            .rposition(|line| !line.trim().is_empty())
1021            .map(|last| block_start(last));
1022        let start = above.unwrap_or(options);
1023        let end = lines[selected..]
1024            .iter()
1025            .position(|line| line.trim().is_empty())
1026            .map_or(lines.len(), |blank| selected + blank);
1027        Some(
1028            lines[start..end]
1029                .iter()
1030                .map(|line| line.trim().to_string())
1031                .filter(|line| !line.is_empty())
1032                .take(20)
1033                .collect(),
1034        )
1035    }
1036    #[cfg(not(unix))]
1037    {
1038        let _ = pane;
1039        None
1040    }
1041}
1042
1043pub fn daemon_pane(session: &LiveSession) -> Option<String> {
1044    let name = session.tmux.as_deref()?.split(':').next()?;
1045    let rest = name.strip_prefix("p_")?;
1046    (!rest.is_empty()
1047        && rest
1048            .chars()
1049            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
1050    .then(|| name.to_string())
1051}
1052
1053/// Deliver the user's own turn to `to` through the one door that carries the
1054/// user's authority: a hosted runtime's own input, or the session's pane.
1055/// A session with neither (running outside supercode) is refused, never
1056/// reached as a peer instead. Callers hold the owner's authority already:
1057/// this is reached only through owner doors (the machine's own harness.v1).
1058pub async fn deliver_user_turn(
1059    homes: &HarnessHomes,
1060    envelope: &Envelope,
1061    to: &MailAddress,
1062) -> Result<UserTurn, String> {
1063    let session = LiveSessions::read(homes)
1064        .sessions
1065        .into_iter()
1066        .find(|session| &session.address == to)
1067        .ok_or_else(|| format!("{to} is not running; nothing was sent"))?;
1068    let mailbox = Mailbox::open(&mail_root(), to).map_err(|error| error.to_string())?;
1069    if let Door::Runtime(record) = &session.door {
1070        let delivered = deliver_to_runtime(record, envelope.body.clone(), true).await?;
1071        mailbox
1072            .deliver_read(envelope)
1073            .map_err(|error| error.to_string())?;
1074        return Ok(match delivered {
1075            RuntimeDelivery::Steered => UserTurn::Steered,
1076            _ => UserTurn::Started,
1077        });
1078    }
1079    let Some(pane) = daemon_pane(&session) else {
1080        let name = session.name.split('@').next().unwrap_or(&session.name);
1081        return Err(format!(
1082            "{name} runs outside supercode, where nothing can speak as its user. Open it in a \
1083             pane with `supercode open {name}`; nothing was sent."
1084        ));
1085    };
1086    mailbox
1087        .deliver(envelope)
1088        .map_err(|error| error.to_string())?;
1089    let typed = type_user_turns(&mailbox, &pane).await;
1090    Ok(if typed.contains(&envelope.id) {
1091        UserTurn::Typed
1092    } else {
1093        UserTurn::Waiting
1094    })
1095}
1096
1097/// Type the user's waiting turns into `pane`, oldest first, each only when
1098/// the pane's composer is empty. Stops at the first that has to wait.
1099/// Returns the ids typed.
1100pub async fn type_user_turns(mailbox: &Mailbox, pane: &str) -> Vec<String> {
1101    let mut typed = Vec::new();
1102    for waiting in mailbox.user_turns().unwrap_or_default() {
1103        // Claimed before it is typed: the machine's watcher and a direct delivery both type waiting turns, and
1104        // two typers filling one composer sent a turn's text twice in one prompt. A turn another typer holds is
1105        // that typer's, and so is every turn after it.
1106        let Ok(Some(stored)) = mailbox.claim_user_turn(&waiting) else {
1107            break;
1108        };
1109        match submit_when_composer_empty(pane, &stored.envelope.body).await {
1110            Ok(true) => {
1111                mailbox.acknowledge(&stored).ok();
1112                typed.push(stored.envelope.id.clone());
1113            }
1114            Ok(false) => {
1115                mailbox.release(&stored).ok();
1116                break;
1117            }
1118            Err(error) => {
1119                mailbox.release(&stored).ok();
1120                eprintln!(
1121                    "supercode: the user's turn {} for {} waits: {error}",
1122                    stored.envelope.id,
1123                    mailbox.address()
1124                );
1125                break;
1126            }
1127        }
1128    }
1129    typed
1130}
1131
1132/// What an idle hooked session's pane is given, to start the turn in which
1133/// its hook shows it the waiting mail.
1134pub const CODEX_WAKE: &str =
1135    "You have unread supercode messages. Read them with: supercode message inbox";
1136
1137/// The daemon's pane door: type `text` as a submitted turn if the composer
1138/// is empty now. `Ok(false)` when it holds a draft or is not on screen.
1139async fn submit_when_composer_empty(pane: &str, text: &str) -> Result<bool, String> {
1140    let entry = crate::teams_entry().map_err(|error| error.to_string())?;
1141    let node = std::env::var(crate::orchestrator_door::NODE_BIN_ENV)
1142        .ok()
1143        .filter(|value| !value.trim().is_empty())
1144        .unwrap_or_else(|| "node".into());
1145    let output = tokio::process::Command::new(node)
1146        .arg(entry)
1147        .args(["input", pane, text, "--when-composer-empty"])
1148        // A message is the session's own door, not a session acting on a pane: the pane doors read that from this
1149        // process's place under the daemon's `message watch`, not from anything named here.
1150        .env_remove("SUPERCODE_CALLER")
1151        .stdin(std::process::Stdio::null())
1152        .output()
1153        .await
1154        .map_err(|error| error.to_string())?;
1155    if !output.status.success() {
1156        return Err(crate::mailbox::error_line(&String::from_utf8_lossy(
1157            &output.stderr,
1158        )));
1159    }
1160    let answer: serde_json::Value =
1161        serde_json::from_slice(&output.stdout).map_err(|error| error.to_string())?;
1162    Ok(answer["delivered"] == true)
1163}