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