Skip to main content

supercode_harness/
claude_relay.rs

1//! Claude relays: the degraded tier's door into a Claude Code session that
2//! supercode does not control.
3//!
4//! A Claude session answers a message by copying its `from` into
5//! `SendMessage`. For that answer to come back, the message must come FROM a
6//! live Claude peer. A relay is that peer: a Claude Code runtime that
7//! supercode hosts like any other (`runtimes.start` in the machine daemon's
8//! `harness serve`, registered in the live-runtime registry), named
9//! `sc-<name>-on-<machine>`, sending on one session's behalf. Nothing here
10//! runs its own process supervisor or writes Claude's private socket frame.
11//!
12//! Three rules earn their place here:
13//!
14//! 1. **No model runs.** A relay's API is supercode's own deterministic
15//!    endpoint ([`crate::relay_endpoint`]), which answers a send turn with a
16//!    `SendMessage` of the queued pair. Every send is queued first, and a
17//!    PreToolUse hook (`supercode message gate`) still denies any tool call
18//!    but a `SendMessage` of exactly that pair.
19//! 2. **Receipts come from Claude, through hooks.** A PostToolUse hook writes
20//!    Claude's own `SendMessage` result beside the queue; a denied call and a
21//!    turn that ends without sending write theirs too. The sender waits on
22//!    that file, not on the model's words.
23//! 3. **Inbound mail never reaches the model.** Claude hands every inbound
24//!    peer envelope and idle or delivery notice to the relay's
25//!    `UserPromptSubmit` hook byte-exact; the hook files it in the represented
26//!    session's mailbox and blocks the prompt, so no model turn runs for it
27//!    (measured: `duration_api_ms: 0`).
28//!
29//! A relay's busy/idle is its own; its name carries the `sc-` prefix and
30//! every turn ends with [`RELAY_STATUS_LINE`].
31
32use std::collections::{BTreeMap, HashMap};
33use std::path::{Path, PathBuf};
34use std::time::{Duration, Instant};
35
36use serde::{Deserialize, Serialize};
37use serde_json::{json, Value};
38
39use crate::claude_peer::{read_registry, registry_dir, ClaudePeerSession};
40use crate::mailbox::{mail_root, Envelope, MailAddress, MailKind, ReplyVia};
41use crate::HarnessHomes;
42
43/// Model name a relay's requests carry. The relay endpoint answers them
44/// without any model.
45pub const RELAY_MODEL: &str = "haiku";
46
47/// Prefix marking a registry name as a relay rather than a session.
48pub const RELAY_NAME_PREFIX: &str = "sc-";
49
50/// Text every relay turn ends with. Claude quotes a session's last line in
51/// its idle notices, so this is where the correction reaches the agent.
52pub const RELAY_STATUS_LINE: &str = "relay, not the session's status";
53
54/// How long a send waits for Claude's own receipt.
55pub const SEND_TIMEOUT: Duration = Duration::from_secs(90);
56
57/// Tools a relay may touch.
58const RELAY_TOOLS: &str = "ListAgents,SendMessage";
59
60/// Line Claude opens a delivered peer message with in a turn. The hook sees
61/// the envelope itself; one of the two starts is required, so text that
62/// merely quotes an envelope further in is never read as mail.
63const NATIVE_PEER_PREAMBLE: &str = "Another Claude session sent a message:";
64/// Tags of Claude's peer envelope.
65const NATIVE_PEER_OPENING: &str = "<cross-session-message ";
66const NATIVE_PEER_CLOSING: &str = "</cross-session-message>";
67const NATIVE_IDLE_NOTICE: &str = "[Cross-session idle notice]";
68const NATIVE_DELIVERY_NOTICE: &str = "[Cross-session delivery notice]";
69
70/// Registry name of the relay that represents `name` on `machine`.
71///
72/// Not `name@machine`: Claude accepts `@` in `--name`, but its `SendMessage`
73/// refuses a `to` containing `@` ("must be a bare teammate name").
74pub fn relay_name(name: &str, machine: &str) -> String {
75    let base = name.strip_prefix(RELAY_NAME_PREFIX).unwrap_or(name);
76    format!("{RELAY_NAME_PREFIX}{base}-on-{machine}")
77}
78
79/// The one send a relay is allowed to make next.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct QueuedSend {
82    /// Registry name of the receiving Claude session.
83    pub to: String,
84    /// Exact message text.
85    pub message: String,
86}
87
88/// Decide one PreToolUse hook call. `None` allows it; `Some(reason)` denies.
89///
90/// Only a `SendMessage` whose `to` and `message` equal the queued pair is
91/// allowed; `ListAgents` is read-only and always allowed; anything else, or a
92/// send with nothing queued, is denied.
93pub fn gate_decision(hook_input: &Value, queued: Option<&QueuedSend>) -> Option<String> {
94    let tool = hook_input
95        .get("tool_name")
96        .and_then(Value::as_str)
97        .unwrap_or_default();
98    if tool == "ListAgents" {
99        return None;
100    }
101    if tool != "SendMessage" {
102        return Some(format!("a relay may not use {tool}"));
103    }
104    let Some(queued) = queued else {
105        return Some(
106            "nothing is queued to send; mail for the host is not answered by the relay".into(),
107        );
108    };
109    let input = hook_input.get("tool_input").cloned().unwrap_or(Value::Null);
110    let to = input.get("to").and_then(Value::as_str).unwrap_or_default();
111    let message = input
112        .get("message")
113        .and_then(Value::as_str)
114        .unwrap_or_default();
115    if to != queued.to {
116        return Some(format!(
117            "not the queued outbound message: `to` is {to:?}, the queue says {:?}",
118            queued.to
119        ));
120    }
121    if message != queued.message {
122        let at = message
123            .char_indices()
124            .zip(queued.message.chars())
125            .find(|((_, sent), queued)| sent != queued)
126            .map(|((index, _), _)| index)
127            .unwrap_or_else(|| message.len().min(queued.message.len()));
128        return Some(format!(
129            "not the queued outbound message: `message` ({} bytes) differs from the queue ({} \
130             bytes) at byte {at}: sent {:?}, queued {:?}",
131            message.len(),
132            queued.message.len(),
133            message
134                .get(at..)
135                .unwrap_or_default()
136                .chars()
137                .take(40)
138                .collect::<String>(),
139            queued
140                .message
141                .get(at..)
142                .unwrap_or_default()
143                .chars()
144                .take(40)
145                .collect::<String>(),
146        ));
147    }
148    None
149}
150
151/// The hook's JSON answer for a denial.
152pub fn gate_denial(reason: &str) -> Value {
153    json!({
154        "hookSpecificOutput": {
155            "hookEventName": "PreToolUse",
156            "permissionDecision": "deny",
157            "permissionDecisionReason": reason,
158        }
159    })
160}
161
162/// Files of one relay, all in its own directory (also its working directory,
163/// which holds no project settings).
164#[derive(Debug, Clone)]
165pub struct RelayPaths {
166    /// The relay's directory.
167    pub directory: PathBuf,
168    /// The single queued send the gate compares against.
169    pub queue: PathBuf,
170    /// Claude's answer to the queued send, written by the relay's hooks.
171    pub receipt: PathBuf,
172    /// The prompt that began the relay's current turn, written as the turn starts: a turn's end
173    /// answers the queued send only when that send began it.
174    pub turn: PathBuf,
175    /// Settings passed with `--settings`, carrying the hooks.
176    pub settings: PathBuf,
177    /// The hosted runtime this relay runs as.
178    pub record: PathBuf,
179    /// Newest message id sent to each Claude session name, for threading.
180    pub sent: PathBuf,
181    /// Serializes sends through this relay.
182    pub lock: PathBuf,
183}
184
185impl RelayPaths {
186    /// Paths of the relay named `relay_name` under `root`.
187    pub fn new(root: &Path, relay_name: &str) -> Self {
188        let hash = blake3::hash(relay_name.as_bytes()).to_hex();
189        Self::in_directory(root.join("relays").join(&hash[..24]))
190    }
191
192    /// Paths of the relay whose directory is `directory`.
193    pub fn in_directory(directory: PathBuf) -> Self {
194        Self {
195            queue: directory.join("queue.json"),
196            receipt: directory.join("receipt.json"),
197            turn: directory.join("turn.txt"),
198            settings: directory.join("settings.json"),
199            record: directory.join("relay.json"),
200            sent: directory.join("sent.json"),
201            lock: directory.join("send.lock"),
202            directory,
203        }
204    }
205
206    /// Newest message id sent to each Claude session name.
207    pub fn last_sent(&self) -> HashMap<String, String> {
208        std::fs::read(&self.sent)
209            .ok()
210            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
211            .unwrap_or_default()
212    }
213}
214
215/// Everything needed to start one relay.
216#[derive(Debug, Clone)]
217pub struct RelaySpec {
218    /// Session the relay speaks for.
219    pub represented: MailAddress,
220    /// Name the represented session is known by.
221    pub represented_name: String,
222    /// Registry name the relay registers under.
223    pub name: String,
224    /// Relay files.
225    pub paths: RelayPaths,
226    /// Program run by the hooks (this supercode binary).
227    pub program: PathBuf,
228}
229
230impl RelaySpec {
231    /// The relay that speaks for `represented`.
232    pub fn for_sender(represented: &MailAddress, represented_name: &str) -> std::io::Result<Self> {
233        let base = represented_name
234            .split('@')
235            .next()
236            .unwrap_or(represented_name);
237        let name = relay_name(base, &represented.machine);
238        Ok(Self {
239            represented: represented.clone(),
240            represented_name: represented_name.to_string(),
241            paths: RelayPaths::new(&mail_root(), &name),
242            name,
243            program: supercode_program()?,
244        })
245    }
246}
247
248/// Arguments of the Claude Code runtime a relay runs as.
249///
250/// `--setting-sources project` in an empty directory keeps user hooks and
251/// settings out; `--settings` then adds only the relay's hooks. The API is
252/// the relay endpoint, through the environment ([`relay_environment`]).
253pub fn relay_arguments(spec: &RelaySpec) -> Vec<String> {
254    vec![
255        "--print".into(),
256        "--input-format".into(),
257        "stream-json".into(),
258        "--output-format".into(),
259        "stream-json".into(),
260        "--verbose".into(),
261        "--permission-prompt-tool".into(),
262        "stdio".into(),
263        "--model".into(),
264        RELAY_MODEL.into(),
265        "--name".into(),
266        spec.name.clone(),
267        "--permission-mode".into(),
268        "bypassPermissions".into(),
269        "--setting-sources".into(),
270        "project".into(),
271        "--settings".into(),
272        spec.paths.settings.to_string_lossy().into_owned(),
273        "--tools".into(),
274        RELAY_TOOLS.into(),
275        "--no-session-persistence".into(),
276    ]
277}
278
279/// Environment of a relay: its API is the relay endpoint at `endpoint`, and
280/// its API key names its directory there. The key also keeps account
281/// connectors (MCP servers) out of the relay.
282pub fn relay_environment(spec: &RelaySpec, endpoint: &str) -> BTreeMap<String, String> {
283    let key = spec
284        .paths
285        .directory
286        .file_name()
287        .map(|name| name.to_string_lossy().into_owned())
288        .unwrap_or_default();
289    BTreeMap::from([
290        ("ANTHROPIC_BASE_URL".to_string(), endpoint.to_string()),
291        ("ANTHROPIC_API_KEY".to_string(), key),
292        (
293            "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
294            "1".to_string(),
295        ),
296    ])
297}
298
299/// Settings document installing a relay's hooks.
300pub fn relay_settings(spec: &RelaySpec) -> Value {
301    let program = shell_quote(&spec.program.to_string_lossy());
302    let directory = shell_quote(&spec.paths.directory.to_string_lossy());
303    let represented = shell_quote(&spec.represented.to_string());
304    let command = |verb: &str| format!("{program} message {verb} {directory}");
305    json!({
306        "hooks": {
307            // Every tool, not only the two named in --tools.
308            "PreToolUse": [{
309                "matcher": ".*",
310                "hooks": [{"type": "command", "command": command("gate")}],
311            }],
312            "PostToolUse": [{
313                "matcher": "SendMessage",
314                "hooks": [{"type": "command", "command": command("relay-receipt")}],
315            }],
316            // A SendMessage that fails fires this, with Claude Code's own error.
317            "PostToolUseFailure": [{
318                "matcher": "SendMessage",
319                "hooks": [{"type": "command", "command": command("relay-receipt")}],
320            }],
321            "Stop": [{
322                "hooks": [{"type": "command", "command": command("relay-receipt")}],
323            }],
324            // A turn an API error ends (a usage limit, an overload) fires this, not Stop.
325            "StopFailure": [{
326                "hooks": [{"type": "command", "command": command("relay-receipt")}],
327            }],
328            "UserPromptSubmit": [{
329                "hooks": [{
330                    "type": "command",
331                    "command": format!("{program} message relay-inbound {represented} {directory}"),
332                }],
333            }],
334        }
335    })
336}
337
338fn shell_quote(value: &str) -> String {
339    format!("'{}'", value.replace('\'', "'\\''"))
340}
341
342/// Whether a prompt Claude handed the relay is inbound mail (a peer envelope
343/// or a notice) rather than its host's own send turn.
344pub fn is_inbound_prompt(prompt: &str) -> bool {
345    let trimmed = prompt.trim_start();
346    trimmed.starts_with(NATIVE_PEER_OPENING)
347        || trimmed.starts_with(NATIVE_IDLE_NOTICE)
348        || trimmed.starts_with(NATIVE_DELIVERY_NOTICE)
349}
350
351/// The UserPromptSubmit answer that keeps a prompt from the model.
352pub fn inbound_block() -> Value {
353    json!({
354        "decision": "block",
355        "reason": "filed in the mailbox of the session this relay speaks for",
356    })
357}
358
359/// The host turn asking a relay to make one send.
360pub fn send_turn(send: &QueuedSend) -> String {
361    format!(
362        "Send one message with SendMessage.\n\
363         to: {}\n\
364         message: the exact text between the markers, without the markers\n\
365         ---BEGIN MESSAGE---\n{}\n---END MESSAGE---",
366        send.to, send.message
367    )
368}
369
370/// A native peer envelope as Claude delivered it to a relay.
371#[derive(Debug, Clone, PartialEq, Eq)]
372pub struct NativeEnvelope {
373    /// Claude's `from` (the sender's socket, `uds:/tmp/cc-socks/<pid>.sock`).
374    pub from: String,
375    /// Claude's `from-name`.
376    pub from_name: Option<String>,
377    /// Message body, unescaped as Claude delivered it.
378    pub body: String,
379}
380
381/// One inbound prompt, as Claude handed it to a relay's hook.
382#[derive(Debug, Clone, PartialEq, Eq)]
383pub enum RelayEvent {
384    /// A peer message arrived.
385    Peer(NativeEnvelope),
386    /// A `[Cross-session idle notice]`.
387    IdleNotice(String),
388    /// A `[Cross-session delivery notice]`.
389    DeliveryNotice(String),
390}
391
392/// The live Claude session behind a native `uds:` sender address.
393pub fn resolve_native_sender(
394    registry: &[ClaudePeerSession],
395    native_from: &str,
396) -> Option<ClaudePeerSession> {
397    let socket = native_from.strip_prefix("uds:").unwrap_or(native_from);
398    registry
399        .iter()
400        .find(|session| session.socket_path.to_string_lossy() == socket)
401        .cloned()
402}
403
404/// Outcome of one relayed send, as the sender reads it.
405#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
406#[serde(rename_all = "snake_case", tag = "outcome")]
407pub enum RelayReceipt {
408    /// Claude reported the message queued in the receiver's inbox.
409    Delivered {
410        /// Claude's own result text.
411        detail: String,
412        /// Claude's message id, when it reported one.
413        native_msg_id: Option<String>,
414    },
415    /// The send did not happen.
416    Failed {
417        /// Why, in words the sending agent can act on.
418        detail: String,
419    },
420}
421
422/// Read a receipt the relay's hooks wrote: Claude's own `SendMessage`
423/// result, a gate denial, or a turn that ended without sending.
424pub fn read_receipt(value: &Value) -> RelayReceipt {
425    if let Some(reason) = value.get("denied").and_then(Value::as_str) {
426        return RelayReceipt::Failed {
427            detail: format!("the relay's gate refused the send: {reason}"),
428        };
429    }
430    if let Some(error) = value.get("send_failed").and_then(Value::as_str) {
431        return RelayReceipt::Failed {
432            detail: format!("Claude Code refused the relay's send: {}", error.trim()),
433        };
434    }
435    if value.get("turn_ended").and_then(Value::as_bool) == Some(true) {
436        let said = value
437            .get("said")
438            .and_then(Value::as_str)
439            .filter(|said| !said.trim().is_empty())
440            .map(|said| format!("; it said: {}", said.trim()))
441            .unwrap_or_default();
442        return RelayReceipt::Failed {
443            detail: format!(
444                "the Claude relay ended its turn without sending; nothing was sent{said}"
445            ),
446        };
447    }
448    let response = value.get("tool_response").cloned().unwrap_or(Value::Null);
449    let parsed = match &response {
450        Value::String(text) => serde_json::from_str::<Value>(text).unwrap_or(response.clone()),
451        Value::Array(blocks) => blocks
452            .iter()
453            .find_map(|block| block.get("text").and_then(Value::as_str))
454            .and_then(|text| serde_json::from_str::<Value>(text).ok())
455            .unwrap_or(response.clone()),
456        _ => response.clone(),
457    };
458    if parsed.get("success").and_then(Value::as_bool) != Some(true) {
459        return RelayReceipt::Failed {
460            detail: format!("Claude did not report the send as successful: {parsed}"),
461        };
462    }
463    RelayReceipt::Delivered {
464        detail: parsed
465            .get("message")
466            .and_then(Value::as_str)
467            .unwrap_or_default()
468            .to_string(),
469        native_msg_id: parsed
470            .get("msg_id")
471            .and_then(Value::as_str)
472            .map(str::to_string),
473    }
474}
475
476/// Send `message` to the Claude session named `to`, from `sender` through
477/// its relay: start the relay as a hosted runtime when it is not running,
478/// queue the send, hand it the send turn through the runtime's own door, and
479/// wait for Claude's receipt.
480pub async fn send_through_relay(
481    sender: &MailAddress,
482    sender_name: &str,
483    to: &str,
484    message: String,
485    message_id: &str,
486) -> RelayReceipt {
487    let failed = |detail: String| RelayReceipt::Failed { detail };
488    let spec = match RelaySpec::for_sender(sender, sender_name) {
489        Ok(spec) => spec,
490        Err(error) => return failed(error.to_string()),
491    };
492    if let Err(error) = std::fs::create_dir_all(&spec.paths.directory) {
493        return failed(error.to_string());
494    }
495    // One send at a time through one relay: the queue file is the gate.
496    let lock = match tokio::task::spawn_blocking({
497        let path = spec.paths.lock.clone();
498        move || SendLock::acquire(&path)
499    })
500    .await
501    {
502        Ok(Ok(lock)) => lock,
503        Ok(Err(error)) => return failed(format!("could not take the relay's send lock: {error}")),
504        Err(error) => return failed(error.to_string()),
505    };
506    let runtime = match ensure_relay_runtime(&spec).await {
507        Ok(runtime) => runtime,
508        Err(detail) => return failed(detail),
509    };
510    let queued = QueuedSend {
511        to: to.to_string(),
512        message,
513    };
514    std::fs::remove_file(&spec.paths.receipt).ok();
515    if let Err(error) = std::fs::write(
516        &spec.paths.queue,
517        serde_json::to_vec(&queued).unwrap_or_default(),
518    ) {
519        return failed(error.to_string());
520    }
521    let delivered =
522        crate::runtime_mail::deliver_to_runtime(&runtime, send_turn(&queued), true).await;
523    let receipt = match delivered {
524        Err(detail) => failed(format!("could not reach the Claude relay: {detail}")),
525        Ok(_) => wait_for_receipt(&spec.paths.receipt).await,
526    };
527    std::fs::remove_file(&spec.paths.queue).ok();
528    if matches!(receipt, RelayReceipt::Delivered { .. }) {
529        let mut sent = spec.paths.last_sent();
530        sent.insert(to.to_string(), message_id.to_string());
531        std::fs::write(
532            &spec.paths.sent,
533            serde_json::to_vec(&sent).unwrap_or_default(),
534        )
535        .ok();
536    }
537    drop(lock);
538    receipt
539}
540
541async fn wait_for_receipt(path: &Path) -> RelayReceipt {
542    let started = Instant::now();
543    while started.elapsed() < SEND_TIMEOUT {
544        if let Some(value) = std::fs::read(path)
545            .ok()
546            .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
547        {
548            return read_receipt(&value);
549        }
550        tokio::time::sleep(Duration::from_millis(200)).await;
551    }
552    RelayReceipt::Failed {
553        detail: format!(
554            "the Claude relay did not confirm the send within {} seconds; it may still arrive",
555            SEND_TIMEOUT.as_secs()
556        ),
557    }
558}
559
560/// The relay's hosted runtime, started in the machine daemon when it is not
561/// running.
562async fn ensure_relay_runtime(
563    spec: &RelaySpec,
564) -> Result<crate::live_runtime::LiveRuntimeRecord, String> {
565    #[derive(Serialize, Deserialize)]
566    struct Record {
567        runtime_id: String,
568        #[serde(default)]
569        endpoint: String,
570        /// The machine daemon's connection to the runtime: the door that closes it.
571        #[serde(default)]
572        connection: String,
573    }
574    let endpoint = relay_endpoint(&spec.program).await?;
575    // Written on every send, not only at start: Claude Code reloads a changed settings file, so
576    // a running relay takes the hooks this supercode installs.
577    std::fs::write(
578        &spec.paths.settings,
579        serde_json::to_vec_pretty(&relay_settings(spec)).unwrap_or_default(),
580    )
581    .map_err(|error| error.to_string())?;
582    if let Some(record) = std::fs::read(&spec.paths.record)
583        .ok()
584        .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok())
585    {
586        if let Some(runtime) =
587            crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id)
588        {
589            if record.endpoint == endpoint {
590                return Ok(runtime);
591            }
592            // Started against an endpoint no longer serving, its requests
593            // would go nowhere: it ends, and a new one starts.
594            end_relay_process(&spec.name);
595        }
596    }
597    let params = json!({
598        "harness": "claude-code",
599        "launch": {
600            "program": "claude",
601            "arguments": relay_arguments(spec),
602            "env": relay_environment(spec, &endpoint),
603        },
604        "cwd": spec.paths.directory,
605    });
606    let result = machine_rpc(&spec.program, "runtimes.start", &params).await?;
607    let runtime_id = result
608        .pointer("/handle/runtime_id")
609        .and_then(Value::as_str)
610        .ok_or_else(|| format!("the machine daemon did not start the relay: {result}"))?
611        .to_string();
612    let connection = result
613        .get("connection")
614        .and_then(Value::as_str)
615        .unwrap_or_default()
616        .to_string();
617    std::fs::write(
618        &spec.paths.record,
619        serde_json::to_vec(&Record {
620            runtime_id: runtime_id.clone(),
621            endpoint,
622            connection,
623        })
624        .unwrap_or_default(),
625    )
626    .map_err(|error| error.to_string())?;
627    crate::runtime_mail::controlled_runtime("claude-code", &runtime_id)
628        .ok_or_else(|| "the relay started but registered no live runtime".to_string())
629}
630
631/// The relays of sessions no longer running, retired: each relay's runtime (a `claude --print` under
632/// `supercode harness serve`, some hundreds of MB) is closed through the machine daemon that
633/// started it (`runtimes.close`, so the daemon's own table forgets it: a relay process ended behind
634/// its back left sends failing until the daemon restarted), and its folder removed. A relay speaks
635/// for one session and receives the replies to what that session sent; once the session has ended,
636/// nothing reaches it. A relay for a board or an operator, which is not a session, is kept; so is a
637/// live relay recorded before its connection was kept, which no door can close cleanly.
638/// Answers the represented addresses whose relays were retired.
639pub async fn retire_relays_of_ended_sessions(homes: &HarnessHomes) -> Vec<String> {
640    #[derive(Deserialize)]
641    struct Record {
642        runtime_id: String,
643        #[serde(default)]
644        connection: String,
645    }
646    let Ok(entries) = std::fs::read_dir(mail_root().join("relays")) else {
647        return Vec::new();
648    };
649    let running: std::collections::HashSet<String> = crate::mail_route::LiveSessions::read(homes)
650        .all()
651        .iter()
652        .map(|session| session.address.to_string())
653        .collect();
654    let Ok(program) = supercode_program() else {
655        return Vec::new();
656    };
657    let mut retired = Vec::new();
658    for entry in entries.flatten() {
659        let paths = RelayPaths::in_directory(entry.path());
660        // the address the relay speaks for, as its inbound hook names it
661        let Some(represented) = std::fs::read_to_string(&paths.settings)
662            .ok()
663            .and_then(|text| {
664                let from = text.find("relay-inbound '")? + "relay-inbound '".len();
665                let len = text[from..].find('\'')?;
666                MailAddress::parse(&text[from..from + len]).ok()
667            })
668        else {
669            continue;
670        };
671        if matches!(represented.harness.as_str(), "board" | "operator")
672            || running.contains(&represented.to_string())
673        {
674            continue;
675        }
676        let record = std::fs::read(&paths.record)
677            .ok()
678            .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok());
679        let alive = record.as_ref().is_some_and(|record| {
680            crate::runtime_mail::controlled_runtime("claude-code", &record.runtime_id).is_some()
681        });
682        if alive {
683            let connection = record.map(|record| record.connection).unwrap_or_default();
684            if connection.is_empty()
685                || machine_rpc(
686                    &program,
687                    "runtimes.close",
688                    &json!({ "connection": connection }),
689                )
690                .await
691                .is_err()
692            {
693                continue;
694            }
695        }
696        if std::fs::remove_dir_all(&paths.directory).is_ok() {
697            retired.push(represented.to_string());
698        }
699    }
700    retired
701}
702
703/// End the Claude process registered under the relay name `name`.
704fn end_relay_process(name: &str) {
705    let registry = registry_dir(&HarnessHomes::default());
706    for session in read_registry(&registry) {
707        #[cfg(unix)]
708        if session.name == name {
709            // SAFETY: `kill` only sends a signal to the relay's own process.
710            unsafe {
711                libc::kill(session.pid as libc::pid_t, libc::SIGTERM);
712            }
713        }
714    }
715}
716
717/// The relay endpoint's base URL. The machine daemon's watcher serves it;
718/// the daemon is started when it is not running.
719async fn relay_endpoint(program: &Path) -> Result<String, String> {
720    if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
721        return Ok(url);
722    }
723    ensure_machine_daemon(program).await?;
724    let deadline = Instant::now() + Duration::from_secs(10);
725    while Instant::now() < deadline {
726        if let Some(url) = crate::relay_endpoint::relay_endpoint_url() {
727            return Ok(url);
728        }
729        tokio::time::sleep(Duration::from_millis(200)).await;
730    }
731    Err(
732        "the relay endpoint is not answering; the machine daemon's `supercode message watch` \
733         serves it (see mail/machine-daemon.log)"
734            .into(),
735    )
736}
737
738/// One `harness.v1` call into this machine's daemon (`supercode teams rpc`),
739/// starting the daemon when it is not running.
740pub async fn machine_rpc(program: &Path, method: &str, params: &Value) -> Result<Value, String> {
741    let call = || {
742        let mut command = tokio::process::Command::new(program);
743        command
744            .args(["teams", "rpc", method, &params.to_string()])
745            .stdin(std::process::Stdio::null())
746            .stdout(std::process::Stdio::piped())
747            .stderr(std::process::Stdio::piped());
748        command.output()
749    };
750    let output = call().await.map_err(|error| error.to_string())?;
751    if output.status.success() {
752        return serde_json::from_slice(&output.stdout)
753            .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
754    }
755    // Not running: start it (this OS user's own daemon, no Teams context
756    // needed) and ask once more.
757    ensure_machine_daemon(program).await?;
758    let output = call().await.map_err(|error| error.to_string())?;
759    if output.status.success() {
760        return serde_json::from_slice(&output.stdout)
761            .map_err(|error| format!("unreadable answer from the machine daemon: {error}"));
762    }
763    Err(error_line(&String::from_utf8_lossy(&output.stderr)))
764}
765
766/// Start this OS user's machine daemon when it is not answering. It hosts
767/// relays (in its `harness serve`) and the idle watcher.
768pub async fn ensure_machine_daemon(program: &Path) -> Result<(), String> {
769    let describe = || {
770        tokio::process::Command::new(program)
771            .args(["teams", "describe"])
772            .stdin(std::process::Stdio::null())
773            .stdout(std::process::Stdio::null())
774            .stderr(std::process::Stdio::null())
775            .status()
776    };
777    if describe().await.is_ok_and(|status| status.success()) {
778        return Ok(());
779    }
780    // A service manager runs this user's daemon (a connector, or the machine
781    // unit): it is between restarts, and a daemon started here would take the
782    // socket and lock the service's daemon out. Wait for the service instead.
783    if crate::teams::service_owns_daemon() {
784        for _ in 0..100 {
785            tokio::time::sleep(Duration::from_millis(200)).await;
786            if describe().await.is_ok_and(|status| status.success()) {
787                return Ok(());
788            }
789        }
790        return Err(
791            "this machine's daemon is run by its service manager and did not answer within 20 seconds; \
792             see `supercode teams status`"
793                .into(),
794        );
795    }
796    let root = mail_root();
797    std::fs::create_dir_all(&root).map_err(|error| error.to_string())?;
798    let log = std::fs::OpenOptions::new()
799        .create(true)
800        .append(true)
801        .open(root.join("machine-daemon.log"))
802        .map_err(|error| error.to_string())?;
803    let mut command = std::process::Command::new(program);
804    command
805        .args(["teams", "machine", "start", "--supercode"])
806        .arg(program)
807        .stdin(std::process::Stdio::null())
808        .stdout(log.try_clone().map_err(|error| error.to_string())?)
809        .stderr(log);
810    #[cfg(unix)]
811    {
812        use std::os::unix::process::CommandExt;
813        // Its own process group, so the caller's exit does not take the
814        // daemon (and every relay) with it.
815        command.process_group(0);
816    }
817    command
818        .spawn()
819        .map_err(|error| format!("could not start the machine daemon: {error}"))?;
820    for _ in 0..50 {
821        tokio::time::sleep(Duration::from_millis(200)).await;
822        if describe().await.is_ok_and(|status| status.success()) {
823            return Ok(());
824        }
825    }
826    Err(format!(
827        "the machine daemon did not start within 10 seconds; see {}",
828        root.join("machine-daemon.log").display()
829    ))
830}
831
832/// The one line of a failed command's stderr an agent can act on.
833fn error_line(stderr: &str) -> String {
834    let lines: Vec<&str> = stderr
835        .lines()
836        .map(str::trim)
837        .filter(|line| !line.is_empty())
838        .collect();
839    lines
840        .iter()
841        .find(|line| line.starts_with("Error") || line.starts_with("error"))
842        .or(lines.last())
843        .copied()
844        .unwrap_or("the machine daemon failed without saying why")
845        .chars()
846        .take(300)
847        .collect()
848}
849
850/// An exclusive lock on a relay's sends, released on drop.
851struct SendLock {
852    _file: std::fs::File,
853}
854
855impl SendLock {
856    fn acquire(path: &Path) -> std::io::Result<Self> {
857        let file = std::fs::OpenOptions::new()
858            .create(true)
859            .truncate(false)
860            .write(true)
861            .open(path)?;
862        #[cfg(unix)]
863        {
864            use std::os::unix::io::AsRawFd;
865            // SAFETY: flock on a descriptor this function owns; the lock is
866            // released when the file is dropped.
867            if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
868                return Err(std::io::Error::last_os_error());
869            }
870        }
871        Ok(Self { _file: file })
872    }
873}
874
875/// File one inbound prompt in `represented`'s mailbox. `last_sent` maps a
876/// Claude session name to the newest message this relay sent it, for
877pub fn file_inbound_prompt(
878    homes: &HarnessHomes,
879    represented: &MailAddress,
880    prompt: &str,
881    last_sent: Option<&HashMap<String, String>>,
882) {
883    match parse_inbound_text(prompt) {
884        Some(RelayEvent::Peer(native)) => {
885            let registry = read_registry(&registry_dir(homes));
886            let sender = resolve_native_sender(&registry, &native.from);
887            let in_reply_to = sender
888                .as_ref()
889                .and_then(|session| last_sent.and_then(|sent| sent.get(&session.name).cloned()));
890            file_inbound(represented, &native, sender.as_ref(), in_reply_to);
891        }
892        Some(RelayEvent::IdleNotice(text) | RelayEvent::DeliveryNotice(text)) => {
893            file_notice(represented, &text);
894        }
895        _ => {}
896    }
897}
898/// Recognize an inbound peer envelope or notice in the text Claude handed a
899/// relay.
900pub fn parse_inbound_text(text: &str) -> Option<RelayEvent> {
901    let trimmed = text.trim_start();
902    if trimmed.starts_with(NATIVE_IDLE_NOTICE) {
903        return Some(RelayEvent::IdleNotice(trimmed.to_string()));
904    }
905    if trimmed.starts_with(NATIVE_DELIVERY_NOTICE) {
906        return Some(RelayEvent::DeliveryNotice(trimmed.to_string()));
907    }
908    if !trimmed.starts_with(NATIVE_PEER_PREAMBLE) && !trimmed.starts_with(NATIVE_PEER_OPENING) {
909        return None;
910    }
911    let start = text.find(NATIVE_PEER_OPENING)?;
912    let header_end = start + text[start..].find(">\n")?;
913    let header = &text[start + NATIVE_PEER_OPENING.len()..header_end];
914    let body_start = header_end + 2;
915    // The body is not escaped by Claude; the closing tag is the LAST one, and
916    // the fixed paragraph after it never contains the tag.
917    let body_end = text.rfind(&format!("\n{NATIVE_PEER_CLOSING}"))?;
918    if body_end < body_start {
919        return None;
920    }
921    let attributes = parse_attributes(header);
922    Some(RelayEvent::Peer(NativeEnvelope {
923        from: attributes.get("from")?.clone(),
924        from_name: attributes.get("from-name").cloned(),
925        body: text[body_start..body_end].to_string(),
926    }))
927}
928fn parse_attributes(header: &str) -> BTreeMap<String, String> {
929    let mut attributes = BTreeMap::new();
930    let mut rest = header;
931    while let Some(equals) = rest.find("=\"") {
932        let key = rest[..equals].trim().to_string();
933        let value_start = equals + 2;
934        let Some(length) = rest[value_start..].find('"') else {
935            break;
936        };
937        attributes.insert(key, rest[value_start..value_start + length].to_string());
938        rest = &rest[value_start + length + 1..];
939    }
940    attributes
941}
942/// Deliver mail to the session a relay speaks for. When it lives on another
943/// machine and Teams cannot take the message there, it is kept in this
944/// machine's copy of that mailbox (never dropped) and the failure is written
945fn deliver_home(represented: &MailAddress, envelope: &Envelope) {
946    if let Err(error) = crate::mailbox::deliver_to(represented, envelope) {
947        eprintln!(
948            "could not deliver {} to {represented}: {error}; kept in this machine's mailbox for it",
949            envelope.id
950        );
951        if let Ok(mailbox) = crate::mailbox::Mailbox::open(&mail_root(), represented) {
952            mailbox.deliver(envelope).ok();
953        }
954        return;
955    }
956    // Filed; now hand it to its session by the session's own door, as any
957    // sender's message is (a Claude session gets it at its next tool round).
958    // That can take as long as a relay send, which this hook must not wait
959    // on, so a detached `message push` does it.
960    if represented.machine == crate::mailbox::local_machine_name() {
961        if let Ok(program) = supercode_program() {
962            std::process::Command::new(program)
963                .args(["message", "push", &represented.to_string(), &envelope.id])
964                .stdin(std::process::Stdio::null())
965                .stdout(std::process::Stdio::null())
966                .stderr(std::process::Stdio::null())
967                .spawn()
968                .ok();
969        }
970    }
971}
972fn file_inbound(
973    represented: &MailAddress,
974    native: &NativeEnvelope,
975    sender: Option<&ClaudePeerSession>,
976    in_reply_to: Option<String>,
977) {
978    // The replying Claude session runs beside the relay, on this machine —
979    // not on the machine of the session the relay speaks for.
980    let machine = crate::mailbox::local_machine_name();
981    let (from, from_name) = match sender {
982        Some(session) => (
983            MailAddress::new(&machine, "claude-code", &session.session_id),
984            format!("{}@{machine}", session.name),
985        ),
986        None => (
987            MailAddress::new(&machine, "claude-code", "unknown"),
988            native
989                .from_name
990                .clone()
991                .unwrap_or_else(|| "an unknown Claude session".into()),
992        ),
993    };
994    let Ok(from) = from else { return };
995    let Ok(mut envelope) = Envelope::new(
996        from,
997        from_name,
998        MailKind::Peer,
999        ReplyVia::Command,
1000        native.body.clone(),
1001    ) else {
1002        return;
1003    };
1004    envelope.native_from = Some(native.from.clone());
1005    if let Some(in_reply_to) = in_reply_to {
1006        envelope.thread = crate::mailbox::thread_of_reply(Some(&in_reply_to));
1007        envelope.in_reply_to = Some(in_reply_to);
1008        envelope.in_reply_to_inferred = true;
1009    }
1010    // The session a relay speaks for may be on another machine; its mail goes
1011    // home through Teams.
1012    deliver_home(represented, &envelope);
1013}
1014fn file_notice(represented: &MailAddress, text: &str) {
1015    let Ok(from) = MailAddress::new(
1016        crate::mailbox::local_machine_name(),
1017        "claude-code",
1018        "notice",
1019    ) else {
1020        return;
1021    };
1022    let Ok(envelope) = Envelope::new(
1023        from,
1024        "Claude Code",
1025        MailKind::Notice,
1026        ReplyVia::None,
1027        text.to_string(),
1028    ) else {
1029        return;
1030    };
1031    // The session a relay speaks for may be on another machine; its mail goes
1032    // home through Teams.
1033    deliver_home(represented, &envelope);
1034}
1035/// The `supercode` program that the relay hooks and the machine daemon run:
1036/// this process when it is `supercode` (the CLI, `supercode harness serve`),
1037pub fn supercode_program() -> std::io::Result<PathBuf> {
1038    let current = std::env::current_exe()?;
1039    if current.file_stem().and_then(|stem| stem.to_str()) == Some("supercode") {
1040        return Ok(current);
1041    }
1042    std::env::var_os("PATH")
1043        .iter()
1044        .flat_map(std::env::split_paths)
1045        .map(|directory| directory.join("supercode"))
1046        .find(|candidate| candidate.is_file())
1047        .ok_or_else(|| {
1048            std::io::Error::new(
1049                std::io::ErrorKind::NotFound,
1050                "the supercode program is not on PATH; Claude relays and the machine daemon need it",
1051            )
1052        })
1053}